iPlug2 - C++ Audio Plug-in Framework
Loading...
Searching...
No Matches
IPlugAPP_main.cpp
1/*
2 ==============================================================================
3
4 This file is part of the iPlug 2 library. Copyright (C) the iPlug 2 developers.
5
6 See LICENSE.txt for more info.
7
8 ==============================================================================
9*/
10
11#include <memory>
12#include "wdltypes.h"
13#include "wdlstring.h"
14
15#include "IPlugPlatform.h"
16#include "IPlugAPP_host.h"
17
18#include "config.h"
19#include "resource.h"
20
21using namespace iplug;
22
23#pragma mark - WINDOWS
24#if defined OS_WIN
25#include <windows.h>
26#include <commctrl.h>
27#include <shellapi.h>
28
29// Include stb_image_write for PNG saving
30// STBIW_WINDOWS_UTF8 makes it open UTF-8 paths via _wfopen, matching the
31// UTF-8 screenshot path parsed from the wide command line below
32#define STBIW_WINDOWS_UTF8
33#define STB_IMAGE_WRITE_IMPLEMENTATION
34#include "../../Dependencies/IGraphics/STB/stb_image_write.h"
35
36extern WDL_DLGRET MainDlgProc(HWND hwndDlg, UINT uMsg, WPARAM wParam, LPARAM lParam);
37
38HWND gHWND;
39extern HINSTANCE gHINSTANCE;
40UINT gScrollMessage;
41
42// Save a screenshot of the given HWND to a PNG file using Win32 API
43bool SaveWindowScreenshot(HWND hwnd, const char* path)
44{
45 if (!hwnd || !path)
46 return false;
47
48 // Get client area dimensions
49 RECT clientRect;
50 if (!GetClientRect(hwnd, &clientRect))
51 return false;
52
53 int width = clientRect.right - clientRect.left;
54 int height = clientRect.bottom - clientRect.top;
55
56 if (width <= 0 || height <= 0)
57 return false;
58
59 // Create a compatible DC and bitmap
60 HDC hdcWindow = GetDC(hwnd);
61 if (!hdcWindow)
62 return false;
63
64 HDC hdcMem = CreateCompatibleDC(hdcWindow);
65 if (!hdcMem)
66 {
67 ReleaseDC(hwnd, hdcWindow);
68 return false;
69 }
70
71 // Create a 32-bit DIB section for the screenshot
72 BITMAPINFO bmi = {};
73 bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
74 bmi.bmiHeader.biWidth = width;
75 bmi.bmiHeader.biHeight = -height; // Top-down DIB
76 bmi.bmiHeader.biPlanes = 1;
77 bmi.bmiHeader.biBitCount = 32;
78 bmi.bmiHeader.biCompression = BI_RGB;
79
80 void* pBits = nullptr;
81 HBITMAP hBitmap = CreateDIBSection(hdcMem, &bmi, DIB_RGB_COLORS, &pBits, nullptr, 0);
82
83 if (!hBitmap || !pBits)
84 {
85 DeleteDC(hdcMem);
86 ReleaseDC(hwnd, hdcWindow);
87 return false;
88 }
89
90 HGDIOBJ hOldBitmap = SelectObject(hdcMem, hBitmap);
91
92 // Use PrintWindow to capture the window content
93 // PW_CLIENTONLY captures only the client area
94 // PW_RENDERFULLCONTENT renders the window fully, including layered content
95#ifndef PW_RENDERFULLCONTENT
96 #define PW_RENDERFULLCONTENT 0x00000002
97#endif
98 BOOL captured = PrintWindow(hwnd, hdcMem, PW_CLIENTONLY | PW_RENDERFULLCONTENT);
99
100 if (!captured)
101 {
102 // Fallback to BitBlt if PrintWindow fails
103 captured = BitBlt(hdcMem, 0, 0, width, height, hdcWindow, 0, 0, SRCCOPY);
104 }
105
106 SelectObject(hdcMem, hOldBitmap);
107 DeleteDC(hdcMem);
108 ReleaseDC(hwnd, hdcWindow);
109
110 if (!captured)
111 {
112 DeleteObject(hBitmap);
113 return false;
114 }
115
116 // Convert BGRA to RGBA for stb_image_write
117 uint8_t* pixels = static_cast<uint8_t*>(pBits);
118 for (int i = 0; i < width * height; i++)
119 {
120 // Swap B and R channels (BGRA -> RGBA)
121 uint8_t temp = pixels[i * 4 + 0];
122 pixels[i * 4 + 0] = pixels[i * 4 + 2];
123 pixels[i * 4 + 2] = temp;
124 // Set alpha to 255 (opaque) since Windows DIB may have garbage in alpha
125 pixels[i * 4 + 3] = 255;
126 }
127
128 // Use stb_image_write to save as PNG
129 int result = stbi_write_png(path, width, height, 4, pixels, width * 4);
130
131 DeleteObject(hBitmap);
132
133 return result != 0;
134}
135
136int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpszCmdParam, int nShowCmd)
137{
138 try
139 {
140#ifndef APP_ALLOW_MULTIPLE_INSTANCES
141 HANDLE hMutex = OpenMutex(MUTEX_ALL_ACCESS, 0, BUNDLE_NAME); // BUNDLE_NAME used because it won't have spaces in it
142
143 if (!hMutex)
144 hMutex = CreateMutex(0, 0, BUNDLE_NAME);
145 else
146 {
147 HWND hWnd = FindWindow(0, BUNDLE_NAME);
148 SetForegroundWindow(hWnd);
149 return 0;
150 }
151#endif
152 gHINSTANCE = hInstance;
153
154 InitCommonControls();
155 gScrollMessage = RegisterWindowMessage("MSWHEEL_ROLLMSG");
156
157 IPlugAPPHost* pAppHost = IPlugAPPHost::Create();
158
159 // Parse command line arguments from the wide command line, so that quoted
160 // arguments (paths with spaces) and non-ASCII characters survive
161 int argc = 0;
162 LPWSTR* argv = CommandLineToArgvW(GetCommandLineW(), &argc);
163 if (argv)
164 {
165 for (int i = 1; i < argc; i++)
166 {
167 if (wcscmp(argv[i], L"--screenshot") == 0 && (i + 1) < argc)
168 {
169 pAppHost->SetScreenshotPath(UTF16AsUTF8(argv[++i]).Get());
170 }
171 else if (wcscmp(argv[i], L"--no-io") == 0)
172 {
173 pAppHost->SetNoIO(true);
174 }
175 }
176 LocalFree(argv);
177 }
178
179 // Screenshot mode implies --no-io
180 if (pAppHost->IsScreenshotMode())
181 pAppHost->SetNoIO(true);
182
183 pAppHost->Init();
184 pAppHost->TryToChangeAudio();
185
186 HACCEL hAccel = LoadAccelerators(gHINSTANCE, MAKEINTRESOURCE(IDR_ACCELERATOR1));
187
188 static UINT(WINAPI *__SetProcessDpiAwarenessContext)(DPI_AWARENESS_CONTEXT);
189
190 if (!__SetProcessDpiAwarenessContext)
191 {
192 HINSTANCE h = LoadLibrary("user32.dll");
193 if (h) *(void **)&__SetProcessDpiAwarenessContext = GetProcAddress(h, "SetProcessDpiAwarenessContext");
194 if (!__SetProcessDpiAwarenessContext)
195 *(void **)&__SetProcessDpiAwarenessContext = (void*)(INT_PTR)1;
196 }
197 if ((UINT_PTR)__SetProcessDpiAwarenessContext > (UINT_PTR)1)
198 {
199 __SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2);
200 }
201
202 CreateDialog(gHINSTANCE, MAKEINTRESOURCE(IDD_DIALOG_MAIN), GetDesktopWindow(), IPlugAPPHost::MainDlgProc);
203
204#if !defined _DEBUG || defined NO_IGRAPHICS
205 HMENU menu = GetMenu(gHWND);
206 RemoveMenu(menu, 1, MF_BYPOSITION);
207 DrawMenuBar(gHWND);
208#endif
209
210 for (;;)
211 {
212 MSG msg= {0,};
213 int vvv = GetMessage(&msg, NULL, 0, 0);
214
215 if (!vvv)
216 break;
217
218 if (vvv < 0)
219 {
220 Sleep(10);
221 continue;
222 }
223
224 if (!msg.hwnd)
225 {
226 DispatchMessage(&msg);
227 continue;
228 }
229
230 if (gHWND && (TranslateAccelerator(gHWND, hAccel, &msg) || IsDialogMessage(gHWND, &msg)))
231 continue;
232
233 // default processing for other dialogs
234 HWND hWndParent = NULL;
235 HWND temphwnd = msg.hwnd;
236
237 do
238 {
239 if (GetClassLong(temphwnd, GCW_ATOM) == (INT)32770)
240 {
241 hWndParent = temphwnd;
242 if (!(GetWindowLong(temphwnd, GWL_STYLE) & WS_CHILD))
243 break; // not a child, exit
244 }
245 }
246 while (temphwnd = GetParent(temphwnd));
247
248 if (hWndParent && IsDialogMessage(hWndParent,&msg))
249 continue;
250
251 TranslateMessage(&msg);
252 DispatchMessage(&msg);
253 }
254
255 // in case gHWND didnt get destroyed -- this corresponds to SWELLAPP_DESTROY roughly
256 if (gHWND)
257 DestroyWindow(gHWND);
258
259#ifndef APP_ALLOW_MULTIPLE_INSTANCES
260 ReleaseMutex(hMutex);
261#endif
262 }
263 catch(const std::exception& e)
264 {
265 fprintf(stderr, "Fatal exception: %s\n", e.what());
266 DBGMSG("Exception: %s", e.what());
267 return 1;
268 }
269 return 0;
270}
271#pragma mark - MAC
272#elif defined(OS_MAC)
273#import <Cocoa/Cocoa.h>
274#include <dlfcn.h>
275#include <cstring>
276#include "IPlugSWELL.h"
277#include "IPlugPaths.h"
278
279HWND gHWND;
280
281// Function pointer type for CGWindowListCreateImage
282typedef CGImageRef (*CGWindowListCreateImageFunc)(CGRect, uint32_t, uint32_t, uint32_t);
283
284// Save a screenshot of the given HWND (NSView*) to a PNG file
285extern "C" bool SaveWindowScreenshot(void* hwnd, const char* path)
286{
287 if (!hwnd || !path)
288 return false;
289
290 NSView* view = (__bridge NSView*)hwnd;
291 NSWindow* window = [view window];
292
293 if (!window)
294 return false;
295
296 // Get CGWindowListCreateImage via dlsym to bypass availability check
297 // The function still exists and works in the runtime
298 static CGWindowListCreateImageFunc pCGWindowListCreateImage = nullptr;
299 if (!pCGWindowListCreateImage)
300 {
301 void* handle = dlopen("/System/Library/Frameworks/CoreGraphics.framework/CoreGraphics", RTLD_LAZY);
302 if (handle)
303 pCGWindowListCreateImage = (CGWindowListCreateImageFunc)dlsym(handle, "CGWindowListCreateImage");
304 }
305
306 if (!pCGWindowListCreateImage)
307 return false;
308
309 // Get the window's CGWindowID
310 CGWindowID windowID = (CGWindowID)[window windowNumber];
311
312 // Capture the window content at full resolution (high DPI)
313 CGImageRef cgImage = pCGWindowListCreateImage(
314 CGRectNull, // Capture the whole window
315 kCGWindowListOptionIncludingWindow,
316 windowID,
317 kCGWindowImageBoundsIgnoreFraming // Exclude window frame, capture at screen resolution
318 );
319
320 if (!cgImage)
321 return false;
322
323 // Create NSBitmapImageRep from CGImage and save as PNG
324 NSBitmapImageRep* bitmap = [[NSBitmapImageRep alloc] initWithCGImage:cgImage];
325 CGImageRelease(cgImage);
326
327 if (!bitmap)
328 return false;
329
330 NSData* pngData = [bitmap representationUsingType:NSBitmapImageFileTypePNG properties:@{}];
331 if (!pngData)
332 return false;
333
334 NSString* filePath = [NSString stringWithUTF8String:path];
335 return [pngData writeToFile:filePath atomically:YES];
336}
337extern HMENU SWELL_app_stocksysmenu;
338
339static WDL_String gScreenshotPath;
340static bool gNoIO = false;
341
342int main(int argc, char *argv[])
343{
344#if APP_COPY_AUV3
345 //if invoked with an argument registerauv3 use plug-in kit to explicitly register auv3 app extension (doesn't happen from debugger)
346 if (argc > 2 && std::string_view(argv[2]) == "registerauv3")
347 {
348 WDL_String appexPath;
349 appexPath.SetFormatted(1024, "pluginkit -a %s%s%s.appex", argv[0], "/../../Plugins/", appexPath.get_filepart());
350 if (system(appexPath.Get()) > -1)
351 NSLog(@"Registered audiounit app extension\n");
352 else
353 NSLog(@"Failed to register audiounit app extension\n");
354 }
355#endif
356
357 // Parse command line arguments
358 for (int i = 1; i < argc; i++)
359 {
360 if (strcmp(argv[i], "--screenshot") == 0 && i + 1 < argc)
361 {
362 gScreenshotPath.Set(argv[i + 1]);
363 i++; // Skip the path argument
364 }
365 else if (strcmp(argv[i], "--no-io") == 0)
366 {
367 gNoIO = true;
368 }
369 }
370
371 if (AppIsSandboxed())
372 DBGMSG("App is sandboxed, file system access etc restricted!\n");
373
374 return NSApplicationMain(argc, (const char**) argv);
375}
376
377INT_PTR SWELLAppMain(int msg, INT_PTR parm1, INT_PTR parm2)
378{
379 IPlugAPPHost* pAppHost = nullptr;
380
381 switch (msg)
382 {
383 case SWELLAPP_ONLOAD:
384 {
385 pAppHost = IPlugAPPHost::Create();
386
387 // Set CLI options
388 if (gScreenshotPath.GetLength() > 0)
389 {
390 pAppHost->SetScreenshotPath(gScreenshotPath.Get());
391 pAppHost->SetNoIO(true); // Implicit --no-io for screenshot mode
392 }
393 else if (gNoIO)
394 {
395 pAppHost->SetNoIO(true);
396 }
397
398 pAppHost->Init();
399 pAppHost->TryToChangeAudio();
400 break;
401 }
402 case SWELLAPP_LOADED:
403 {
404 pAppHost = IPlugAPPHost::sInstance.get();
405
406 HMENU menu = SWELL_GetCurrentMenu();
407
408 if (menu)
409 {
410 // work on a new menu
411 menu = SWELL_DuplicateMenu(menu);
412 HMENU src = LoadMenu(NULL, MAKEINTRESOURCE(IDR_MENU1));
413
414 for (int x = 0; x < GetMenuItemCount(src)-1; x++)
415 {
416 HMENU sm = GetSubMenu(src,x);
417
418 if (sm)
419 {
420 char str[1024];
421 MENUITEMINFO mii = {sizeof(mii), MIIM_TYPE};
422 mii.dwTypeData = str;
423 mii.cch = sizeof(str);
424 str[0] = 0;
425 GetMenuItemInfo(src, x, TRUE, &mii);
426 MENUITEMINFO mi= {sizeof(mi), MIIM_STATE|MIIM_SUBMENU|MIIM_TYPE,MFT_STRING, 0, 0, SWELL_DuplicateMenu(sm), NULL, NULL, 0, str};
427 InsertMenuItem(menu, x+1, TRUE, &mi);
428 }
429 }
430 }
431
432 if (menu)
433 {
434 HMENU sm = GetSubMenu(menu, 1);
435 DeleteMenu(sm, ID_QUIT, MF_BYCOMMAND); // remove QUIT from our file menu, since it is in the system menu on OSX
436 DeleteMenu(sm, ID_PREFERENCES, MF_BYCOMMAND); // remove PREFERENCES from the file menu, since it is in the system menu on OSX
437
438 // remove any trailing separators
439 int a = GetMenuItemCount(sm);
440
441 while (a > 0 && GetMenuItemID(sm, a-1) == 0)
442 DeleteMenu(sm, --a, MF_BYPOSITION);
443
444 DeleteMenu(menu, 1, MF_BYPOSITION); // delete file menu
445 }
446#ifdef ID_SCREENSHOT
447 // Always set up screenshot shortcut (guarded: plugin resource.h may omit ID_SCREENSHOT;
448 // mirrors the existing #ifdef pattern in IPlugAPP_dialog.cpp)
449 SetMenuItemModifier(menu, ID_SCREENSHOT, MF_BYCOMMAND, 'S', FCONTROL | FSHIFT);
450#endif
451
452#if !defined _DEBUG || defined NO_IGRAPHICS
453 if (menu)
454 {
455 HMENU sm = GetSubMenu(menu, 1);
456 DeleteMenu(sm, ID_LIVE_EDIT, MF_BYCOMMAND);
457 DeleteMenu(sm, ID_SHOW_BOUNDS, MF_BYCOMMAND);
458 DeleteMenu(sm, ID_SHOW_DRAWN, MF_BYCOMMAND);
459 DeleteMenu(sm, ID_SHOW_FPS, MF_BYCOMMAND);
460
461 // remove any trailing separators
462 int a = GetMenuItemCount(sm);
463
464 while (a > 0 && GetMenuItemID(sm, a-1) == 0)
465 DeleteMenu(sm, --a, MF_BYPOSITION);
466
467 // Only delete debug menu if it's now empty (screenshot should remain)
468 if (GetMenuItemCount(sm) == 0)
469 DeleteMenu(menu, 1, MF_BYPOSITION);
470 }
471#else
472 SetMenuItemModifier(menu, ID_LIVE_EDIT, MF_BYCOMMAND, 'E', FCONTROL);
473 SetMenuItemModifier(menu, ID_SHOW_DRAWN, MF_BYCOMMAND, 'D', FCONTROL);
474 SetMenuItemModifier(menu, ID_SHOW_BOUNDS, MF_BYCOMMAND, 'B', FCONTROL);
475 SetMenuItemModifier(menu, ID_SHOW_FPS, MF_BYCOMMAND, 'F', FCONTROL);
476#endif
477
478 HWND hwnd = CreateDialog(gHINST, MAKEINTRESOURCE(IDD_DIALOG_MAIN), NULL, IPlugAPPHost::MainDlgProc);
479
480 if (menu)
481 {
482 SetMenu(hwnd, menu); // set the menu for the dialog to our menu (on Windows that menu is set from the .rc, but on SWELL
483 SWELL_SetDefaultModalWindowMenu(menu); // other windows will get the stock (bundle) menus
484 }
485
486 break;
487 }
488 case SWELLAPP_ONCOMMAND:
489 // this is to catch commands coming from the system menu etc
490 if (gHWND && (parm1&0xffff))
491 SendMessage(gHWND, WM_COMMAND, parm1 & 0xffff, 0);
492 break;
493 case SWELLAPP_DESTROY:
494 if (gHWND)
495 DestroyWindow(gHWND);
496 break;
497 case SWELLAPP_PROCESSMESSAGE:
498 MSG* pMSG = (MSG*) parm1;
499 NSView* pContentView = (NSView*) pMSG->hwnd;
500 NSEvent* pEvent = (NSEvent*) parm2;
501 int etype = (int) [pEvent type];
502
503 bool textField = [pContentView isKindOfClass:[NSText class]];
504
505 if (!textField && etype == NSKeyDown)
506 {
507 int flag, code = SWELL_MacKeyToWindowsKey(pEvent, &flag);
508
509 if (!(flag&~FVIRTKEY) && (code == VK_RETURN || code == VK_ESCAPE))
510 {
511 [pContentView keyDown: pEvent];
512 return 1;
513 }
514 }
515 break;
516 }
517 return 0;
518}
519
520#define CBS_HASSTRINGS 0
521#define SWELL_DLG_SCALE_AUTOGEN 1
522#define SET_IDD_DIALOG_PREF_SCALE 1.5
523#if PLUG_HOST_RESIZE
524#define SWELL_DLG_FLAGS_AUTOGEN SWELL_DLG_WS_FLIPPED|SWELL_DLG_WS_RESIZABLE
525#endif
526#include "swell-dlggen.h"
527#include "resources/main.rc_mac_dlg"
528#include "swell-menugen.h"
529#include "resources/main.rc_mac_menu"
530
531#pragma mark - LINUX
532#elif defined(OS_LINUX)
533#include "IPlugSWELL.h"
534
535HWND gHWND;
536HINSTANCE gHINSTANCE;
537int gStandaloneExitStatus = EXIT_SUCCESS;
538bool gStandaloneCloseRequested = false;
539
540static bool gNoIO = false;
541
542int main(int argc, char** argv)
543{
544 SWELL_initargs(&argc, &argv);
545 // Let SWELL forward events to GTK dialogs while retaining its own GDK event handler.
546 SWELL_ExtendedAPI("LOAD_GTK", nullptr);
547 SWELL_Internal_PostMessage_Init();
548 SWELL_ExtendedAPI("APPNAME", (void*) BUNDLE_NAME);
549
550 // Parse command line arguments
551 for (int i = 1; i < argc; i++)
552 {
553 if (strcmp(argv[i], "--no-io") == 0)
554 gNoIO = true;
555 }
556
557 IPlugAPPHost* pAppHost = IPlugAPPHost::Create();
558
559 if (gNoIO)
560 pAppHost->SetNoIO(true);
561
562 if (!pAppHost->Init())
563 {
564 fprintf(stderr, "Standalone initialization failed; audio and editor startup cancelled\n");
565 return 1;
566 }
567 if (!pAppHost->TryToChangeAudio())
568 fprintf(stderr, "Audio startup failed; check the standalone audio settings\n");
569
570 HMENU menu = LoadMenu(NULL, MAKEINTRESOURCE(IDR_MENU1));
571 if (!CreateDialog(gHINSTANCE, MAKEINTRESOURCE(IDD_DIALOG_MAIN), NULL, IPlugAPPHost::MainDlgProc))
572 {
573 fprintf(stderr, "Could not create the standalone window\n");
574 return EXIT_FAILURE;
575 }
576
577 if (menu)
578 {
579 SetMenu(gHWND, menu);
580 }
581 else
582 fprintf(stderr, "Standalone menu could not be loaded; opening the editor without it\n");
583
584 // Let the event loop process the optional menu resize before opening the editor.
585 if (!PostMessage(gHWND, WM_USER_OPENWINDOW, 0, 0))
586 {
587 fprintf(stderr, "Could not schedule standalone editor startup\n");
588 DestroyWindow(gHWND);
589 return EXIT_FAILURE;
590 }
591
592 while (gHWND)
593 {
594 SWELL_RunMessageLoop();
595 if (gStandaloneCloseRequested && gHWND)
596 {
597 gStandaloneCloseRequested = false;
598 DestroyWindow(gHWND);
599 }
600 Sleep(10);
601 }
602
603 if (gHWND)
604 DestroyWindow(gHWND);
605
606 return gStandaloneExitStatus;
607}
608
609INT_PTR SWELLAppMain(int msg, INT_PTR parm1, INT_PTR parm2)
610{
611 return 0;
612}
613
614#define CBS_HASSTRINGS 0
615#define SWELL_DLG_SCALE_AUTOGEN 1
616#define SET_IDD_DIALOG_PREF_SCALE 1.5
617#if PLUG_HOST_RESIZE
618#define SWELL_DLG_FLAGS_AUTOGEN SWELL_DLG_WS_FLIPPED|SWELL_DLG_WS_RESIZABLE
619#endif
620#include "swell-dlggen.h"
621#ifndef SWELL_DLG_WS_DEFAULT_SCALING
622#define SWELL_DLG_WS_DEFAULT_SCALING 0
623#endif
624#include "resources/main.rc_mac_dlg"
625#include "swell-menugen.h"
626#include "resources/main.rc_mac_menu"
627#endif
Common paths useful for plug-ins.
Include to get consistently named preprocessor macros for different platforms and logging functionali...
A class that hosts an IPlug as a standalone app and provides Audio/Midi I/O.
Definition: IPlugAPP_host.h:92
void SetScreenshotPath(const char *path)
Set screenshot path for CLI screenshot mode.
void SetNoIO(bool noIO)
Set no-I/O mode (disables audio and MIDI initialization)
bool IsScreenshotMode() const
Check if in screenshot mode.