std::wstring GetFilenamesFromCommandLine() { std::wstring result = L"[]"; if (AppGetCommandLine()->HasArguments()) { bool firstEntry = true; std::vector<CefString> args; AppGetCommandLine()->GetArguments(args); std::vector<CefString>::iterator iterator; result = L"["; for (iterator = args.begin(); iterator != args.end(); iterator++) { std::wstring argument = (*iterator).ToWString(); if (IsFilename(argument)) { std::wstring fullPath; // We check if this is a valid file path. If not just ignore this parameter. if( !GetFullPath(argument, fullPath) ) continue; if (!firstEntry) { result += L","; } firstEntry = false; result += L"\"" + fullPath + L"\""; } } result += L"]"; } return result; }
std::wstring GetFilenamesFromCommandLine() { std::wstring result = L"[]"; if (AppGetCommandLine()->HasArguments()) { bool firstEntry = true; std::vector<CefString> args; AppGetCommandLine()->GetArguments(args); std::vector<CefString>::iterator iterator; result = L"["; for (iterator = args.begin(); iterator != args.end(); iterator++) { std::wstring argument = (*iterator).ToWString(); if (IsURL(argument) || IsFilename(argument)) { if (!firstEntry) { result += L","; } firstEntry = false; result += L"\"" + argument + L"\""; } } result += L"]"; } return result; }
// Inject webinos.js // The file is loaded from the webinos\test\client folder if possible. // If this fails, the current folder is used. void ClientApp::InjectWebinos(CefRefPtr<CefFrame> frame) { CefRefPtr<CefCommandLine> commandLine = AppGetCommandLine(); // First try and load the platform-supplied webinos.js std::string pzpPath = AppGetWebinosWRTConfig(NULL,NULL); CefString wrtPath; // Make sure there is a trailing separator on the path. if (pzpPath.length() > 0) { if (pzpPath.find_last_of('/') == pzpPath.length()-1 || pzpPath.find_last_of('\\') == pzpPath.length()-1) wrtPath = pzpPath + "wrt/webinos.js"; else wrtPath = pzpPath + "/wrt/webinos.js"; } #if defined(OS_WIN) base::FilePath webinosJSPath(wrtPath.ToWString().c_str()); #else base::FilePath webinosJSPath(wrtPath); #endif LOG(INFO) << "webinos.js path is " << wrtPath; int64 webinosJSCodeSize; bool gotJSFile = base::GetFileSize(webinosJSPath, &webinosJSCodeSize); if (gotJSFile) { char* webinosJSCode = new char[webinosJSCodeSize+1]; base::ReadFile(webinosJSPath, webinosJSCode, webinosJSCodeSize); webinosJSCode[webinosJSCodeSize] = 0; if (frame == NULL) { // Register as a Cef extension. CefRegisterExtension("webinos", webinosJSCode, NULL); } else { // Run the code in the frame javascript context right now, // but only if the URL refers to the widget server. int widgetServerPort; AppGetWebinosWRTConfig(NULL,&widgetServerPort); char injectionCandidate[MAX_URL_LENGTH]; sprintf(injectionCandidate,"http://localhost:%d",widgetServerPort); std::string url = frame->GetURL(); if (url.substr(0,strlen(injectionCandidate)) == injectionCandidate) frame->ExecuteJavaScript(webinosJSCode, url, 0); } delete[] webinosJSCode; } else { LOG(ERROR) << "Can't find webinos.js"; } }
void AppQuitMessageLoop() { CefRefPtr<CefCommandLine> command_line = AppGetCommandLine(); if (command_line->HasSwitch(cefclient::kMultiThreadedMessageLoop)) { // Running in multi-threaded message loop mode. Need to execute // PostQuitMessage on the main application thread. ASSERT(hMessageWnd); PostMessage(hMessageWnd, WM_COMMAND, ID_QUIT, 0); } else { CefQuitMessageLoop(); } }
ClientHandler::ClientHandler() : m_MainHwnd(NULL), m_BrowserHwnd(NULL), m_EditHwnd(NULL), m_BackHwnd(NULL), m_ForwardHwnd(NULL), m_StopHwnd(NULL), m_ReloadHwnd(NULL), m_bFormElementHasFocus(false) { CefRefPtr<CefCommandLine> commandLine = AppGetCommandLine(); if (commandLine.get()) { if (commandLine->HasSwitch(cefclient::kUrl)) m_StartupURL = commandLine->GetSwitchValue(cefclient::kUrl); else m_StartupURL = "http://www.google.com/"; } }
// Program entry point function. int APIENTRY wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); g_appStartupTime = timeGetTime(); CefMainArgs main_args(hInstance); CefRefPtr<ClientApp> app(new ClientApp); // Execute the secondary process, if any. int exit_code = CefExecuteProcess(main_args, app.get(), NULL); if (exit_code >= 0) return exit_code; // Retrieve the current working directory. if (_getcwd(szWorkingDir, MAX_UNC_PATH) == NULL) szWorkingDir[0] = 0; // Parse command line arguments. The passed in values are ignored on Windows. AppInitCommandLine(0, NULL); // Determine if we should use an already running instance of Brackets. HANDLE hMutex = ::OpenMutex(MUTEX_ALL_ACCESS, FALSE, FIRST_INSTANCE_MUTEX_NAME); if ((hMutex != NULL) && AppGetCommandLine()->HasArguments() && (lpCmdLine != NULL)) { // for subsequent instances, re-use an already running instance if we're being called to // open an existing file on the command-line (eg. Open With.. from Windows Explorer) HWND hFirstInstanceWnd = cef_main_window::FindFirstTopLevelInstance(); if (hFirstInstanceWnd != NULL) { ::SetForegroundWindow(hFirstInstanceWnd); if (::IsIconic(hFirstInstanceWnd)) ::ShowWindow(hFirstInstanceWnd, SW_RESTORE); // message the other Brackets instance to actually open the given filename std::wstring wstrFilename = lpCmdLine; ConvertToUnixPath(wstrFilename); // note: WM_COPYDATA will manage passing the string across process space COPYDATASTRUCT data; data.dwData = ID_WM_COPYDATA_SENDOPENFILECOMMAND; data.cbData = (wstrFilename.length() + 1) * sizeof(WCHAR); data.lpData = (LPVOID)wstrFilename.c_str(); ::SendMessage(hFirstInstanceWnd, WM_COPYDATA, (WPARAM)(HWND)hFirstInstanceWnd, (LPARAM)(LPVOID)&data); // exit this instance return 0; } // otherwise, fall thru and launch a new instance } if (hMutex == NULL) { // first instance of this app, so create the mutex and continue execution of this instance. hMutex = ::CreateMutex(NULL, FALSE, FIRST_INSTANCE_MUTEX_NAME); } CefSettings settings; // Populate the settings based on command line arguments. AppGetSettings(settings, app); // Check command if (CefString(&settings.cache_path).length() == 0) { CefString(&settings.cache_path) = AppGetCachePath(); } // Initialize CEF. CefInitialize(main_args, settings, app.get(), NULL); CefRefPtr<CefCommandLine> cmdLine = AppGetCommandLine(); if (cmdLine->HasSwitch(cefclient::kStartupPath)) { wcscpy(szInitialUrl, cmdLine->GetSwitchValue(cefclient::kStartupPath).c_str()); } else { // If the shift key is not pressed, look for the index.html file if (GetAsyncKeyState(VK_SHIFT) == 0) { // Get the full pathname for the app. We look for the index.html // file relative to this location. wchar_t appPath[MAX_UNC_PATH]; wchar_t *pathRoot; GetModuleFileName(NULL, appPath, MAX_UNC_PATH); // Strip the .exe filename (and preceding "\") from the appPath // and store in pathRoot pathRoot = wcsrchr(appPath, '\\'); // Look for .\dev\src\index.html first wcscpy(pathRoot, L"\\dev\\src\\index.html"); // If the file exists, use it if (GetFileAttributes(appPath) != INVALID_FILE_ATTRIBUTES) { wcscpy(szInitialUrl, appPath); } if (!wcslen(szInitialUrl)) { // Look for .\www\index.html next wcscpy(pathRoot, L"\\www\\index.html"); if (GetFileAttributes(appPath) != INVALID_FILE_ATTRIBUTES) { wcscpy(szInitialUrl, appPath); } } } } if (!wcslen(szInitialUrl)) { // If we got here, either the startup file couldn't be found, or the user pressed the // shift key while launching. Prompt to select the index.html file. OPENFILENAME ofn = {0}; ofn.lStructSize = sizeof(ofn); ofn.lpstrFile = szInitialUrl; ofn.nMaxFile = MAX_UNC_PATH; ofn.lpstrFilter = L"Web Files\0*.htm;*.html\0\0"; ofn.lpstrTitle = L"Please select the " APP_NAME L" index.html file."; ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_NOCHANGEDIR | OFN_EXPLORER; if (!GetOpenFileName(&ofn)) { // User cancelled, exit the app CefShutdown(); return 0; } } // Perform application initialization if (!InitInstance (hInstance, nCmdShow)) return FALSE; // Start the node server process startNodeProcess(); gFilesToOpen = GetFilenamesFromCommandLine(); int result = 0; if (!settings.multi_threaded_message_loop) { // Run the CEF message loop. This function will block until the application // recieves a WM_QUIT message. CefRunMessageLoop(); } else { MSG msg; // Run the application message loop. while (GetMessage(&msg, NULL, 0, 0)) { if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } result = static_cast<int>(msg.wParam); } OnBeforeShutdown(); // Shut down CEF. CefShutdown(); // release the first instance mutex if (hMutex != NULL) ReleaseMutex(hMutex); return result; }
// Program entry point function. int APIENTRY wWinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) { UNREFERENCED_PARAMETER(hPrevInstance); UNREFERENCED_PARAMETER(lpCmdLine); g_appStartupTime = timeGetTime(); CefMainArgs main_args(hInstance); CefRefPtr<ClientApp> app(new ClientApp); // Execute the secondary process, if any. int exit_code = CefExecuteProcess(main_args, app.get()); if (exit_code >= 0) return exit_code; // Retrieve the current working directory. if (_getcwd(szWorkingDir, MAX_PATH) == NULL) szWorkingDir[0] = 0; // Parse command line arguments. The passed in values are ignored on Windows. AppInitCommandLine(0, NULL); CefSettings settings; // Populate the settings based on command line arguments. AppGetSettings(settings, app); // Check command if (CefString(&settings.cache_path).length() == 0) { CefString(&settings.cache_path) = AppGetCachePath(); } // Initialize CEF. CefInitialize(main_args, settings, app.get()); HACCEL hAccelTable; // Initialize global strings LoadString(hInstance, IDS_APP_TITLE, szTitle, MAX_LOADSTRING); LoadString(hInstance, IDC_CEFCLIENT, szWindowClass, MAX_LOADSTRING); MyRegisterClass(hInstance, *(app->GetCurrentLanguage().GetStruct())); CefRefPtr<CefCommandLine> cmdLine = AppGetCommandLine(); if (cmdLine->HasSwitch(cefclient::kStartupPath)) { wcscpy(szInitialUrl, cmdLine->GetSwitchValue(cefclient::kStartupPath).c_str()); } else { // If the shift key is not pressed, look for the index.html file if (GetAsyncKeyState(VK_SHIFT) == 0) { // Get the full pathname for the app. We look for the index.html // file relative to this location. wchar_t appPath[MAX_PATH]; wchar_t *pathRoot; GetModuleFileName(NULL, appPath, MAX_PATH); // Strip the .exe filename (and preceding "\") from the appPath // and store in pathRoot pathRoot = wcsrchr(appPath, '\\'); // Look for .\dev\src\index.html first wcscpy(pathRoot, L"\\dev\\src\\index.html"); // If the file exists, use it if (GetFileAttributes(appPath) != INVALID_FILE_ATTRIBUTES) { wcscpy(szInitialUrl, appPath); } if (!wcslen(szInitialUrl)) { // Look for .\www\index.html next wcscpy(pathRoot, L"\\www\\index.html"); if (GetFileAttributes(appPath) != INVALID_FILE_ATTRIBUTES) { wcscpy(szInitialUrl, appPath); } } } } if (!wcslen(szInitialUrl)) { // If we got here, either the startup file couldn't be found, or the user pressed the // shift key while launching. Prompt to select the index.html file. OPENFILENAME ofn = {0}; ofn.lStructSize = sizeof(ofn); ofn.lpstrFile = szInitialUrl; ofn.nMaxFile = MAX_PATH; ofn.lpstrFilter = L"Web Files\0*.htm;*.html\0\0"; ofn.lpstrTitle = L"Please select the " APP_NAME L" index.html file."; ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_NOCHANGEDIR | OFN_EXPLORER; if (!GetOpenFileName(&ofn)) { // User cancelled, exit the app CefShutdown(); return 0; } } // Perform application initialization if (!InitInstance (hInstance, nCmdShow)) return FALSE; // Temporary localization hack. Default to English. Check for French. DWORD menuId = IDC_CEFCLIENT; if (app->GetCurrentLanguage() == CefString("fr-FR")) { menuId = IDC_CEFCLIENT_FR; } hAccelTable = LoadAccelerators(hInstance, MAKEINTRESOURCE(menuId)); int result = 0; if (!settings.multi_threaded_message_loop) { // Run the CEF message loop. This function will block until the application // recieves a WM_QUIT message. CefRunMessageLoop(); } else { MSG msg; // Run the application message loop. while (GetMessage(&msg, NULL, 0, 0)) { if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)) { TranslateMessage(&msg); DispatchMessage(&msg); } } result = static_cast<int>(msg.wParam); } OnBeforeShutdown(); // Shut down CEF. CefShutdown(); return result; }
// // FUNCTION: WndProc(HWND, UINT, WPARAM, LPARAM) // // PURPOSE: Processes messages for the main window. // LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam) { static HWND backWnd = NULL, forwardWnd = NULL, reloadWnd = NULL, stopWnd = NULL, editWnd = NULL; static WNDPROC editWndOldProc = NULL; // Static members used for the find dialog. static FINDREPLACE fr; static WCHAR szFindWhat[80] = {0}; static WCHAR szLastFindWhat[80] = {0}; static bool findNext = false; static bool lastMatchCase = false; int wmId, wmEvent; PAINTSTRUCT ps; HDC hdc; if (hWnd == editWnd) { // Callback for the edit window switch (message) { case WM_CHAR: if (wParam == VK_RETURN && g_handler.get()) { // When the user hits the enter key load the URL CefRefPtr<CefBrowser> browser = g_handler->GetBrowser(); wchar_t strPtr[MAX_URL_LENGTH+1] = {0}; *((LPWORD)strPtr) = MAX_URL_LENGTH; LRESULT strLen = SendMessage(hWnd, EM_GETLINE, 0, (LPARAM)strPtr); if (strLen > 0) { strPtr[strLen] = 0; browser->GetMainFrame()->LoadURL(strPtr); } return 0; } } return (LRESULT)CallWindowProc(editWndOldProc, hWnd, message, wParam, lParam); } else if (message == uFindMsg) { // Find event. LPFINDREPLACE lpfr = (LPFINDREPLACE)lParam; if (lpfr->Flags & FR_DIALOGTERM) { // The find dialog box has been dismissed so invalidate the handle and // reset the search results. hFindDlg = NULL; if (g_handler.get()) { g_handler->GetBrowser()->GetHost()->StopFinding(true); szLastFindWhat[0] = 0; findNext = false; } return 0; } if ((lpfr->Flags & FR_FINDNEXT) && g_handler.get()) { // Search for the requested string. bool matchCase = (lpfr->Flags & FR_MATCHCASE?true:false); if (matchCase != lastMatchCase || (matchCase && wcsncmp(szFindWhat, szLastFindWhat, sizeof(szLastFindWhat)/sizeof(WCHAR)) != 0) || (!matchCase && _wcsnicmp(szFindWhat, szLastFindWhat, sizeof(szLastFindWhat)/sizeof(WCHAR)) != 0)) { // The search string has changed, so reset the search results. if (szLastFindWhat[0] != 0) { g_handler->GetBrowser()->GetHost()->StopFinding(true); findNext = false; } lastMatchCase = matchCase; wcscpy_s(szLastFindWhat, sizeof(szLastFindWhat)/sizeof(WCHAR), szFindWhat); } g_handler->GetBrowser()->GetHost()->Find(0, lpfr->lpstrFindWhat, (lpfr->Flags & FR_DOWN)?true:false, matchCase, findNext); if (!findNext) findNext = true; } return 0; } else { // Callback for the main window switch (message) { case WM_CREATE: { // Create the single static handler class instance g_handler = new ClientHandler(); g_handler->SetMainHwnd(hWnd); // Create the child windows used for navigation RECT rect; int x = 0; GetClientRect(hWnd, &rect); backWnd = CreateWindow(L"BUTTON", L"Back", WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_DISABLED, x, 0, BUTTON_WIDTH, URLBAR_HEIGHT, hWnd, (HMENU) IDC_NAV_BACK, hInst, 0); x += BUTTON_WIDTH; forwardWnd = CreateWindow(L"BUTTON", L"Forward", WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_DISABLED, x, 0, BUTTON_WIDTH, URLBAR_HEIGHT, hWnd, (HMENU) IDC_NAV_FORWARD, hInst, 0); x += BUTTON_WIDTH; reloadWnd = CreateWindow(L"BUTTON", L"Reload", WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_DISABLED, x, 0, BUTTON_WIDTH, URLBAR_HEIGHT, hWnd, (HMENU) IDC_NAV_RELOAD, hInst, 0); x += BUTTON_WIDTH; stopWnd = CreateWindow(L"BUTTON", L"Stop", WS_CHILD | WS_VISIBLE | BS_PUSHBUTTON | WS_DISABLED, x, 0, BUTTON_WIDTH, URLBAR_HEIGHT, hWnd, (HMENU) IDC_NAV_STOP, hInst, 0); x += BUTTON_WIDTH; editWnd = CreateWindow(L"EDIT", 0, WS_CHILD | WS_VISIBLE | WS_BORDER | ES_LEFT | ES_AUTOVSCROLL | ES_AUTOHSCROLL| WS_DISABLED, x, 0, rect.right - BUTTON_WIDTH * 4, URLBAR_HEIGHT, hWnd, 0, hInst, 0); // Assign the edit window's WNDPROC to this function so that we can // capture the enter key editWndOldProc = reinterpret_cast<WNDPROC>(GetWindowLongPtr(editWnd, GWLP_WNDPROC)); SetWindowLongPtr(editWnd, GWLP_WNDPROC, reinterpret_cast<LONG_PTR>(WndProc)); g_handler->SetEditHwnd(editWnd); g_handler->SetButtonHwnds(backWnd, forwardWnd, reloadWnd, stopWnd); rect.top += URLBAR_HEIGHT; CefWindowInfo info; CefBrowserSettings settings; if (AppIsOffScreenRenderingEnabled()) { CefRefPtr<CefCommandLine> cmd_line = AppGetCommandLine(); bool transparent = cmd_line->HasSwitch(cefclient::kTransparentPaintingEnabled); CefRefPtr<OSRWindow> osr_window = OSRWindow::Create(&g_main_browser_provider, transparent); osr_window->CreateWidget(hWnd, rect, hInst, szOSRWindowClass); info.SetAsOffScreen(osr_window->hwnd()); info.SetTransparentPainting(transparent ? TRUE : FALSE); g_handler->SetOSRHandler(osr_window.get()); } else { // Initialize window info to the defaults for a child window. info.SetAsChild(hWnd, rect); } // Creat the new child browser window CefBrowserHost::CreateBrowser(info, g_handler.get(), g_handler->GetStartupURL(), settings, NULL); return 0; } case WM_COMMAND: { CefRefPtr<CefBrowser> browser; if (g_handler.get()) browser = g_handler->GetBrowser(); wmId = LOWORD(wParam); wmEvent = HIWORD(wParam); // Parse the menu selections: switch (wmId) { case IDM_ABOUT: DialogBox(hInst, MAKEINTRESOURCE(IDD_ABOUTBOX), hWnd, About); return 0; case IDM_EXIT: if (g_handler.get()) g_handler->CloseAllBrowsers(false); return 0; case ID_WARN_CONSOLEMESSAGE: if (g_handler.get()) { std::wstringstream ss; ss << L"Console messages will be written to " << std::wstring(CefString(g_handler->GetLogFile())); MessageBox(hWnd, ss.str().c_str(), L"Console Messages", MB_OK | MB_ICONINFORMATION); } return 0; case ID_WARN_DOWNLOADCOMPLETE: case ID_WARN_DOWNLOADERROR: if (g_handler.get()) { std::wstringstream ss; ss << L"File \"" << std::wstring(CefString(g_handler->GetLastDownloadFile())) << L"\" "; if (wmId == ID_WARN_DOWNLOADCOMPLETE) ss << L"downloaded successfully."; else ss << L"failed to download."; MessageBox(hWnd, ss.str().c_str(), L"File Download", MB_OK | MB_ICONINFORMATION); } return 0; case ID_FIND: if (!hFindDlg) { // Create the find dialog. ZeroMemory(&fr, sizeof(fr)); fr.lStructSize = sizeof(fr); fr.hwndOwner = hWnd; fr.lpstrFindWhat = szFindWhat; fr.wFindWhatLen = sizeof(szFindWhat); fr.Flags = FR_HIDEWHOLEWORD | FR_DOWN; hFindDlg = FindText(&fr); } else { // Give focus to the existing find dialog. ::SetFocus(hFindDlg); } return 0; case IDC_NAV_BACK: // Back button if (browser.get()) browser->GoBack(); return 0; case IDC_NAV_FORWARD: // Forward button if (browser.get()) browser->GoForward(); return 0; case IDC_NAV_RELOAD: // Reload button if (browser.get()) browser->Reload(); return 0; case IDC_NAV_STOP: // Stop button if (browser.get()) browser->StopLoad(); return 0; case ID_TESTS_GETSOURCE: // Test the GetSource function if (browser.get()) RunGetSourceTest(browser); return 0; case ID_TESTS_GETTEXT: // Test the GetText function if (browser.get()) RunGetTextTest(browser); return 0; case ID_TESTS_POPUP: // Test a popup window if (browser.get()) RunPopupTest(browser); return 0; case ID_TESTS_REQUEST: // Test a request if (browser.get()) RunRequestTest(browser); return 0; case ID_TESTS_PLUGIN_INFO: // Test plugin info if (browser.get()) RunPluginInfoTest(browser); return 0; case ID_TESTS_ZOOM_IN: if (browser.get()) ModifyZoom(browser, 0.5); return 0; case ID_TESTS_ZOOM_OUT: if (browser.get()) ModifyZoom(browser, -0.5); return 0; case ID_TESTS_ZOOM_RESET: if (browser.get()) browser->GetHost()->SetZoomLevel(0.0); return 0; case ID_TESTS_TRACING_BEGIN: g_handler->BeginTracing(); return 0; case ID_TESTS_TRACING_END: g_handler->EndTracing(); return 0; case ID_TESTS_PRINT: if(browser.get()) browser->GetHost()->Print(); return 0; case ID_TESTS_OTHER_TESTS: if (browser.get()) RunOtherTests(browser); return 0; } break; } case WM_PAINT: hdc = BeginPaint(hWnd, &ps); EndPaint(hWnd, &ps); return 0; case WM_SETFOCUS: if (g_handler.get() && g_handler->GetBrowser()) { if (AppIsOffScreenRenderingEnabled()) { // Give focus to the OSR window. CefRefPtr<OSRWindow> osr_window = static_cast<OSRWindow*>(g_handler->GetOSRHandler().get()); if (osr_window) ::SetFocus(osr_window->hwnd()); } else { // Give focus to the browser. g_handler->GetBrowser()->GetHost()->SetFocus(true); } } return 0; case WM_SIZE: // Minimizing resizes the window to 0x0 which causes our layout to go all // screwy, so we just ignore it. if (wParam != SIZE_MINIMIZED && g_handler.get() && g_handler->GetBrowser()) { CefWindowHandle hwnd = g_handler->GetBrowser()->GetHost()->GetWindowHandle(); if (hwnd) { // Resize the browser window and address bar to match the new frame // window size RECT rect; GetClientRect(hWnd, &rect); rect.top += URLBAR_HEIGHT; int urloffset = rect.left + BUTTON_WIDTH * 4; HDWP hdwp = BeginDeferWindowPos(1); hdwp = DeferWindowPos(hdwp, editWnd, NULL, urloffset, 0, rect.right - urloffset, URLBAR_HEIGHT, SWP_NOZORDER); hdwp = DeferWindowPos(hdwp, hwnd, NULL, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, SWP_NOZORDER); EndDeferWindowPos(hdwp); } } break; case WM_ERASEBKGND: if (g_handler.get() && g_handler->GetBrowser()) { CefWindowHandle hwnd = g_handler->GetBrowser()->GetHost()->GetWindowHandle(); if (hwnd) { // Dont erase the background if the browser window has been loaded // (this avoids flashing) return 0; } } break; case WM_ENTERMENULOOP: if (!wParam) { // Entering the menu loop for the application menu. CefSetOSModalLoop(true); } break; case WM_EXITMENULOOP: if (!wParam) { // Exiting the menu loop for the application menu. CefSetOSModalLoop(false); } break; case WM_CLOSE: if (g_handler.get() && !g_handler->IsClosing()) { CefRefPtr<CefBrowser> browser = g_handler->GetBrowser(); if (browser.get()) { // Notify the browser window that we would like to close it. This // will result in a call to ClientHandler::DoClose() if the // JavaScript 'onbeforeunload' event handler allows it. browser->GetHost()->CloseBrowser(false); // Cancel the close. return 0; } } // Allow the close. break; case WM_DESTROY: // Quitting CEF is handled in ClientHandler::OnBeforeClose(). return 0; } return DefWindowProc(hWnd, message, wParam, lParam); } }
// Inject webinos.js // The file is loaded from the webinos\test\client folder if possible. // If this fails, the current folder is used. void ClientApp::InjectWebinos(CefRefPtr<CefFrame> frame) { CefRefPtr<CefCommandLine> commandLine = AppGetCommandLine(); // First try and load the platform-supplied webinos.js #if defined(OS_WIN) FilePath workingDir(commandLine->GetProgram().ToWString().c_str()); FilePath webinosJSPath = workingDir.DirName().Append(L"..\\..\\webinos\\web_root\\webinos.js"); #else FilePath workingDir(commandLine->GetProgram()); FilePath webinosJSPath = workingDir.DirName().Append("..\\..\\webinos\\web_root\\webinos.js"); #endif int64 webinosJSCodeSize; bool gotJSFile = file_util::GetFileSize(webinosJSPath, &webinosJSCodeSize); if (!gotJSFile) { // Unable to load the platform-supplied webinos.js, use the installed version. #if defined(OS_WIN) workingDir = FilePath(commandLine->GetProgram().ToWString().c_str()); webinosJSPath = workingDir.DirName().Append(L"webinos.js"); #else workingDir = FilePath(commandLine->GetProgram()); webinosJSPath = workingDir.DirName().Append("webinos.js"); #endif gotJSFile = file_util::GetFileSize(webinosJSPath, &webinosJSCodeSize); } if (gotJSFile) { char* webinosJSCode = new char[webinosJSCodeSize+1]; file_util::ReadFile(webinosJSPath, webinosJSCode, webinosJSCodeSize); webinosJSCode[webinosJSCodeSize] = 0; if (frame == NULL) { // Register as a Cef extension. CefRegisterExtension("webinos", webinosJSCode, NULL); } else { // Run the code in the frame javascript context right now, // but only if the URL refers to the widget server. int widgetServerPort; AppGetWebinosWRTConfig(NULL,&widgetServerPort); char injectionCandidate[MAX_URL_LENGTH]; sprintf(injectionCandidate,"http://localhost:%d",widgetServerPort); std::string url = frame->GetURL(); if (url.substr(0,strlen(injectionCandidate)) == injectionCandidate) frame->ExecuteJavaScript(webinosJSCode, url, 0); } delete[] webinosJSCode; } else { LOG(ERROR) << "Can't find webinos.js"; } }
void ClientApp::OnContextCreated(CefRefPtr<CefBrowser> browser, CefRefPtr<CefFrame> frame, CefRefPtr<CefV8Context> context) { /** N.B. this code is poor and needs tidying up **/ CefRefPtr<CefCommandLine> commandLine = AppGetCommandLine(); #if defined(OS_WIN) FilePath workingDir(commandLine->GetProgram().ToWString().c_str()); FilePath bootPath = workingDir.DirName().Append(L"webinosBoot.js"); #else FilePath workingDir(commandLine->GetProgram()); FilePath bootPath = workingDir.DirName().Append("webinosBoot.js"); #endif int64 bootDataSize; if (file_util::GetFileSize(bootPath, &bootDataSize)) { char* bootData = new char[bootDataSize+1]; file_util::ReadFile(bootPath, bootData, bootDataSize); bootData[bootDataSize] = 0; std::string widgetInterface; webinos::WidgetConfig cfg; if (cfg.LoadFromURL(frame->GetURL())) { std::string widgetArgs; AppGetWidgetArgs(cfg.GetSessionId(),widgetArgs); /* We need to expose the w3c widget interface (http://www.w3.org/TR/widgets-apis/) interface Widget { readonly attribute DOMString author; readonly attribute DOMString description; readonly attribute DOMString name; readonly attribute DOMString shortName; readonly attribute DOMString version; readonly attribute DOMString id; readonly attribute DOMString authorEmail; readonly attribute DOMString authorHref; readonly attribute WidgetStorage preferences; <!-- TBD! readonly attribute unsigned long height; readonly attribute unsigned long width; }; */ std::stringstream wifStr(std::stringstream::in | std::stringstream::out); wifStr << "\ // Widget interface\r\n\ window.widget = { \r\n\ author: \"" << cfg.author() << "\",\r\n\ description: \"" << cfg.description() << "\",\r\n\ name: \"" << cfg.name() << "\",\r\n\ shortName: \"" << cfg.shortName() << "\",\r\n\ version: \"" << cfg.version() << "\",\r\n\ id: \"" << cfg.id() << "\",\r\n\ authorEmail: \"" << cfg.authorEmail() << "\",\r\n\ authorHref: \"" << cfg.authorHref() << "\",\r\n\ preferences: {},\r\n\
int main(int argc, char* argv[]) { CefMainArgs main_args(argc, argv); g_appStartupTime = time(NULL); gtk_init(&argc, &argv); CefRefPtr<ClientApp> app(new ClientApp); // Execute the secondary process, if any. int exit_code = CefExecuteProcess(main_args, app.get(), NULL); if (exit_code >= 0) return exit_code; //Retrieve the current working directory if (!getcwd(szWorkingDir, sizeof (szWorkingDir))) return -1; GtkWidget* window; // Parse command line arguments. AppInitCommandLine(argc, argv); CefSettings settings; // Populate the settings based on command line arguments. AppGetSettings(settings, app); settings.no_sandbox = TRUE; // Check cache_path setting if (CefString(&settings.cache_path).length() == 0) { CefString(&settings.cache_path) = AppGetCachePath(); } CefRefPtr<CefCommandLine> cmdLine = AppGetCommandLine(); if (cmdLine->HasSwitch(client::switches::kStartupPath)) { szInitialUrl = cmdLine->GetSwitchValue(client::switches::kStartupPath); } else { szInitialUrl = AppGetRunningDirectory(); szInitialUrl.append("/dev/src/index.html"); if (!FileExists(szInitialUrl)) { szInitialUrl = AppGetRunningDirectory(); szInitialUrl.append("/www/index.html"); if (!FileExists(szInitialUrl)) { if (GetInitialUrl() < 0) return 0; } } } // Initialize CEF. CefInitialize(main_args, settings, app.get(), NULL); // Set window icon std::vector<std::string> icons(APPICONS, APPICONS + sizeof(APPICONS) / sizeof(APPICONS[0]) ); GList *list = NULL; for (int i = 0; i < icons.size(); ++i) { std::string path = icons[i]; GdkPixbuf *icon = gdk_pixbuf_new_from_file(path.c_str(), NULL); if (!icon) continue; list = g_list_append(list, icon); } window = gtk_window_new(GTK_WINDOW_TOPLEVEL); gtk_window_set_default_size(GTK_WINDOW(window), 800, 600); gtk_window_set_icon_list(GTK_WINDOW(window), list); // Free icon list g_list_foreach(list, (GFunc) g_object_unref, NULL); g_list_free(list); GtkWidget* vbox = gtk_vbox_new(FALSE, 0); GtkWidget* menuBar = gtk_menu_bar_new(); // GtkWidget* debug_menu = CreateMenu(menuBar, "Tests"); // AddMenuEntry(debug_menu, "Hello World Menu", // G_CALLBACK(GetSourceActivated)); gtk_box_pack_start(GTK_BOX(vbox), menuBar, FALSE, FALSE, 0); g_signal_connect(G_OBJECT(window), "delete_event", G_CALLBACK(HandleQuit), NULL); g_signal_connect(G_OBJECT(window), "destroy", G_CALLBACK(gtk_widget_destroyed), &window); add_handler_id = g_signal_connect(G_OBJECT(window), "add", G_CALLBACK(HandleAdd), NULL); // g_signal_connect(G_OBJECT(window), "destroy", // G_CALLBACK(destroy), NULL); // Create the handler. g_handler = new ClientHandler(); g_handler->SetMainHwnd(vbox); // Create the browser view. CefWindowInfo window_info; CefBrowserSettings browserSettings; browserSettings.web_security = STATE_DISABLED; window_info.SetAsChild(vbox); CefBrowserHost::CreateBrowser( window_info, static_cast<CefRefPtr<CefClient> >(g_handler), "file://"+szInitialUrl, browserSettings, NULL); gtk_container_add(GTK_CONTAINER(window), vbox); gtk_widget_show_all(GTK_WIDGET(window)); // Install an signal handler so we clean up after ourselves. signal(SIGINT, TerminationSignalHandler); signal(SIGTERM, TerminationSignalHandler); // Start the node server process startNodeProcess(); CefRunMessageLoop(); CefShutdown(); return 0; }