def messageReceivedCb(self, message): ''' @param: message string ''' actWin = self.getWindow() actUrl = QUrl() if message.startswith('URL:'): url = QUrl.fromUserInput(message[4:]) self.addNewTab(url) actWin = self.getWindow() elif message.startswith('ACTION:'): text = message[7:] if text == 'NewTab': self.addNewTab() elif text == 'NewWindow': actWin = self.createWindow(const.BW_NewWindow) elif text == 'ShowDownloadManager': self.downloadManager().show() actWin = self.downloadManager() elif text == 'ToggleFullScreen' and actWin: assert (isinstance(actWin, BrowserWindow)) actWin.toggleFullScreen() elif text.startswith('OpenUrlInCurrentTab'): actUrl = QUrl.fromUserInput(text[:19]) elif text.startswith('OpenUrlInNewTab'): # user attempted to start another instance. let's open a new one self.createWindow(const.BW_NewWindow, QUrl.fromUserInput(text[18:])) return else: actWin = self.createWindow(const.BW_NewWindow) if not actWin: if not self.isClosing(): # It can only occur if download manager window was still opened self.createWindow(const.BW_NewWindow, actUrl) return actWin.setWindowState(actWin.windowState() & Qt.WindowMinimized) actWin.raise_() actWin.activateWindow() actWin.setFocus() win = actWin if isinstance(win, BrowserWindow) and not actWin.isEmpty(): win.loadAddress(actUrl)
def addTabFromClipboard(self): # QString selectionClipboard = QApplication.clipboard().text( QClipboard.Selection) # QUrl guessedUrl = QUrl.fromUserInput(selectionClipboard) if not guessedUrl.isEmpty(): self.addViewByUrl(guessedUrl, const.NT_SelectedNewEmptyTab)
def _paste_and_go(window, in_current_tab=True): c = QApplication.clipboard() for mode in c.Clipboard, c.Selection: text = c.text(mode).strip() if text: if text.partition(':')[0].lower() in {'file', 'http', 'https', 'about'}: qurl = QUrl.fromUserInput(text) if qurl.isValid() and not qurl.isEmpty(): window.open_url(qurl, in_current_tab=in_current_tab) return window.show_status_message(_('No URL in clipboard'), 2, 'success')
def _paste_and_go(window, in_current_tab=True): c = QApplication.clipboard() for mode in c.Clipboard, c.Selection: text = c.text(mode).strip() if text: if text.partition(':')[ 0].lower() in {'file', 'http', 'https', 'about', 'chrome'}: qurl = QUrl.fromUserInput(text) if qurl.isValid() and not qurl.isEmpty(): window.open_url(qurl, in_current_tab=in_current_tab) return window.show_status_message(_('No URL in clipboard'), 2, 'success')
def _createSelectedTextContextMenu(self, menu, hitTest): ''' @param: menu QMenu @param: hitTest WebHitTestResult ''' selectedText = self.page().selectedText() menu.addSeparator() if self.pageAction(QWebEnginePage.Copy) not in menu.actions(): menu.addAction(self.pageAction(QWebEnginePage.Copy)) menu.addAction(QIcon.fromTheme('mail-message-new'), _('Send text...'), self._sendTextByMail).setData(selectedText) menu.addSeparator() # 379: Remove newlines selectedString = selectedText.strip() if '.' not in selectedString: # Try to add .com selectedString += '.com' guessedUrl = QUrl.fromUserInput(selectedString) if self.isUrlValid(guessedUrl): act = Action(QIcon.fromTheme('document-open-remote'), _('Go to &web address'), menu) act.setData(guessedUrl) act.triggered.connect(self._openActionUrl) act.ctrlTriggered.connect(lambda: self.userDefinedOpenUrlInNewTab()) menu.addAction(act) menu.addSeparator() selectedText = selectedText[:20] # KDE is displaying newlines in menu actions ... weird selectedText = selectedText.replace('\n', ' ').replace('\t', ' ') engine = gVar.app.searchEnginesManager().defaultEngine() act = Action(engine.icon, _('Search "%s .." with %s') % (selectedText, engine.name), menu) act.triggered.connect(self._searchSelectedText) act.ctrlTriggered.connect(self._searchSelectedTextInBackgroundTab) menu.addAction(act) # Search with ... swMenu = Menu(_('Search with...'), menu) swMenu.setCloseOnMiddleClick(True) searchManager = gVar.app.searchEnginesManager() for en in searchManager.allEngines(): act = Action(en.icon, en.name, swMenu) act.setData(en) act.triggered.connect(self._searchSelectedText) act.ctrlTriggered.connect(self._searchSelectedTextInBackgroundTab) swMenu.addAction(act) menu.addMenu(swMenu)
def parse_url(url_or_path): return QUrl.fromUserInput(url_or_path, os.getcwd())
def loadAction(cls, text): ''' @return: LoadAction ''' action = cls.LoadAction() t = text.strip() if not t: return action # Check for Search Engine shortcut firstSpacePos = t.find(' ') if gVar.appSettings.searchFromAddressBar and firstSpacePos != -1: shortcut = t[:firstSpacePos] searchedString = t[firstSpacePos:].strip() en = gVar.app.searchEnginesManager().engineForShortcut(shortcut) if en.isValid(): action.type = cls.LoadAction.Search action.searchEngine = en url = gVar.app.searchEnginesManager().searchResult( en, searchedString) action.loadRequest = LoadRequest(url) return action # Check for Bookmark keyword items = gVar.app.bookmarks().searchKeyword(t) if items: item = items[0] action.type = cls.LoadAction.Bookmark action.bookmark = item action.loadRequest.setUrl(item.url()) return action if not gVar.appSettings.searchFromAddressBar: guessedUrl = QUrl.fromUserInput(t) if guessedUrl.isValid(): action.type = cls.LoadAction.Url action.loadRequest = LoadRequest(guessedUrl) return action # Check for one word search if t != 'localhost' \ and gVar.appTools.containsSpace(t) \ and '.' not in t \ and ':' not in t \ and '/' not in t: action.type = cls.LoadAction.Search action.searchEngine = cls.searchEngine() url = gVar.app.searchEnginesManager().searchResult( cls.searchEngine(), t) action.loadRequest = LoadRequest(url) return action # Otherwise load as url guessedUrl = QUrl.fromUserInput(t) if guessedUrl.isValid(): # Always allow javascript: to be loaded forceLoad = guessedUrl.scheme() == 'javascript' # Only allow spaces in query urlRaw = guessedUrl.toString(QUrl.RemoveQuery) if forceLoad or not gVar.appTools.containsSpace(t) or \ not gVar.appTools.contiansSpace(urlRaw): # Only allow supported schemes if forceLoad or guessedUrl.scheme( ) in WebPage.supportedSchemes(): action.type = cls.LoadAction.Url action.loadRequest = LoadRequest(guessedUrl) return action # Search when creating url failed action.type = cls.LoadAction.Search action.searchEngine = cls.searchEngine() url = gVar.app.searchEnginesManager().searchResult( cls.searchEngine(), t) action.loadRequest = LoadRequest(url) return action
def __init__(self, argv): # noqa 901 super(MainApplication, self).__init__(argv) self._isPrivate = False self._isPortable = True self._isClosing = False self._isStartingAfterCrash = False self._history = None # History self._bookmarks = None # Bookmarks self._autoFill = None # AutoFill self._cookieJar = None # CookieJar self._plugins = None # PluginProxy self._browsingLibrary = None # BrowsingLibrary self._networkManager = None self._restoreManager = None self._sessionManager = None self._downloadManager = None self._userAgentManager = None self._searchEnginesManager = None self._closedWindowsManager = None self._protocolHandlerManager = None self._html5PermissionsManager = None self._desktopNotifications = None # DesktopNotificationsFactory self._webProfile = None # QWebEngineProfile self._autoSaver = None self._proxyStyle = None self._wmClass = QByteArray() self._windows = [] self._lastActiveWindow = None self._postLaunchActions = [] self.setAttribute(Qt.AA_UseHighDpiPixmaps) self.setAttribute(Qt.AA_DontCreateNativeWidgetSiblings) self.setApplicationName('demo') self.setOrganizationDomain('org.autowin') self.setWindowIcon(QIcon.fromTheme('demo', QIcon(':/icons/demo.svg'))) self.setDesktopFileName('orig.autowin.demo') self.setApplicationVersion('1.0') # Set fallback icon theme (eg. on Windows/Mac) if QIcon.fromTheme('view-refresh').isNull(): QIcon.setThemeName('breeze-fallback') # QSQLITE database plugin is required if not QSqlDatabase.isDriverAvailable('QSQLITE'): QMessageBox.Critical( None, 'Error', 'Qt SQLite database plugin is not available.' ' Please install it and restart the application.') self._isClosing = True return if const.OS_WIN: # Set default app font (needed for N'ko) fontId = QFontDatabase.addApplicationFont('font.ttf') if fontId != -1: families = QFontDatabase.applicationFontFamilies(fontId) if not families.empty(): self.setFont(QFont(families.at(0))) startUrl = QUrl() startProfile = '' messages = [] noAddons = False newInstance = False if len(argv) > 1: cmd = CommandLineOptions() for pair in cmd.getActions(): action = pair.action text = pair.text if action == const.CL_StartWithoutAddons: noAddons = True elif action == const.CL_StartWithProfile: startProfile = text elif action == const.CL_StartPortable: self._isPortable = True elif action == const.CL_NewTab: messages.append("ACTION:NewTab") self._postLaunchActions.append(self.OpenNewTab) elif action == const.CL_NewWindow: messages.append("ACTION:NewWindow") elif action == const.CL_ToggleFullScreen: messages.append("ACTION:ToggleFullScreen") self._postLaunchActions.append(self.ToggleFullScreen) elif action == const.CL_ShowDownloadManager: messages.append("ACTION:ShowDownloadManager") self._postLaunchActions.append(self.OpenDownloadManager) elif action == const.CL_StartPrivateBrowsing: self._isPrivate = True elif action == const.CL_StartNewInstance: newInstance = True elif action == const.CL_OpenUrlInCurrentTab: startUrl = QUrl.fromUserInput(text) messages.append("ACTION:OpenUrlInCurrentTab" + text) elif action == const.CL_OpenUrlInNewWindow: startUrl = QUrl.fromUserInput(text) messages.append("ACTION:OpenUrlInNewWindow" + text) elif action == const.CL_OpenUrl: startUrl = QUrl.fromUserInput(text) messages.append("URL:" + text) elif action == const.CL_ExitAction: self._isClosing = True return elif action == const.CL_WMClass: self._wmClass = text if not self.isPortable(): appConf = QSettings( pathjoin(self.applicationDirPath(), '%s.conf' % const.APPNAME), QSettings.IniFormat) appConf.value('Config/Portable') if self.isPortable(): print('%s: Running in Portable Mode.' % const.APPNAME) DataPaths.setPortableVersion() # Don't start single application in private browsing if not self.isPrivate(): appId = 'org.autowin.mc' if self.isPortable(): appId += '.Portable' if self.isTestModeEnabled(): appId += '.TestMode' if newInstance: if not startProfile or startProfile == 'default': print( 'New instance cannot be started with default profile!') else: # Generate unique appId so it is possible to start more # separate instances of the same profile. It is dangerous to # run more instance of the same profile, but if the user # wants it, we should allow it. appId += '.' + str(QDateTime.currentMSecsSinceEpoch()) self.setAppId(appId) # If there is nothing to tell other instance, we need to at least weak it if not messages: messages.append(' ') if self.isRunning(): self._isClosing = True for message in messages: self.sendMessage(message) return if const.OS_MACOS: self.setQuitOnLastWindowClosed(False) # TODO: # disable tabbing issue #2261 # extern void disableWindowTabbing(); # self.disableWindowTabbing() else: self.setQuitOnLastWindowClosed(True) QSettings.setDefaultFormat(QSettings.IniFormat) QDesktopServices.setUrlHandler('http', self.addNewTab) QDesktopServices.setUrlHandler('https', self.addNewTab) QDesktopServices.setUrlHandler('ftp', self.addNewTab) profileManager = ProfileManager() profileManager.initConfigDir() profileManager.initCurrentProfile(startProfile) Settings.createSettings( pathjoin(DataPaths.currentProfilePath(), 'settings.ini')) NetworkManager.registerSchemes() if self.isPrivate(): self._webProfile = QWebEngineProfile() else: self._webProfile = QWebEngineProfile.defaultProfile() self._webProfile.downloadRequested.connect(self.downloadRequested) self._networkManager = NetworkManager(self) self.setupUserScripts() if not self.isPrivate() and not self.isTestModeEnabled(): self._sessionManager = SessionManager(self) self._autoSaver = AutoSaver(self) self._autoSaver.save.connect( self._sessionManager.autoSaveLastSession) settings = Settings() settings.beginGroup('SessionRestore') wasRunning = settings.value('isRunning', False) wasRestoring = settings.value('isRestoring', False) settings.setValue('isRunning', True) settings.setValue('isRestoring', wasRunning) settings.endGroup() settings.sync() self._isStartingAfterCrash = bool(wasRunning and wasRestoring) if wasRunning: QTimer.singleShot( 60 * 1000, lambda: Settings().setValue( 'SessionRestore/isRestoring', False)) # we have to ask about startup session before creating main window if self._isStartingAfterCrash and self.afterLaunch( ) == self.SelectSession: self._restoreManager = RestoreManager( self.sessionManager().askSessionFromUser()) self.loadSettings() self._plugins = PluginProxy(self) self._autoFill = AutoFill(self) self.app.protocolHandlerManager() if not noAddons: self._plugins.loadPlugins() window = self.createWindow(const.BW_FirstAppWindow, startUrl) window.startingCompleted.connect(self.restoreOverrideCursor) self.focusChanged.connect(self.onFocusChanged) if not self.isPrivate() and not self.isTestModeEnabled(): # check updates settings = Settings() checkUpdates = settings.value('Web-Browser-Settings/CheckUpdates', True) if checkUpdates: Updater(window) self.sessionManager().backupSavedSessions() if self._isStartingAfterCrash or self.afterLaunch( ) == self.RestoreSession: self._restoreManager = RestoreManager( self.sessionManager().lastActiveSessionPath()) if not self._restoreManager.isValid(): self.destroyRestoreManager() if not self._isStartingAfterCrash and self._restoreManager: self.restoreSession(window, self._restoreManager.restoreData()) QSettings.setPath(QSettings.IniFormat, QSettings.UserScope, DataPaths.currentProfilePath()) self.messageReceived.connect(self.messageReceivedCb) self.aboutToQuit.connect(self.saveSettings) QTimer.singleShot(0, self.postLaunch)
def urlFromUserInput(self, url): ''' @param: QString ''' return QUrl.fromUserInput(url).toString()