Skip to content

OpenToonz - An open-source full-featured 2D animation creation software

C

Add Toonz Preview Thumbnail Provider

Abel You0454fb827226
diff --git a/stuff/config/icon/paletteIcon.ico b/stuff/config/icon/paletteIcon.ico
new file mode 100644
index 000000000..4c7df65da
Binary files /dev/null and b/stuff/config/icon/paletteIcon.ico differ
diff --git a/toonz/sources/CMakeLists.txt b/toonz/sources/CMakeLists.txt
index bb4313717..b25c8b0aa 100644
--- a/toonz/sources/CMakeLists.txt
+++ b/toonz/sources/CMakeLists.txt
@@ -784,6 +784,10 @@ add_subdirectory(tcomposer)
add_subdirectory(tconverter)
add_subdirectory(toonzfarm)
+if(BUILD_TARGET_WIN)
+ add_subdirectory(toonzpreview)
+endif()
+
if(BUILD_ENV_APPLE)
add_subdirectory(mousedragfilter)
endif()
diff --git a/toonz/sources/common/trasterimage/tcodec.cpp b/toonz/sources/common/trasterimage/tcodec.cpp
index 224b73b20..787dd7b09 100644
--- a/toonz/sources/common/trasterimage/tcodec.cpp
+++ b/toonz/sources/common/trasterimage/tcodec.cpp
@@ -570,7 +570,17 @@ void TRasterCodecLz4::decompress(const TRasterP &compressedRas,
namespace {
bool lzoCompress(const QByteArray src, QByteArray &dst) {
+#ifdef _WIN32
+ QDir exeDir;
+ if (QCoreApplication::applicationName() == "ToonzPreview") {
+ QStringList paths = QCoreApplication::libraryPaths();
+ exeDir = QDir(paths.first());
+ } else
+ exeDir = QDir(QCoreApplication::applicationDirPath());
+#else
QDir exeDir(QCoreApplication::applicationDirPath());
+#endif // _WIN32
+
QString compressExe = exeDir.filePath("lzocompress");
QProcess process;
process.start(compressExe, QStringList() << QString::number(src.size()));
@@ -582,7 +592,17 @@ bool lzoCompress(const QByteArray src, QByteArray &dst) {
}
bool lzoDecompress(const QByteArray src, int dstSize, QByteArray &dst) {
+#ifdef _WIN32
+ QDir exeDir;
+ if (QCoreApplication::applicationName() == "ToonzPreview") {
+ QStringList paths = QCoreApplication::libraryPaths();
+ exeDir = QDir(paths.first());
+ exeDir.cdUp();
+ } else
+ exeDir = QDir(QCoreApplication::applicationDirPath());
+#else
QDir exeDir(QCoreApplication::applicationDirPath());
+#endif // _WIN32
QString decompressExe = exeDir.filePath("lzodecompress");
QProcess process;
process.start(decompressExe, QStringList() << QString::number(dstSize)
@@ -593,7 +613,7 @@ bool lzoDecompress(const QByteArray src, int dstSize, QByteArray &dst) {
dst = process.readAll();
return process.exitCode() == 0 && dst.size() == dstSize;
}
-}
+} // namespace
//------------------------------------------------------------------------------
diff --git a/toonz/sources/common/tsystem/tfiletype.cpp b/toonz/sources/common/tsystem/tfiletype.cpp
index 0aff3a172..9d9aa0d7f 100644
--- a/toonz/sources/common/tsystem/tfiletype.cpp
+++ b/toonz/sources/common/tsystem/tfiletype.cpp
@@ -41,8 +41,10 @@ TFileType::Type TFileType::getInfo(const TFilePath &fp) {
//--------------------------------------------------------------------------------
TFileType::Type TFileType::getInfoFromExtension(const std::string &extension) {
+ std::string extLower = extension;
+ std::transform(extLower.begin(), extLower.end(), extLower.begin(), ::tolower);
FileTypeData *data = FileTypeData::instance();
- std::map<std::string, int>::iterator it = data->m_table.find(extension);
+ std::map<std::string, int>::iterator it = data->m_table.find(extLower);
int type = (it == data->m_table.end()) ? TFileType::UNKNOW_FILE : it->second;
return (TFileType::Type)type;
}
diff --git a/toonz/sources/toonz/preferencespopup.cpp b/toonz/sources/toonz/preferencespopup.cpp
index 4cd74ba34..2ee6cf83b 100644
--- a/toonz/sources/toonz/preferencespopup.cpp
+++ b/toonz/sources/toonz/preferencespopup.cpp
@@ -1583,6 +1583,9 @@ PreferencesPopup::PreferencesPopup()
<< tr("Animation") << tr("Auto Lip-Sync") << tr("Colors")
<< tr("Vector Visualize") << tr("Version Control")
<< tr("Touch/Tablet Settings");
+#ifdef _WIN32
+ categories << tr("Addons");
+#endif
categoryList->addItems(categories);
categoryList->setFixedWidth(160);
categoryList->setCurrentRow(0);
@@ -1605,6 +1608,9 @@ PreferencesPopup::PreferencesPopup()
stackedWidget->addWidget(createVisualizationPage());
stackedWidget->addWidget(createVersionControlPage());
stackedWidget->addWidget(createTouchTabletPage());
+#ifdef _WIN32
+ stackedWidget->addWidget(createAddonsPage());
+#endif // WIN32
QHBoxLayout* mainLayout = new QHBoxLayout();
mainLayout->setContentsMargins(0, 0, 0, 0);
@@ -2478,6 +2484,92 @@ QWidget* PreferencesPopup::createTouchTabletPage() {
return widget;
}
+#ifdef _WIN32
+#include <windows.h>
+QWidget* PreferencesPopup::createAddonsPage() {
+ QWidget* widget = new QWidget(this);
+ QGridLayout* lay = new QGridLayout();
+
+ static auto CheckToonzPreview = []() -> bool {
+ HKEY h;
+ bool r = RegOpenKeyW(HKEY_CLASSES_ROOT,
+ L"CLSID\\{A20E2270-0FE1-421D-A34E-98C26C13F9DB}",
+ &h) == ERROR_SUCCESS;
+ if (r) RegCloseKey(h);
+ return r;
+ };
+
+ QGroupBox* groupBox =
+ new QGroupBox(tr("Windows Explorer Thumbnails (Shell Extension)"));
+ QVBoxLayout* gbLayout = new QVBoxLayout(groupBox);
+ gbLayout->setMargin(10);
+
+ QLabel* infoLabel =
+ new QLabel(tr("Enable thumbnails for OpenToonz files (.tnz, .pli, .tlv) "
+ "in Windows Explorer. \n"
+ "Administrator privileges are required; you may need to "
+ "restart Explorer for changes to take effect."));
+ gbLayout->addWidget(infoLabel);
+
+ QPushButton* previewButton = new QPushButton(this);
+ previewButton->setText(CheckToonzPreview() ? tr("Uninstall") : tr("Install"));
+
+ gbLayout->addWidget(previewButton);
+
+ connect(previewButton, &QPushButton::clicked, this, [previewButton]() {
+ bool install = !CheckToonzPreview();
+ QString dllPath_raw =
+ QApplication::applicationDirPath() + "/toonzpreview.dll";
+
+ QString dllPath = dllPath_raw.replace("/", "\\");
+
+ if (install && !QFile::exists(dllPath)) {
+ DVGui::warning("toonzpreview.dll not found!");
+ return;
+ }
+
+ QString quotedDllPath = QString("\"%1\"").arg(dllPath);
+
+ QStringList args =
+ install ? QStringList{quotedDllPath} : QStringList{"/u", quotedDllPath};
+
+ QString command = "regsvr32";
+
+ QString paramStr = args.join(" ");
+
+ SHELLEXECUTEINFO sei = {sizeof(sei)};
+
+ sei.lpVerb = L"runas";
+
+ std::wstring commandW = command.toStdWString();
+ std::wstring paramStrW = paramStr.toStdWString();
+
+ sei.hProcess = NULL;
+ sei.lpFile = commandW.c_str(); // regsvr32.exe
+ sei.lpParameters = paramStrW.c_str(); // param
+ sei.nShow = SW_SHOWNORMAL; // UAC
+ sei.fMask = SEE_MASK_NOCLOSEPROCESS;
+
+ bool operationSuccess = false;
+ if (ShellExecuteEx(&sei)) {
+ if (sei.hProcess) {
+ WaitForSingleObject(sei.hProcess, 60000);
+ }
+ }
+
+ previewButton->setText(CheckToonzPreview() ? tr("Uninstall")
+ : tr("Install"));
+ });
+
+ lay->addWidget(groupBox, lay->rowCount(), 0, 2, 4, Qt::AlignLeft);
+ lay->setRowStretch(lay->rowCount(), 1);
+
+ widget->setLayout(lay);
+
+ return widget;
+}
+#endif // _WIN32
+
//-----------------------------------------------------------------------------
void PreferencesPopup::onChange() {
diff --git a/toonz/sources/toonz/preferencespopup.h b/toonz/sources/toonz/preferencespopup.h
index e90ae3b13..432b6ef85 100644
--- a/toonz/sources/toonz/preferencespopup.h
+++ b/toonz/sources/toonz/preferencespopup.h
@@ -118,7 +118,9 @@ private:
QWidget* createColorsPage();
QWidget* createVersionControlPage();
QWidget* createTouchTabletPage();
-
+#ifdef _WIN32
+ QWidget* createAddonsPage();
+#endif
//--- callbacks ---
// General
void onAutoSaveChanged();
diff --git a/toonz/sources/toonzpreview/CMakeLists.txt b/toonz/sources/toonzpreview/CMakeLists.txt
new file mode 100644
index 000000000..988774af5
--- /dev/null
+++ b/toonz/sources/toonzpreview/CMakeLists.txt
@@ -0,0 +1,42 @@
+set(PREVIEW_SOURCES
+ toonzpreview.cpp
+ toonzpreview.def
+)
+
+set(PREVIEW_HEADERS
+ toonzpreview.h
+)
+
+add_library(toonzpreview SHARED ${PREVIEW_SOURCES} ${PREVIEW_HEADERS})
+
+target_compile_definitions(toonzpreview PRIVATE
+ TOONZPREVIEW_EXPORTS
+ _ATL_NO_AUTOMATIC_NAMESPACE
+ UNICODE
+ _UNICODE
+)
+
+message("subdir: toonz")
+message("Bin: " ${CMAKE_CURRENT_BINARY_DIR})
+
+target_include_directories(toonzpreview PRIVATE
+ ../include/toonzqt
+ ../include/toonz
+ ../include/tcg
+ ${Qt5Widgets_INCLUDE_DIRS}
+)
+
+target_link_libraries(toonzpreview PRIVATE
+ image
+ toonzqt
+ shlwapi
+ tnzcore
+ Qt5::Core
+ ${OpenCV_LIBS}
+)
+
+set_target_properties(toonzpreview PROPERTIES
+ PREFIX ""
+ SUFFIX ".dll"
+ OUTPUT_NAME "toonzpreview"
+)
\ No newline at end of file
diff --git a/toonz/sources/toonzpreview/toonzpreview.cpp b/toonz/sources/toonzpreview/toonzpreview.cpp
new file mode 100644
index 000000000..b1554fe20
--- /dev/null
+++ b/toonz/sources/toonzpreview/toonzpreview.cpp
@@ -0,0 +1,976 @@
+// toonzpreview.cpp
+#include "toonzpreview.h"
+#include "tiio.h"
+#include "tiio_std.h"
+#include "tnzimage.h"
+
+#include "toonzqt/icongenerator.h"
+#include "timagecache.h"
+#include "tfilepath.h"
+#include "traster.h"
+#include "tpixel.h"
+
+// Qt Includes
+#include <QCoreApplication>
+#include <QDebug>
+#include <QDir>
+
+#include <shlwapi.h>
+#include <propkey.h>
+#include <string>
+#include <vector>
+#include <memory>
+#include <fstream>
+#include <codecvt>
+#include <locale>
+#include <mutex>
+#include "tenv.h"
+
+#pragma comment(lib, "shlwapi.lib")
+// Ensure we link against the standard UUIDs
+#pragma comment(lib, "uuid.lib")
+
+// Global Variables
+long g_cDllRef = 0;
+HINSTANCE g_hInst = NULL;
+const wchar_t *exts[] = {L".tnz", L".tlv", L".pli", L".tga"};
+const wchar_t *progId = L"OpenToonz.ToonzPreview";
+const int EXT_COUNT = 4;
+
+// CONSTANTS FOR REGISTRY
+// This is the Standard Windows Interface ID for IThumbnailProvider.
+// DO NOT CHANGE THIS. It must match system expectations.
+const wchar_t *SZ_ITHUMBNAILPROVIDER_IID =
+ L"{e357fccd-a995-4576-b01f-234630154e96}";
+
+#ifdef TOONZPREVIW_DEBUG
+void DebugLog(const std::string &message) {
+ std::string fullMessage = "[ToonzPreview] " + message + "\n";
+ OutputDebugStringA(fullMessage.c_str());
+
+ WCHAR dllPath[MAX_PATH];
+ if (GetModuleFileNameW(g_hInst, dllPath, MAX_PATH)) {
+ WCHAR logFilePath[MAX_PATH];
+ wcscpy_s(logFilePath, MAX_PATH, dllPath);
+ PathRemoveFileSpecW(logFilePath);
+ wcscat_s(logFilePath, MAX_PATH, L"\\toonz_preview.log");
+
+ std::wstring_convert<std::codecvt_utf8<wchar_t>> converter;
+ std::string narrowLogPath = converter.to_bytes(logFilePath);
+
+ std::ofstream logfile(narrowLogPath, std::ios::app);
+ if (logfile.is_open()) {
+ logfile << "[" << GetCurrentProcessId() << ":" << GetCurrentThreadId()
+ << "] " << message << std::endl;
+ }
+ }
+}
+
+#else
+void DebugLog(const std::string &message) {
+ // No operation in release builds
+}
+#endif // TOONZPREVIW_DEBUG
+
+TFilePath getPaletteIconPath() {
+ return TEnv::getConfigDir() + "icon" + "paletteIcon.ico";
+}
+
+std::string WideToNarrow(const std::wstring &wideStr) {
+ if (wideStr.empty()) return "";
+ int size_needed = WideCharToMultiByte(
+ CP_UTF8, 0, wideStr.c_str(), (int)wideStr.size(), NULL, 0, NULL, NULL);
+ if (size_needed == 0) return "";
+ std::string narrowStr(size_needed, 0);
+ WideCharToMultiByte(CP_UTF8, 0, wideStr.c_str(), (int)wideStr.size(),
+ &narrowStr[0], size_needed, NULL, NULL);
+ return narrowStr;
+}
+
+// ---------------------------------------------------------------------------
+// Process Isolation Implementation
+// ---------------------------------------------------------------------------
+
+bool SetDisableProcessIsolation() {
+ std::wstring keyPath = L"CLSID\\";
+ keyPath += SZ_CLSID_TOONZPREVIEW;
+ // Correction: Do not append "\\InprocServer32".
+ // DisableProcessIsolation is a direct property of CLSID, not the DLL.
+
+ HKEY hKey = NULL;
+ // Attempt to open the CLSID\{GUID} key
+ LSTATUS status = RegOpenKeyExW(HKEY_CLASSES_ROOT, keyPath.c_str(), 0,
+ KEY_SET_VALUE, &hKey);
+
+ if (status != ERROR_SUCCESS) {
+ DebugLog("Failed to open CLSID key for DisableProcessIsolation.");
+ return false;
+ }
+
+ DWORD dwData = 1;
+ // Set the DisableProcessIsolation key value (DWORD = 1)
+ status = RegSetValueExW(hKey, L"DisableProcessIsolation", 0, REG_DWORD,
+ (const BYTE *)&dwData, sizeof(dwData));
+
+ RegCloseKey(hKey);
+
+ if (status != ERROR_SUCCESS) {
+ DebugLog("Failed to set DisableProcessIsolation value.");
+ return false;
+ }
+
+ DebugLog("Successfully set DisableProcessIsolation=1.");
+ return true;
+}
+
+/**
+ * @brief Clears the DisableProcessIsolation value from the registry.
+ */
+bool ClearDisableProcessIsolation() {
+ std::wstring keyPath = L"CLSID\\";
+ keyPath += SZ_CLSID_TOONZPREVIEW;
+ // Correction: Do not append "\\InprocServer32".
+
+ HKEY hKey = NULL;
+ LSTATUS status = RegOpenKeyExW(HKEY_CLASSES_ROOT, keyPath.c_str(), 0,
+ KEY_SET_VALUE | KEY_QUERY_VALUE, &hKey);
+
+ if (status != ERROR_SUCCESS) {
+ // If the key itself doesn't exist, no cleanup is needed, return true
+ return true;
+ }
+
+ // Delete the DisableProcessIsolation value
+ status = RegDeleteValueW(hKey, L"DisableProcessIsolation");
+
+ RegCloseKey(hKey);
+
+ // ERROR_FILE_NOT_FOUND means the value did not exist in the first place,
+ // which is also a success
+ if (status != ERROR_SUCCESS && status != ERROR_FILE_NOT_FOUND) {
+ DebugLog("Failed to delete DisableProcessIsolation value.");
+ return false;
+ }
+
+ DebugLog("Successfully cleared DisableProcessIsolation.");
+ return true;
+}
+
+void EnsureQtApplication() {
+ static std::once_flag qtInitFlag;
+ std::call_once(qtInitFlag, []() {
+ if (QCoreApplication::instance()) {
+ DebugLog("Qt application already exists");
+ } else {
+ DebugLog("Starting Qt application initialization...");
+
+ // Get the path of our DLL
+ WCHAR dllPath[MAX_PATH];
+ if (GetModuleFileNameW(g_hInst, dllPath, MAX_PATH)) {
+ DebugLog("DLL path: " + WideToNarrow(dllPath));
+
+ // Get the DLL's directory (e.g., E:\)
+ WCHAR dllDir[MAX_PATH];
+ wcscpy_s(dllDir, MAX_PATH, dllPath);
+ PathRemoveFileSpecW(dllDir);
+ std::string dllDirNarrow = WideToNarrow(dllDir);
+ DebugLog("DLL directory: " + dllDirNarrow);
+
+ QCoreApplication::setAttribute(Qt::AA_DisableHighDpiScaling);
+ QCoreApplication::setAttribute(Qt::AA_UseSoftwareOpenGL);
+
+ DebugLog("Creating QCoreApplication...");
+
+ try {
+ static int argc = 1;
+ static char *argv[] = {(char *)"toonzpreview_host", nullptr};
+ static QCoreApplication app(argc, argv);
+
+ QCoreApplication::setApplicationName("ToonzPreview");
+ QCoreApplication::setOrganizationName("OpenToonz");
+
+ DebugLog("QCoreApplication created successfully");
+
+ QString baseDir = QString::fromStdWString(dllDir);
+
+ QCoreApplication::addLibraryPath(baseDir);
+ DebugLog("Added base directory to library paths: " +
+ baseDir.toStdString());
+
+ QStringList pluginSubdirs = {
+ "audio", // qtaudio_windows.dll
+ "bearer", // qgenericbearer.dll
+ "iconengines", // qsvgicon.dll
+ "imageformats", // qjpeg.dll, qsvg.dll..
+ "mediaservice", // dsengine.dll..
+ "platforms", // qwindows.dll
+ "playlistformats", // qtmultimedia_m3u.dll
+ "printsupport", // windowsprintersupport.dll
+ "styles" // qwindowsvistastyle.dll
+ };
+
+ for (const QString &subdir : pluginSubdirs) {
+ QString fullPath = baseDir + "/" + subdir;
+ if (QDir(fullPath).exists()) {
+ QCoreApplication::addLibraryPath(fullPath);
+ DebugLog("Added plugin directory: " + fullPath.toStdString());
+ } else {
+ DebugLog("WARNING: Plugin directory not found: " +
+ fullPath.toStdString());
+ }
+ }
+
+ QStringList libraryPaths = QCoreApplication::libraryPaths();
+ DebugLog("Final Qt library paths (" +
+ QString::number(libraryPaths.size()).toStdString() + "):");
+ for (const QString &path : libraryPaths) {
+ DebugLog(" " + path.toStdString());
+ }
+
+ } catch (const std::exception &e) {
+ DebugLog("Exception during QCoreApplication creation: " +
+ std::string(e.what()));
+ return;
+ } catch (...) {
+ DebugLog("Unknown exception during QCoreApplication creation");
+ return;
+ }
+
+ } else {
+ DebugLog("Error: Could not get DLL path.");
+ }
+ DebugLog(
+ "Qt application initialization completed successfully without "
+ "environment variables");
+ }
+ });
+}
+HBITMAP RasterToHBITMAP(const TRaster32P &ras) {
+ if (!ras || !ras->getRawData()) {
+ DebugLog("RasterToHBITMAP: Invalid raster data");
+ return NULL;
+ }
+
+ int w = ras->getLx();
+ int h = ras->getLy();
+
+ if (w <= 0 || h <= 0) return NULL;
+
+ BITMAPINFO bmi = {0};
+ bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
+ bmi.bmiHeader.biWidth = w;
+ bmi.bmiHeader.biHeight = h;
+ bmi.bmiHeader.biPlanes = 1;
+ bmi.bmiHeader.biBitCount = 32;
+ bmi.bmiHeader.biCompression = BI_RGB;
+ bmi.bmiHeader.biSizeImage = w * h * 4;
+
+ void *pBits = NULL;
+ HDC hdc = GetDC(NULL);
+ HBITMAP hBmp = CreateDIBSection(hdc, &bmi, DIB_RGB_COLORS, &pBits, NULL, 0);
+ ReleaseDC(NULL, hdc);
+
+ if (!hBmp || !pBits) return NULL;
+
+ ras->lock();
+ const unsigned char *srcPixels = ras->getRawData();
+ if (srcPixels) {
+ memcpy(pBits, srcPixels, w * h * 4);
+ } else {
+ DeleteObject(hBmp);
+ hBmp = NULL;
+ }
+ ras->unlock();
+ return hBmp;
+}
+
+void SetupDependencyPath(HMODULE hModule) {
+ WCHAR dllPath[MAX_PATH];
+ if (GetModuleFileNameW(hModule, dllPath, MAX_PATH)) {
+ PathRemoveFileSpecW(dllPath);
+ SetDllDirectoryW(dllPath);
+ }
+}
+void LoadDependencies() {
+ static HMODULE hToonzQt = NULL;
+ static HMODULE hTnzCore = NULL;
+ static HMODULE hImage = NULL;
+
+ // Keep these DLLs resident in memory
+ WCHAR dllDir[MAX_PATH];
+ GetModuleFileNameW(g_hInst, dllDir, MAX_PATH);
+ PathRemoveFileSpecW(dllDir);
+
+ auto LoadDep = [&](const wchar_t *name) -> HMODULE {
+ WCHAR path[MAX_PATH];
+ wcscpy_s(path, dllDir);
+ wcscat_s(path, L"\\");
+ wcscat_s(path, name);
+ return LoadLibraryW(path);
+ };
+
+ hToonzQt = LoadDep(L"toonzqt.dll");
+ hTnzCore = LoadDep(L"tnzcore.dll");
+ hImage = LoadDep(L"image.dll");
+}
+// ---------------------------------------------------------------------------
+// DLL Entry Point
+// ---------------------------------------------------------------------------
+BOOL APIENTRY DllMain(HMODULE hModule, DWORD ul_reason_for_call,
+ LPVOID lpReserved) {
+ static HMODULE hToonzQt = NULL;
+ static HMODULE hTnzCore = NULL;
+ static HMODULE hImage = NULL;
+
+ switch (ul_reason_for_call) {
+ case DLL_PROCESS_ATTACH: {
+ g_hInst = hModule;
+
+ SetupDependencyPath(hModule);
+
+ DisableThreadLibraryCalls(hModule);
+ DebugLog("DLL_PROCESS_ATTACH - Path Set & ToonzPreview loaded");
+ break;
+ }
+ case DLL_PROCESS_DETACH:
+
+ DebugLog("DLL_PROCESS_DETACH");
+ break;
+ }
+ return TRUE;
+}
+
+// ---------------------------------------------------------------------------
+// DLL Exports
+// ---------------------------------------------------------------------------
+STDAPI DllCanUnloadNow() { return (g_cDllRef > 0) ? S_FALSE : S_OK; }
+
+STDAPI DllGetClassObject(REFCLSID rclsid, REFIID riid, void **ppv) {
+ DebugLog("DllGetClassObject called");
+ if (!IsEqualCLSID(rclsid, CLSID_ToonzThumbnailProvider)) {
+ return CLASS_E_CLASSNOTAVAILABLE;
+ }
+ CClassFactory *pFactory = new CClassFactory();
+ if (!pFactory) return E_OUTOFMEMORY;
+
+ HRESULT hr = pFactory->QueryInterface(riid, ppv);
+ pFactory->Release();
+ return hr;
+}
+
+HRESULT RegisterRegistryKeys() {
+ WCHAR modulePath[MAX_PATH];
+ if (!GetModuleFileNameW(g_hInst, modulePath, MAX_PATH)) return E_FAIL;
+
+ // Key: HKLM\SOFTWARE\Classes\CLSID\{SZ_CLSID_TOONZPREVIEW}
+ std::wstring clsidKey =
+ std::wstring(L"SOFTWARE\\Classes\\CLSID\\") + SZ_CLSID_TOONZPREVIEW;
+ HKEY hKey;
+ LONG lResult =
+ RegCreateKeyExW(HKEY_LOCAL_MACHINE, clsidKey.c_str(), 0, NULL,
+ REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hKey, NULL);
+ if (lResult == ERROR_SUCCESS) {
+ RegSetValueExW(hKey, NULL, 0, REG_SZ, (BYTE *)L"Toonz Thumbnail Provider",
+ (wcslen(L"Toonz Thumbnail Provider") + 1) * sizeof(WCHAR));
+
+ // AppID
+ RegSetValueExW(hKey, L"AppID", 0, REG_SZ, (BYTE *)SZ_CLSID_TOONZPREVIEW,
+ (wcslen(SZ_CLSID_TOONZPREVIEW) + 1) * sizeof(WCHAR));
+
+ HKEY hInProc;
+ if (RegCreateKeyExW(hKey, L"InProcServer32", 0, NULL,
+ REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hInProc,
+ NULL) == ERROR_SUCCESS) {
+ RegSetValueExW(hInProc, NULL, 0, REG_SZ, (BYTE *)modulePath,
+ (wcslen(modulePath) + 1) * sizeof(WCHAR));
+ RegSetValueExW(hInProc, L"ThreadingModel", 0, REG_SZ,
+ (BYTE *)L"Apartment",
+ (wcslen(L"Apartment") + 1) * sizeof(WCHAR));
+ RegCloseKey(hInProc);
+ }
+ RegCloseKey(hKey);
+ }
+
+ // Key: HKLM\SOFTWARE\Classes\{progId}
+ std::wstring typeKey = std::wstring(L"SOFTWARE\\Classes\\") + progId;
+ if (RegCreateKeyExW(HKEY_LOCAL_MACHINE, typeKey.c_str(), 0, NULL,
+ REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hKey,
+ NULL) == ERROR_SUCCESS) {
+ RegSetValueExW(hKey, NULL, 0, REG_SZ, (BYTE *)progId,
+ (wcslen(progId) + 1) * sizeof(WCHAR));
+ RegCloseKey(hKey);
+
+ bool installTGA = true;
+ for (int i = 0; i < EXT_COUNT; i++) {
+ if (wcscmp(exts[i], L".tga") == 0) {
+ int result = MessageBoxW(
+ NULL,
+ L"Do you want to install thumbnail handler for .tga file type?",
+ L"Confirm Installation", MB_YESNO | MB_ICONQUESTION);
+
+ if (result != IDYES) {
+ installTGA = false;
+ DebugLog("User canceled TGA file type registration");
+ continue;
+ }
+ }
+ }
+
+ // Key: HKLM\SOFTWARE\Classes\{progId}\ShellEx\{SZ_ITHUMBNAILPROVIDER_IID}
+ std::wstring shellExKey = std::wstring(L"SOFTWARE\\Classes\\") + progId +
+ L"\\ShellEx\\" + SZ_ITHUMBNAILPROVIDER_IID;
+
+ if (RegCreateKeyExW(HKEY_LOCAL_MACHINE, shellExKey.c_str(), 0, NULL,
+ REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hKey,
+ NULL) == ERROR_SUCCESS) {
+ RegSetValueExW(hKey, NULL, 0, REG_SZ, (BYTE *)SZ_CLSID_TOONZPREVIEW,
+ (wcslen(SZ_CLSID_TOONZPREVIEW) + 1) * sizeof(WCHAR));
+ RegCloseKey(hKey);
+ DebugLog("Registered thumbnail handler for " +
+ WideToNarrow(exts[EXT_COUNT - 1]));
+ }
+
+ for (int i = 0; i < EXT_COUNT; i++) {
+ if (wcscmp(exts[i], L".tga") == 0 && !installTGA) {
+ continue;
+ }
+
+ // Key:
+ // HKLM\SOFTWARE\Classes\SystemFileAssociations\{exts[i]}\ShellEx\{SZ_ITHUMBNAILPROVIDER_IID}
+ std::wstring sysKeyPath =
+ std::wstring(L"SOFTWARE\\Classes\\SystemFileAssociations\\") +
+ exts[i] + L"\\ShellEx\\" + SZ_ITHUMBNAILPROVIDER_IID;
+
+ if (RegCreateKeyExW(HKEY_LOCAL_MACHINE, sysKeyPath.c_str(), 0, NULL,
+ REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hKey,
+ NULL) == ERROR_SUCCESS) {
+ RegSetValueExW(hKey, NULL, 0, REG_SZ, (BYTE *)SZ_CLSID_TOONZPREVIEW,
+ (wcslen(SZ_CLSID_TOONZPREVIEW) + 1) * sizeof(WCHAR));
+ RegCloseKey(hKey);
+ DebugLog("Registered SystemFileAssociations for " +
+ WideToNarrow(exts[i]));
+ }
+ }
+ }
+
+ // Key: HKLM\SOFTWARE\Classes\.tpl\DefaultIcon
+ std::wstring tplIconKey = L"SOFTWARE\\Classes\\.tpl\\DefaultIcon";
+ if (RegCreateKeyExW(HKEY_LOCAL_MACHINE, tplIconKey.c_str(), 0, NULL,
+ REG_OPTION_NON_VOLATILE, KEY_WRITE, NULL, &hKey,
+ NULL) == ERROR_SUCCESS) {
+ TFilePath paletteIconPath = getPaletteIconPath();
+ std::wstring iconPathW = paletteIconPath.getWideString();
+
+ RegSetValueExW(hKey, NULL, 0, REG_SZ, (BYTE *)iconPathW.c_str(),
+ (iconPathW.length() + 1) * sizeof(WCHAR));
+
+ RegCloseKey(hKey);
+ DebugLog("Registered DefaultIcon for .tpl: " + WideToNarrow(iconPathW));
+ }
+
+ return S_OK;
+}
+
+STDAPI DllRegisterServer() {
+ DebugLog("DllRegisterServer called");
+ HRESULT hr = RegisterRegistryKeys();
+
+ // Critical Step: After successful COM registration, set to disable process
+ // isolation
+ if (SUCCEEDED(hr)) {
+ if (!SetDisableProcessIsolation()) {
+ DebugLog(
+ "WARNING: Failed to set DisableProcessIsolation=1. "
+ "IInitializeWithFile may not be called.");
+ // Do not return E_FAIL, allow registration to continue but log a warning
+ }
+ }
+
+ SHChangeNotify(SHCNE_UPDATEIMAGE, SHCNF_DWORD | SHCNF_FLUSH, NULL, NULL);
+ system("ie4uinit.exe -show");
+ return hr;
+}
+
+STDAPI DllUnregisterServer() {
+ DebugLog("DllUnregisterServer called");
+
+ ClearDisableProcessIsolation();
+
+ std::wstring clsidKey =
+ std::wstring(L"SOFTWARE\\Classes\\CLSID\\") + SZ_CLSID_TOONZPREVIEW;
+ HKEY hTestKey;
+ if (RegOpenKeyExW(HKEY_LOCAL_MACHINE, clsidKey.c_str(), 0, KEY_READ,
+ &hTestKey) == ERROR_SUCCESS) {
+ RegCloseKey(hTestKey);
+ RegDeleteTreeW(HKEY_LOCAL_MACHINE, clsidKey.c_str());
+ }
+
+ std::wstring shellExKey = std::wstring(L"SOFTWARE\\Classes\\") + progId +
+ L"\\ShellEx\\" + SZ_ITHUMBNAILPROVIDER_IID;
+ if (RegOpenKeyExW(HKEY_LOCAL_MACHINE, shellExKey.c_str(), 0, KEY_READ,
+ &hTestKey) == ERROR_SUCCESS) {
+ RegCloseKey(hTestKey);
+ RegDeleteTreeW(HKEY_LOCAL_MACHINE, shellExKey.c_str());
+ }
+
+ std::wstring progIDPath = L"SOFTWARE\\Classes\\" + std::wstring(progId);
+ if (RegOpenKeyExW(HKEY_LOCAL_MACHINE, progIDPath.c_str(), 0, KEY_READ,
+ &hTestKey) == ERROR_SUCCESS) {
+ RegCloseKey(hTestKey);
+ WCHAR existingValue[100];
+ DWORD dataSize = sizeof(existingValue);
+ if (RegGetValueW(HKEY_LOCAL_MACHINE, progIDPath.c_str(), NULL,
+ RRF_RT_REG_SZ, NULL, existingValue,
+ &dataSize) == ERROR_SUCCESS) {
+ if (wcscmp(existingValue, progId) == 0) {
+ RegDeleteKeyW(HKEY_LOCAL_MACHINE, progIDPath.c_str());
+ }
+ }
+ }
+
+ for (int i = 0; i < EXT_COUNT; i++) {
+ std::wstring sysKeyPath =
+ std::wstring(L"SOFTWARE\\Classes\\SystemFileAssociations\\") + exts[i] +
+ L"\\ShellEx\\" + SZ_ITHUMBNAILPROVIDER_IID;
+ if (RegOpenKeyExW(HKEY_LOCAL_MACHINE, sysKeyPath.c_str(), 0, KEY_READ,
+ &hTestKey) == ERROR_SUCCESS) {
+ RegCloseKey(hTestKey);
+ WCHAR existingClsid[100];
+ DWORD dataSize = sizeof(existingClsid);
+ if (RegGetValueW(HKEY_LOCAL_MACHINE, sysKeyPath.c_str(), NULL,
+ RRF_RT_REG_SZ, NULL, existingClsid,
+ &dataSize) == ERROR_SUCCESS) {
+ if (wcscmp(existingClsid, SZ_CLSID_TOONZPREVIEW) == 0) {
+ RegDeleteKeyW(HKEY_LOCAL_MACHINE, sysKeyPath.c_str());
+ }
+ }
+ }
+
+ std::wstring extPath = L"SOFTWARE\\Classes\\" + std::wstring(exts[i]);
+ if (RegOpenKeyExW(HKEY_LOCAL_MACHINE, extPath.c_str(), 0, KEY_READ,
+ &hTestKey) == ERROR_SUCCESS) {
+ RegCloseKey(hTestKey);
+ WCHAR existingValue[100];
+ DWORD dataSize = sizeof(existingValue);
+ if (RegGetValueW(HKEY_LOCAL_MACHINE, extPath.c_str(), NULL, RRF_RT_REG_SZ,
+ NULL, existingValue, &dataSize) == ERROR_SUCCESS) {
+ if (wcscmp(existingValue, progId) == 0) {
+ RegDeleteKeyW(HKEY_LOCAL_MACHINE, extPath.c_str());
+ }
+ }
+ }
+ }
+
+ std::wstring tplIconKey = L"SOFTWARE\\Classes\\.tpl\\DefaultIcon";
+ if (RegOpenKeyExW(HKEY_LOCAL_MACHINE, tplIconKey.c_str(), 0, KEY_READ,
+ &hTestKey) == ERROR_SUCCESS) {
+ RegCloseKey(hTestKey);
+ RegDeleteKeyW(HKEY_LOCAL_MACHINE, tplIconKey.c_str());
+ }
+
+ SHChangeNotify(SHCNE_UPDATEIMAGE, SHCNF_DWORD | SHCNF_FLUSH, NULL, NULL);
+ system("ie4uinit.exe -show");
+
+ return S_OK;
+}
+
+// ---------------------------------------------------------------------------
+// CToonzThumbnailProvider Implementation
+// ---------------------------------------------------------------------------
+CToonzThumbnailProvider::CToonzThumbnailProvider() : m_cRef(1) {
+ InterlockedIncrement(&g_cDllRef);
+ DebugLog("CToonzThumbnailProvider constructor called");
+}
+
+CToonzThumbnailProvider::~CToonzThumbnailProvider() {
+ InterlockedDecrement(&g_cDllRef);
+ DebugLog("CToonzThumbnailProvider destructor called");
+}
+
+IFACEMETHODIMP CToonzThumbnailProvider::QueryInterface(REFIID riid,
+ void **ppv) {
+ if (!ppv) return E_INVALIDARG;
+ *ppv = NULL;
+
+ DebugLog("=== QueryInterface Start ===");
+
+ LPOLESTR riidStr = NULL;
+ StringFromIID(riid, &riidStr);
+ std::wstring wriid(riidStr);
+ DebugLog("Requested IID: " + WideToNarrow(wriid));
+ CoTaskMemFree(riidStr);
+
+ // Completely manual interface query
+ if (IsEqualIID(riid, IID_IUnknown) ||
+ IsEqualIID(riid, IID_IThumbnailProvider) ||
+ IsEqualIID(riid, IID_IInitializeWithFile) ||
+ IsEqualIID(riid, IID_IPersistFile) || IsEqualIID(riid, IID_IPersist)) {
+ //|| IsEqualIID(riid, IID_IInitializeWithStream)) {
+ // Return the correct pointer based on the requested interface
+ if (IsEqualIID(riid, IID_IUnknown) ||
+ IsEqualIID(riid, IID_IThumbnailProvider)) {
+ DebugLog("Returning IThumbnailProvider interface");
+ *ppv = static_cast<IThumbnailProvider *>(this);
+ } else if (IsEqualIID(riid, IID_IInitializeWithFile)) {
+ DebugLog("Returning IInitializeWithFile interface");
+ *ppv = static_cast<IInitializeWithFile *>(this);
+ } else if (IsEqualIID(riid, IID_IPersistFile)) {
+ DebugLog("Returning IPersistFile interface");
+ *ppv = static_cast<IPersistFile *>(this);
+ } else if (IsEqualIID(riid, IID_IPersist)) {
+ DebugLog("Returning IPersist interface");
+ *ppv = static_cast<IPersist *>(this);
+ } else if (IsEqualIID(riid, IID_IInitializeWithStream)) {
+ DebugLog("Returning IInitializeWithStream interface");
+ *ppv = static_cast<IInitializeWithStream *>(this);
+ }
+
+ if (*ppv) {
+ AddRef();
+ DebugLog("QueryInterface SUCCEEDED");
+ DebugLog("=== QueryInterface End ===");
+ return S_OK;
+ }
+ }
+
+ DebugLog("Interface not supported");
+ DebugLog("=== QueryInterface End ===");
+ return E_NOINTERFACE;
+}
+
+IFACEMETHODIMP_(ULONG) CToonzThumbnailProvider::AddRef() {
+ return InterlockedIncrement(&m_cRef);
+}
+
+IFACEMETHODIMP_(ULONG) CToonzThumbnailProvider::Release() {
+ ULONG cRef = InterlockedDecrement(&m_cRef);
+ if (0 == cRef) delete this;
+ return cRef;
+}
+
+IFACEMETHODIMP CToonzThumbnailProvider::Initialize(LPCWSTR pszFilePath,
+ DWORD grfMode) {
+ DebugLog("IInitializeWithFile::Initialize called");
+
+ if (!pszFilePath) {
+ DebugLog("IInitializeWithFile::Initialize: pszFilePath is NULL");
+ return E_INVALIDARG;
+ }
+
+ m_filePath = pszFilePath;
+ DebugLog("IInitializeWithFile::Initialize: File path set to: " +
+ WideToNarrow(m_filePath));
+ DebugLog("IInitializeWithFile::Initialize: Mode: " + std::to_string(grfMode));
+
+ return S_OK;
+}
+
+/**
+ * @brief Attempts to extract the full path of the file from an IStream object.
+ * * This is a standard method to get the source file path in
+ * IInitializeWithStream::Initialize. It first tries IStream::Stat, then
+ * attempts the IPropertyStore interface.
+ *
+ * @param pStream The input IStream pointer.
+ * @return The extracted full file path; an empty string if unsuccessful.
+ */
+std::wstring GetFullPathFromStream(IStream *pStream) {
+ if (!pStream) {
+ DebugLog("GetFullPathFromStream: pStream is NULL.");
+ return L"";
+ }
+
+ std::wstring filePath;
+
+ // --- Method 1: Try to get path from STATSTG ---
+ STATSTG stat = {0};
+ HRESULT hr = pStream->Stat(&stat, STATFLAG_DEFAULT);
+
+ if (SUCCEEDED(hr) && stat.pwcsName) {
+ filePath = stat.pwcsName;
+ DebugLog("Method 1: Got name from STATSTG: " + WideToNarrow(filePath));
+
+ // Check if it's a full path (contains drive letter ':' or starts with root
+ // '\')
+ bool isFullPath = (filePath.find(L':') != std::wstring::npos) ||
+ (filePath.find(L'\\') == 0);
+
+ // If it's a full path, success, free memory and return
+ if (isFullPath) {
+ DebugLog("STATSTG path appears complete.");
+ CoTaskMemFree(stat.pwcsName);
+ return filePath;
+ }
+
+ // If it's not a full path (only filename), proceed to Method 2
+ DebugLog("STATSTG path is incomplete, attempting Method 2...");
+ CoTaskMemFree(stat.pwcsName); // Free memory allocated for stat.pwcsName
+ } else {
+ DebugLog(
+ "Method 1: Could not get STATSTG information or pwcsName is NULL.");
+ }
+
+ // --- Method 2: Try to get PKEY_ItemPathDisplay via IPropertyStore ---
+ IPropertyStore *pPropertyStore = nullptr;
+ HRESULT propHr = pStream->QueryInterface(IID_PPV_ARGS(&pPropertyStore));
+
+ if (SUCCEEDED(propHr) && pPropertyStore) {
+ PROPVARIANT propVar;
+ PropVariantInit(&propVar);
+
+ // Get the full file path property
+ propHr = pPropertyStore->GetValue(PKEY_ItemPathDisplay, &propVar);
+
+ if (SUCCEEDED(propHr) && propVar.vt == VT_LPWSTR && propVar.pwszVal) {
+ filePath = propVar.pwszVal;
+ DebugLog("Method 2: Got full path from IPropertyStore: " +
+ WideToNarrow(filePath));
+ } else {
+ DebugLog(
+ "Method 2: Failed to get PKEY_ItemPathDisplay or property type is "
+ "wrong.");
+ }
+
+ PropVariantClear(&propVar);
+ pPropertyStore->Release();
+ } else {
+ DebugLog("GetFullPathFromStream: Failed to query IPropertyStore.");
+ }
+
+ return filePath;
+}
+
+IFACEMETHODIMP CToonzThumbnailProvider::Initialize(IStream *pStream,
+ DWORD grfMode) {
+ DebugLog("IInitializeWithStream::Initialize called");
+
+ if (!pStream) {
+ DebugLog("IInitializeWithStream::Initialize: pStream is NULL");
+ return E_INVALIDARG;
+ }
+
+ // Method 1: Try to get the full path from STATSTG
+ STATSTG stat;
+ HRESULT hr = pStream->Stat(&stat, STATFLAG_DEFAULT);
+ m_filePath = GetFullPathFromStream(pStream);
+
+ // If still no full path, log a warning
+ if (m_filePath.find(L':') == std::wstring::npos &&
+ m_filePath.find(L'\\') != 0) {
+ DebugLog(
+ "IInitializeWithStream::Initialize: WARNING - Only have filename, "
+ "palette files may not be found: " +
+ WideToNarrow(m_filePath));
+ }
+
+ DebugLog("IInitializeWithStream::Initialize: Mode: " +
+ std::to_string(grfMode));
+ return S_OK;
+}
+static int g_requestCount = 0;
+static const int CLEANUP_INTERVAL = 10; // Clean up every 10 requests
+IFACEMETHODIMP CToonzThumbnailProvider::GetThumbnail(UINT cx, HBITMAP *phbmp,
+ WTS_ALPHATYPE *pdwAlpha) {
+ DebugLog("GetThumbnail called size=" + std::to_string(cx));
+
+ g_requestCount++;
+ if (g_requestCount >= CLEANUP_INTERVAL) {
+ DebugLog("Performing periodic cache cleanup - request count: " +
+ std::to_string(g_requestCount));
+ TImageCache::instance()->clear();
+ g_requestCount = 0; // Reset count
+ }
+
+ if (!phbmp || !pdwAlpha) {
+ DebugLog("GetThumbnail: Invalid arguments");
+ return E_INVALIDARG;
+ }
+
+ *phbmp = NULL;
+ *pdwAlpha = WTSAT_UNKNOWN;
+
+ if (m_filePath.empty()) {
+ DebugLog("GetThumbnail: No file path set");
+ return E_FAIL;
+ }
+
+ DebugLog("GetThumbnail: Processing file: " + WideToNarrow(m_filePath));
+
+ try {
+ // 1. Initialize Qt Environment (Required for TOfflineGL used by
+ // IconGenerator)
+ EnsureQtApplication();
+
+ static std::once_flag ioInitFlag;
+ std::call_once(ioInitFlag, []() {
+ LoadDependencies();
+ Tiio::defineStd();
+ initImageIo();
+ TThread::init();
+ DebugLog("Tiio and ImageIo initialized successfully.");
+ });
+
+ TFilePath path(m_filePath);
+ TDimension size(cx, cx);
+
+ // 2. Normalize extension to lowercase for comparison
+ std::string type = path.getType();
+ std::transform(type.begin(), type.end(), type.begin(), ::tolower);
+
+ DebugLog("GetThumbnail: File type: " + type);
+
+ TRaster32P ras;
+ static TDimension oldSize(0, 0);
+ if (size.lx > oldSize.lx || size.ly > oldSize.ly) {
+ IconGenerator::setFilmstripIconSize(size);
+ oldSize = size;
+ }
+
+ // 3. Route to the specific static generator based on file type
+ if (type == "tnz") {
+ DebugLog("GetThumbnail: Generating Scene (TNZ) icon");
+ ras = IconGenerator::generateSceneFileIcon(path, size, -5);
+ } else if (type == "pli") {
+ DebugLog("GetThumbnail: Generating Vector Level (PLI) icon");
+ // NO_FRAME lets the reader pick the first frame in the level
+ ras =
+ IconGenerator::generateVectorFileIcon(path, size, TFrameId::NO_FRAME);
+ } else if (type == "tlv" || type == "tga") {
+ DebugLog("GetThumbnail: Generating Raster Level (TLV/TGA) icon");
+ if (type == "tlv")
+ ras = IconGenerator::generateRasterFileIcon(path, size,
+ TFrameId::NO_FRAME);
+ else
+ ras = IconGenerator::generateRasterFileIcon(path, size,
+ path.analyzePath().fId);
+ } else if (type == "tpl") {
+ DebugLog(
+ "GetThumbnail: TPL generation not fully implemented for Shell "
+ "Preview.");
+ } else {
+ DebugLog("GetThumbnail: Unsupported file type: " + type);
+ }
+
+ // 4. Validate Result
+ if (!ras.getPointer() || !ras->getRawData()) {
+ // TODO : return image broken notify infomation
+ DebugLog("GetThumbnail: No raster generated or raster is empty");
+ return E_FAIL;
+ }
+
+ DebugLog(
+ "GetThumbnail: Raster generated successfully, converting to HBITMAP");
+
+ // 5. Convert Toonz Raster to Windows HBITMAP
+ *phbmp = RasterToHBITMAP(ras);
+
+ if (*phbmp) {
+ *pdwAlpha = WTSAT_ARGB; // Indicate the bitmap has an alpha channel
+ DebugLog("GetThumbnail: Success - HBITMAP created");
+ return S_OK;
+ } else {
+ DebugLog("GetThumbnail: Failed to create HBITMAP from Raster");
+ }
+
+ } catch (const std::exception &e) {
+ DebugLog("GetThumbnail: Exception: " + std::string(e.what()));
+ } catch (...) {
+ DebugLog("GetThumbnail: Unknown exception");
+ }
+
+ return E_FAIL;
+}
+
+IFACEMETHODIMP CToonzThumbnailProvider::GetClassID(CLSID *pClassID) {
+ DebugLog("IPersist::GetClassID called");
+ if (!pClassID) return E_INVALIDARG;
+ *pClassID = CLSID_ToonzThumbnailProvider;
+ return S_OK;
+}
+
+// IPersistFile
+IFACEMETHODIMP CToonzThumbnailProvider::IsDirty() { return S_FALSE; }
+IFACEMETHODIMP CToonzThumbnailProvider::Save(LPCWSTR pszFileName,
+ BOOL fRemember) {
+ return E_NOTIMPL;
+}
+IFACEMETHODIMP CToonzThumbnailProvider::SaveCompleted(LPCWSTR pszFileName) {
+ return E_NOTIMPL;
+}
+IFACEMETHODIMP CToonzThumbnailProvider::GetCurFile(LPWSTR *ppszFileName) {
+ return E_NOTIMPL;
+}
+
+IFACEMETHODIMP CToonzThumbnailProvider::Load(LPCWSTR pszFileName,
+ DWORD dwMode) {
+ DebugLog("IPersistFile::Load called");
+
+ if (!pszFileName) {
+ DebugLog("IPersistFile::Load: pszFileName is NULL");
+ return E_INVALIDARG;
+ }
+
+ m_filePath = pszFileName;
+ DebugLog("IPersistFile::Load: File path set to: " + WideToNarrow(m_filePath));
+ DebugLog("IPersistFile::Load: Mode: " + std::to_string(dwMode));
+
+ return S_OK;
+}
+
+// ---------------------------------------------------------------------------
+// CClassFactory Implementation
+// ---------------------------------------------------------------------------
+CClassFactory::CClassFactory() : m_cRef(1) { InterlockedIncrement(&g_cDllRef); }
+
+CClassFactory::~CClassFactory() { InterlockedDecrement(&g_cDllRef); }
+
+IFACEMETHODIMP CClassFactory::QueryInterface(REFIID riid, void **ppv) {
+ if (!ppv) return E_INVALIDARG;
+ *ppv = NULL;
+
+ if (IsEqualIID(riid, IID_IUnknown) || IsEqualIID(riid, IID_IClassFactory)) {
+ *ppv = static_cast<IClassFactory *>(this);
+ AddRef();
+ return S_OK;
+ }
+ return E_NOINTERFACE;
+}
+
+IFACEMETHODIMP_(ULONG) CClassFactory::AddRef() {
+ return InterlockedIncrement(&m_cRef);
+}
+
+IFACEMETHODIMP_(ULONG) CClassFactory::Release() {
+ ULONG cRef = InterlockedDecrement(&m_cRef);
+ if (0 == cRef) delete this;
+ return cRef;
+}
+
+IFACEMETHODIMP CClassFactory::CreateInstance(IUnknown *pUnkOuter, REFIID riid,
+ void **ppv) {
+ if (pUnkOuter) return CLASS_E_NOAGGREGATION;
+
+ CToonzThumbnailProvider *pObj = new CToonzThumbnailProvider();
+ if (!pObj) return E_OUTOFMEMORY;
+
+ HRESULT hr = pObj->QueryInterface(riid, ppv);
+ pObj->Release();
+ return hr;
+}
+
+IFACEMETHODIMP CClassFactory::LockServer(BOOL fLock) {
+ if (fLock)
+ InterlockedIncrement(&g_cDllRef);
+ else
+ InterlockedDecrement(&g_cDllRef);
+ return S_OK;
+}
+
+STDAPI DllInstall(BOOL bInstall, LPCWSTR pszCmdLine) {
+ if (bInstall) {
+ DllRegisterServer();
+ } else {
+ DllUnregisterServer();
+ }
+ return S_OK;
+}
\ No newline at end of file
diff --git a/toonz/sources/toonzpreview/toonzpreview.def b/toonz/sources/toonzpreview/toonzpreview.def
new file mode 100644
index 000000000..b843167e9
--- /dev/null
+++ b/toonz/sources/toonzpreview/toonzpreview.def
@@ -0,0 +1,8 @@
+LIBRARY "toonzpreview"
+
+EXPORTS
+ DllCanUnloadNow PRIVATE
+ DllGetClassObject PRIVATE
+ DllRegisterServer PRIVATE
+ DllUnregisterServer PRIVATE
+ DllInstall PRIVATE
\ No newline at end of file
diff --git a/toonz/sources/toonzpreview/toonzpreview.h b/toonz/sources/toonzpreview/toonzpreview.h
new file mode 100644
index 000000000..04d5c414b
--- /dev/null
+++ b/toonz/sources/toonzpreview/toonzpreview.h
@@ -0,0 +1,119 @@
+#pragma once
+
+#ifndef TOONZPREVIEW_H
+#define TOONZPREVIEW_H
+
+// Windows Headers
+#define WIN32_LEAN_AND_MEAN
+#include <unknwn.h> // For IUnknown
+#include <windows.h>
+
+// COM Headers
+#include <objidl.h> // For IPersist, IPersistFile
+#include <shlguid.h> // Defines standard Shell IIDs
+#include <shlobj.h> // For IInitializeWithFile
+#include <shlwapi.h> // For QITAB
+#include <thumbcache.h> // For IThumbnailProvider, WTS_ALPHATYPE
+
+// C++
+#include <atomic>
+#include <string>
+
+// toonz
+#include "traster.h"
+
+// {A20E2270-0FE1-421D-A34E-98C26C13F9DB}
+static const GUID CLSID_ToonzThumbnailProvider
+ = {0xa20e2270,
+ 0xfe1,
+ 0x421d,
+ {0xa3, 0x4e, 0x98, 0xc2, 0x6c, 0x13, 0xf9, 0xdb}};
+
+const wchar_t *SZ_CLSID_TOONZPREVIEW =
+ L"{A20E2270-0FE1-421D-A34E-98C26C13F9DB}";
+class __declspec(uuid(
+ "A20E2270-0FE1-421D-A34E-98C26C13F9DB")) CToonzThumbnailProvider;
+
+// DLL Export Macro
+#ifdef TOONZPREVIEW_EXPORTS
+#define PREVIEW_API __declspec(dllexport)
+#else
+#define PREVIEW_API __declspec(dllimport)
+#endif
+
+// Forward Declarations
+class CClassFactory;
+
+// ---------------------------------------------------------------------------
+// CToonzThumbnailProvider
+// Implements IThumbnailProvider and IInitializeWithFile
+// ---------------------------------------------------------------------------
+class CToonzThumbnailProvider : public IInitializeWithStream,
+ public IInitializeWithFile,
+ public IPersistFile,
+ public IThumbnailProvider {
+public:
+ CToonzThumbnailProvider();
+ virtual ~CToonzThumbnailProvider();
+
+ // IUnknown
+ IFACEMETHODIMP QueryInterface(REFIID riid, void **ppv);
+ IFACEMETHODIMP_(ULONG) AddRef();
+ IFACEMETHODIMP_(ULONG) Release();
+
+ // IInitializeWithFile
+ IFACEMETHODIMP Initialize(LPCWSTR pszFilePath, DWORD grfMode);
+ // IInitializeWithStream
+ IFACEMETHODIMP Initialize(IStream *pStream, DWORD grfMode);
+
+ // IThumbnailProvider
+ IFACEMETHODIMP GetThumbnail(UINT cx, HBITMAP *phbmp, WTS_ALPHATYPE *pdwAlpha);
+
+ // IPersist
+ IFACEMETHODIMP GetClassID(CLSID *pClassID);
+
+ // IPersistFile
+ IFACEMETHODIMP IsDirty();
+ IFACEMETHODIMP Load(LPCWSTR pszFileName, DWORD dwMode);
+ IFACEMETHODIMP Save(LPCWSTR pszFileName, BOOL fRemember);
+ IFACEMETHODIMP SaveCompleted(LPCWSTR pszFileName);
+ IFACEMETHODIMP GetCurFile(LPWSTR *ppszFileName);
+
+private:
+ long m_cRef;
+ std::wstring m_filePath;
+};
+
+// ---------------------------------------------------------------------------
+// CClassFactory
+// Standard COM Class Factory
+// ---------------------------------------------------------------------------
+class CClassFactory : public IClassFactory {
+public:
+ CClassFactory();
+ virtual ~CClassFactory();
+
+ // IUnknown
+ IFACEMETHODIMP QueryInterface(REFIID riid, void **ppv);
+ IFACEMETHODIMP_(ULONG) AddRef();
+ IFACEMETHODIMP_(ULONG) Release();
+
+ // IClassFactory
+ IFACEMETHODIMP CreateInstance(IUnknown *pUnkOuter, REFIID riid, void **ppv);
+ IFACEMETHODIMP LockServer(BOOL fLock);
+
+private:
+ long m_cRef;
+};
+
+// Globals
+extern long g_cDllRef;
+extern HINSTANCE g_hInst;
+
+// Helpers
+void DebugLog(const std::string &message);
+std::string WideToNarrow(const std::wstring &wideStr);
+void EnsureQtApplication();
+HBITMAP RasterToHBITMAP(const TRaster32P &ras);
+
+#endif // TOONZPREVIEW_H
\ No newline at end of file
diff --git a/toonz/sources/toonzqt/icongenerator.cpp b/toonz/sources/toonzqt/icongenerator.cpp
index 1aeb159b0..78fc97116 100644
--- a/toonz/sources/toonzqt/icongenerator.cpp
+++ b/toonz/sources/toonzqt/icongenerator.cpp
@@ -28,6 +28,7 @@
// TnzLib includes
#include "toonz/toonzscene.h"
#include "toonz/sceneproperties.h"
+#include "toonz/tcamera.h"
#include "toonz/txsheet.h"
#include "toonz/tscenehandle.h"
#include "toonz/txshlevel.h"
@@ -38,12 +39,15 @@
#include "toonz/preferences.h"
#include "toonz/sceneresources.h"
#include "toonz/stage2.h"
+#include "trop.h"
// TnzQt includes
#include "toonzqt/gutil.h"
#include "toonzqt/icongenerator.h"
+#include <QCoreApplication>
+
//=============================================================================
//===================================
@@ -898,8 +902,15 @@ public:
TRaster32P XsheetIconRenderer::generateRaster(
const TDimension &iconSize) const {
ToonzScene *scene = m_xsheet->getScene();
-
- TRaster32P ras(iconSize);
+ TDimension res = scene->getProperties()->getCameras().front()->getRes();
+ if (res.lx > iconSize.lx || res.ly > iconSize.ly) {
+ double sx = (double)iconSize.lx / res.lx;
+ double sy = (double)iconSize.ly / res.ly;
+ double s = std::min(sx, sy);
+ res.lx = tround(res.lx * s);
+ res.ly = tround(res.ly * s);
+ }
+ TRaster32P ras(res);
TPixel32 bgColor = scene->getProperties()->getBgColor();
bgColor.m = 255;
@@ -1034,8 +1045,9 @@ TRaster32P IconGenerator::generateRasterFileIcon(const TFilePath &path,
if (shrink > 1) ir->setShrink(shrink);
}
-
- img = (toUpper(path.getType()) == "TLV") ? ir->loadIcon() : ir->load();
+ bool isDll = QCoreApplication::applicationName() == "ToonzPreview";
+ img = (toUpper(path.getType()) == "TLV" && !isDll) ? ir->loadIcon()
+ : ir->load();
} catch (...) {
}
@@ -1060,8 +1072,9 @@ TRaster32P IconGenerator::generateRasterFileIcon(const TFilePath &path,
TRop::convert(dstRaster, auxRaster, plt, false);
else
dstRaster->fill(TPixel32::Magenta);
-
- ras32 = dstRaster;
+ ras32 = TRaster32P(dstRaster->getLx(), dstRaster->getLy());
+ ras32->fill(TPixel32::White);
+ TRop::over(ras32, dstRaster);
}
if (!ras32) return TRaster32P();
@@ -1080,16 +1093,22 @@ Qt::transparent)
}
*/
- TRaster32P icon(iconSize);
-
double sx = double(iconSize.lx) / ras32->getLx();
double sy = double(iconSize.ly) / ras32->getLy();
- double sc = std::min(sx, sy); // show all the image, possibly adding bands
+ double sc = std::min(sx, sy);
+
+ TDimension finalIconSize(tround(ras32->getLx() * sc),
+ tround(ras32->getLy() * sc));
+
+ TRaster32P icon(finalIconSize);
TAffine aff = TScale(sc).place(ras32->getCenterD(), icon->getCenterD());
- icon->fill(TPixel32(255, 0, 0)); // "bands" color
- TRop::resample(icon, ras32, aff, TRop::Triangle);
+ // Fill with transparent color (no bands/borders needed in this mode)
+ icon->fill(TPixel32::Magenta);
+
+ // Perform resampling and scaling
+ TRop::resample(icon, ras32, aff, TRop::ClosestPixel);
if (icon) {
if (::isUnpremultiplied(icon)) // APPALLING. I'm not touching this, but
@@ -1114,7 +1133,6 @@ Qt::transparent)
return icon;
}
-
//-----------------------------------------------------------------------------
TRaster32P IconGenerator::generateSplineFileIcon(const TFilePath &path,
@@ -1158,9 +1176,15 @@ TRaster32P IconGenerator::generateSceneFileIcon(const TFilePath &path,
path.getParentDir() + "sceneIcons" + (path.getWideName() + L" .png");
return generateRasterFileIcon(iconPath, iconSize, TFrameId::NO_FRAME);
} else {
+ if (row < 0) row = 0;
// obsolete
ToonzScene scene;
- scene.load(path);
+ try {
+ scene.load(path);
+ } catch (...) {
+ scene.clear();
+ return TRaster32P();
+ }
XsheetIconRenderer ir("", iconSize, scene.getXsheet(), row);
return ir.generateRaster(iconSize);
}
@@ -1324,6 +1348,16 @@ IconGenerator::~IconGenerator() {}
//-----------------------------------------------------------------------------
IconGenerator *IconGenerator::instance() {
+ bool isShellExtension = false;
+ if (QCoreApplication::instance()) {
+ if (QCoreApplication::applicationName() == "ToonzPreview") {
+ isShellExtension = true;
+ }
+ }
+ if (isShellExtension) {
+ static IconGenerator *_instance = new IconGenerator();
+ return _instance;
+ }
static IconGenerator _instance;
return &_instance;
}
@@ -1341,15 +1375,27 @@ TDimension IconGenerator::getIconSize() const { return FilmstripIconSize; }
//-----------------------------------------------------------------------------
TOfflineGL *IconGenerator::getOfflineGLContext() {
+ TOfflineGL *context = m_contexts.localData();
// One context per rendering thread
- if (!m_contexts.hasLocalData()) {
- TDimension contextSize(std::max(FilmstripIconSize.lx, IconSize.lx),
- std::max(FilmstripIconSize.ly, IconSize.ly));
- m_contexts.setLocalData(new TOfflineGL(contextSize));
+ if (!context) {
+ context =
+ new TOfflineGL(TDimension(std::max(FilmstripIconSize.lx, IconSize.lx),
+ std::max(FilmstripIconSize.ly, IconSize.ly)));
+ m_contexts.setLocalData(context);
+ return context;
}
- return m_contexts.localData();
-}
+ TDimension requiredSize(std::max(FilmstripIconSize.lx, IconSize.lx),
+ std::max(FilmstripIconSize.ly, IconSize.ly));
+ TDimension actualSize = context->getSize();
+
+ if (actualSize.lx < requiredSize.lx || actualSize.ly < requiredSize.ly) {
+ context = new TOfflineGL(requiredSize);
+ m_contexts.setLocalData(context);
+ }
+
+ return context;
+}
//-----------------------------------------------------------------------------
void IconGenerator::addTask(const std::string &id,