diff --git a/.clang-format b/.clang-format index 5778e924..e5e8ccc2 100644 --- a/.clang-format +++ b/.clang-format @@ -1,89 +1,2 @@ Language: Cpp -# BasedOnStyle: Google -AccessModifierOffset: -1 -AlignAfterOpenBracket: Align -AlignConsecutiveAssignments: false -AlignConsecutiveDeclarations: false -AlignEscapedNewlinesLeft: true -AlignOperands: true -AlignTrailingComments: true -AllowAllParametersOfDeclarationOnNextLine: true -AllowShortBlocksOnASingleLine: false -AllowShortCaseLabelsOnASingleLine: false -AllowShortFunctionsOnASingleLine: All -AllowShortIfStatementsOnASingleLine: true -AllowShortLoopsOnASingleLine: true -AlwaysBreakAfterDefinitionReturnType: None -AlwaysBreakAfterReturnType: None -AlwaysBreakBeforeMultilineStrings: true -AlwaysBreakTemplateDeclarations: true -BinPackArguments: true -BinPackParameters: true -BraceWrapping: - AfterClass: true - AfterControlStatement: true - AfterEnum: true - AfterFunction: true - AfterNamespace: true - AfterObjCDeclaration: true - AfterStruct: true - AfterUnion: true - BeforeCatch: true - BeforeElse: true - IndentBraces: false -BreakBeforeBinaryOperators: None -BreakBeforeBraces: Allman -BreakBeforeTernaryOperators: true -BreakConstructorInitializers: BeforeColon -BreakConstructorInitializersBeforeComma: false -ColumnLimit: 80 -CommentPragmas: '^ IWYU pragma:' -ConstructorInitializerAllOnOneLineOrOnePerLine: false -ConstructorInitializerIndentWidth: 0 -ContinuationIndentWidth: 2 -Cpp11BracedListStyle: true -DerivePointerAlignment: true -DisableFormat: false -ExperimentalAutoDetectBinPacking: false -ForEachMacros: [ foreach, Q_FOREACH, BOOST_FOREACH ] -IncludeCategories: - - Regex: '^<.*\.h>' - Priority: 1 - - Regex: '^<.*' - Priority: 2 - - Regex: '.*' - Priority: 3 -IndentCaseLabels: true -IndentWidth: 2 -IndentWrappedFunctionNames: false -KeepEmptyLinesAtTheStartOfBlocks: false -MacroBlockBegin: '' -MacroBlockEnd: '' -MaxEmptyLinesToKeep: 1 -NamespaceIndentation: None -ObjCBlockIndentWidth: 2 -ObjCSpaceAfterProperty: false -ObjCSpaceBeforeProtocolList: false -PenaltyBreakBeforeFirstCallParameter: 1 -PenaltyBreakComment: 300 -PenaltyBreakFirstLessLess: 120 -PenaltyBreakString: 1000 -PenaltyExcessCharacter: 1000000 -PenaltyReturnTypeOnItsOwnLine: 200 -PointerAlignment: Left -ReflowComments: true -SortIncludes: true -SpaceAfterCStyleCast: false -SpaceBeforeAssignmentOperators: true -SpaceBeforeParens: ControlStatements -SpaceInEmptyParentheses: false -SpacesBeforeTrailingComments: 2 -SpacesInAngles: false -SpacesInContainerLiterals: true -SpacesInCStyleCastParentheses: false -SpacesInParentheses: false -SpacesInSquareBrackets: false -Standard: Auto -TabWidth: 2 -UseTab: Never - +BasedOnStyle: Mozilla diff --git a/data/translations/Internationalization_ca.ts b/data/translations/Internationalization_ca.ts index f69794b2..5df3a4d8 100644 --- a/data/translations/Internationalization_ca.ts +++ b/data/translations/Internationalization_ca.ts @@ -4,12 +4,12 @@ AppLauncher - + App Launcher Llançador d'aplicacions - + Choose an app to open the capture Trieu una aplicació per obrir la captura @@ -32,18 +32,18 @@ Segueix obert després de la selecció - - + + Error Error - + Unable to launch in terminal. No es pot iniciar a la terminal. - + Unable to write in No es pot escriure a @@ -51,12 +51,12 @@ ArrowTool - + Arrow Fletxa - + Set the Arrow as the paint tool Estableix la fletxa com a eina de dibuix @@ -64,12 +64,12 @@ BlurTool - + Blur Desenfocament - + Set Blur as the paint tool Estableix el desenfocament com a eina de dibuix @@ -77,47 +77,47 @@ CaptureLauncher - + <b>Capture Mode</b> - + Rectangular Region - + Full Screen (All Monitors) - + No Delay - + second - + seconds - + Take new screenshot - + Area: - + Delay: @@ -125,13 +125,13 @@ CaptureWidget - + Unable to capture screen Impossible capturar la pantalla Imposible capturar la pantalla - + Select an area with the mouse, or press Esc to exit. Press Enter to capture the screen. Press Right Click to show the color picker. @@ -143,12 +143,12 @@ Press Space to open the side panel. CircleCountTool - + Circle Counter - + Add an autoincrementing counter bubble @@ -156,12 +156,12 @@ Press Space to open the side panel. CircleTool - + Circle Cercle - + Set the Circle as the paint tool Estableix el cercle com a eina de dibuix @@ -169,7 +169,7 @@ Press Space to open the side panel. ConfigWindow - + Configuration Configuració @@ -179,7 +179,7 @@ Press Space to open the side panel. Interfície - + Filename Editor Editor de noms @@ -192,27 +192,27 @@ Press Space to open the side panel. Controller - + &Open Launcher - + &Configuration &Configuració - + &Information &Informació - + &Quit &Ix - + &Take Screenshot @@ -220,12 +220,12 @@ Press Space to open the side panel. CopyTool - + Copy Copia - + Copy the selection into the clipboard @@ -233,7 +233,7 @@ Press Space to open the side panel. DBusUtils - + Unable to connect via DBus Impossible connectar mitjançant DBus @@ -241,12 +241,12 @@ Press Space to open the side panel. ExitTool - + Exit Ix - + Leave the capture screen Ix de la pantalla de captura @@ -254,47 +254,47 @@ Press Space to open the side panel. FileNameEditor - + Edit the name of your captures: Editeu el nom de les vostres captures: - + Edit: Edita: - + Preview: Previsualització: - + Save Guarda - + Saves the pattern Guarda el patró - + Reset Reinicialitza - + Restores the saved pattern Restaura el patró guardat - + Clear Neteja - + Deletes the name Elimina el patró @@ -302,112 +302,112 @@ Press Space to open the side panel. GeneneralConf - + Show help message Mostra el missatge d'ajuda - + Show the help message at the beginning in the capture mode. Mostra el missatge d'ajuda en iniciar el mode de captura. - - + + Show desktop notifications Mostra les notificacions d'escriptori - + Show tray icon Mostra la icona en la barra de tasques - + Show the systemtray icon Mostra la icona en la barra de tasques - - + + Import Importar - - - + + + Error Error - + Unable to read file. Impossible llegir el fitxer. - - + + Unable to write file. Impossible escriure al fitxer. - + Save File Guardar Arxiu - + Confirm Reset Confirmar Reset - + Are you sure you want to reset the configuration? Esteu segur que voleu reiniciar la configuració? - + Configuration File Fitxer de Configuració - + Export Exportar - + Reset Reset - + Launch at startup Llançament a l'inici - + Launch Flameshot - + Close after capture - + Close after taking a screenshot - + Copy URL after upload - + Copy URL and close window after upload @@ -415,48 +415,48 @@ Press Space to open the side panel. ImgurUploader - + Upload to Imgur Puja a Imgur - + Uploading Image S'està pujant la imatge - + Copy URL Copia l'URL - + Open URL Obri l'URL - + Image to Clipboard. Imatge al porta-retalls. - - + + Unable to open the URL. No es pot obrir l'URL. - + URL copied to clipboard. L'URL s'ha copiat al porta-retalls. - + Screenshot copied to clipboard. La captura s'ha copiat al porta-retalls. - + Delete image @@ -464,12 +464,12 @@ Press Space to open the side panel. ImgurUploaderTool - + Image Uploader Puja la imatge - + Upload the selection to Imgur Puja la selecció a Imgur @@ -477,7 +477,7 @@ Press Space to open the side panel. InfoWindow - + About Quant a @@ -497,77 +497,77 @@ Press Space to open the side panel. Roda del ratolí - + Move selection 1px Mou la selecció 1 px - + Resize selection 1px Redimensiona la selecció 1 px - + Quit capture Ix de la captura - + Copy to clipboard Copia al porta-retalls - + Save selection as a file Guarda la selecció com a fitxer - + Undo the last modification Desfés l'última modificació - + Toggle visibility of sidebar with options of the selected tool - + Show color picker Mostra el selector de color - + Change the tool's thickness Canvia el gruix de l'eina - + Key Tecla - + Description Descripció - + <u><b>License</b></u> <u><b>Llicència</b></u> - + <u><b>Version</b></u> <u><b>Versió</b></u> - + <u><b>Shortcuts</b></u> <u><b>Dreceres</b></u> - + Available shortcuts in the screen capture mode. Dreceres disponibles en el mode de captura de pantalla. @@ -575,12 +575,12 @@ Press Space to open the side panel. LineTool - + Line Línia - + Set the Line as the paint tool Estableix la línia com a eina de dibuix @@ -588,12 +588,12 @@ Press Space to open the side panel. MarkerTool - + Marker Marcador - + Set the Marker as the paint tool Estableix el marcador com a eina de dibuix @@ -601,12 +601,12 @@ Press Space to open the side panel. MoveTool - + Move Mou - + Move the selection area Mou la selecció @@ -614,12 +614,12 @@ Press Space to open the side panel. PencilTool - + Pencil Llapis - + Set the Pencil as the paint tool Estableix el llapis com a eina de dibuix @@ -627,12 +627,12 @@ Press Space to open the side panel. PinTool - + Pin Tool - + Pin image on the desktop @@ -640,38 +640,38 @@ Press Space to open the side panel. QObject - + Save Error S'ha produït un error en guardar - + Capture saved as Anomena i guarda la captura - + Error trying to save as S'ha produït un error en anomenar i guardar - - - - + + + + Unable to connect via DBus No es pot connectar mitjançant DBus - + Error Error - + Unable to write in No es pot escriure a @@ -681,7 +681,7 @@ Press Space to open the side panel. - + URL copied to clipboard. L'URL s'ha copiat al porta-retalls. @@ -689,12 +689,12 @@ Press Space to open the side panel. RectangleTool - + Rectangle Rectangle - + Set the Rectangle as the paint tool Estableix el rectangle com a eina de dibuix @@ -702,12 +702,12 @@ Press Space to open the side panel. RedoTool - + Redo - + Redo the next modification @@ -715,12 +715,12 @@ Press Space to open the side panel. SaveTool - + Save Guarda - + Save the capture Guarda la captura @@ -728,7 +728,7 @@ Press Space to open the side panel. ScreenGrabber - + Unable to capture screen Imposible capturar la pantalla @@ -736,12 +736,12 @@ Press Space to open the side panel. SelectionTool - + Rectangular Selection Selecció rectangular - + Set Selection as the paint tool Estableix la selecció com a eina de dibuix @@ -749,22 +749,22 @@ Press Space to open the side panel. SidePanelWidget - + Active thickness: - + Active color: - + Press ESC to cancel - + Grab Color @@ -772,12 +772,12 @@ Press Space to open the side panel. SizeIndicatorTool - + Selection Size Indicator Indicador de mida de selecció - + Show the dimensions of the selection (X Y) Mostra les mides de la selecció (X Y) @@ -785,107 +785,107 @@ Press Space to open the side panel. StrftimeChooserWidget - + Century (00-99) Segle (00-99) - + Year (00-99) Any (00-99) - + Year (2000) Any (2000) - + Month Name (jan) Nom del mes (jul) - + Month Name (january) Nom del mes (juliol) - + Month (01-12) Mes (01-12) - + Week Day (1-7) Dia de la setmana (1-7) - + Week (01-53) Setmana (01-53) - + Day Name (mon) Nom del dia (dg) - + Day Name (monday) Nom del dia (diumenge) - + Day (01-31) Dia (01-31) - + Day of Month (1-31) Dia del mes (1-31) - + Day (001-366) Dia (001-366) - + Hour (00-23) Hora (00-23) - + Hour (01-12) Hora (01-12) - + Minute (00-59) Minut (00-59) - + Second (00-59) Segon (00-59) - + Full Date (%m/%d/%y) Data (%m/%d/%y) - + Full Date (%Y-%m-%d) Data (%Y-%m-%d) - + Time (%H-%M-%S) - + Time (%H-%M) @@ -893,7 +893,7 @@ Press Space to open the side panel. SystemNotification - + Flameshot Info @@ -901,22 +901,22 @@ Press Space to open the side panel. TextConfig - + StrikeOut - + Underline - + Bold - + Italic @@ -924,12 +924,12 @@ Press Space to open the side panel. TextTool - + Text - + Add text to your capture @@ -937,37 +937,37 @@ Press Space to open the side panel. UIcolorEditor - + UI Color Editor Editor de color de la interfície - + Change the color moving the selectors and see the changes in the preview buttons. Canvieu el color movent els selectors i observeu els canvis en els botons de previsualització. - + Select a Button to modify it Seleccioneu un botó per a modificar-lo - + Main Color Color principal - + Click on this button to set the edition mode of the main color. Feu clic en aquest botó per a aplicar el mode d'edició per al color principal. - + Contrast Color Color de contrast - + Click on this button to set the edition mode of the contrast color. Feu clic en aquest botó per a aplicar el mode d'edició per al color de contrast. @@ -975,12 +975,12 @@ Press Space to open the side panel. UndoTool - + Undo Desfés - + Undo the last modification Desfés l'última modificació @@ -988,17 +988,17 @@ Press Space to open the side panel. VisualsEditor - + Opacity of area outside selection: Opacitat de la zona fora de la selecció: - + Button Selection Selecció de botó - + Select All Selecciona-ho tot diff --git a/data/translations/Internationalization_de_DE.ts b/data/translations/Internationalization_de_DE.ts index 9ca35784..07624417 100644 --- a/data/translations/Internationalization_de_DE.ts +++ b/data/translations/Internationalization_de_DE.ts @@ -4,12 +4,12 @@ AppLauncher - + App Launcher Anwendungs Starter - + Choose an app to open the capture Wähle eine Anwendung um die Auswahl zu öffnen @@ -32,18 +32,18 @@ Nach Auswahl geöffnet lassen - - + + Error Fehler - + Unable to write in Kein Schreibzugriff auf - + Unable to launch in terminal. Kann im Terminal nicht geöffnet werden. @@ -51,12 +51,12 @@ ArrowTool - + Arrow Pfeil - + Set the Arrow as the paint tool Wähle den Pfeil als Werkzeug @@ -64,12 +64,12 @@ BlurTool - + Blur Verwischen - + Set Blur as the paint tool Wähle Verwischen als Werkzeug @@ -77,47 +77,47 @@ CaptureLauncher - + <b>Capture Mode</b> - + Rectangular Region - + Full Screen (All Monitors) - + No Delay - + second - + seconds - + Take new screenshot - + Area: - + Delay: @@ -125,12 +125,12 @@ CaptureWidget - + Unable to capture screen Bereich kann nicht erfasst werden - + Select an area with the mouse, or press Esc to exit. Press Enter to capture the screen. Press Right Click to show the color picker. @@ -146,12 +146,12 @@ Drücke die Leertaste um das Seitenmenü zu öffnen. CircleCountTool - + Circle Counter - + Add an autoincrementing counter bubble @@ -159,12 +159,12 @@ Drücke die Leertaste um das Seitenmenü zu öffnen. CircleTool - + Circle Kreis - + Set the Circle as the paint tool Wähle den Kreis als Werkzeug @@ -172,7 +172,7 @@ Drücke die Leertaste um das Seitenmenü zu öffnen. ConfigWindow - + Configuration Einstellungen @@ -182,7 +182,7 @@ Drücke die Leertaste um das Seitenmenü zu öffnen. Benutzeroberfläche - + Filename Editor Dateinamen Editor @@ -195,27 +195,27 @@ Drücke die Leertaste um das Seitenmenü zu öffnen. Controller - + &Take Screenshot &Bildschirmaufnahme anfertigen - + &Open Launcher - + &Configuration &Einstellungen - + &Information &Informationen - + &Quit &Beenden @@ -223,12 +223,12 @@ Drücke die Leertaste um das Seitenmenü zu öffnen. CopyTool - + Copy Kopieren - + Copy the selection into the clipboard Auswahl in die Zwischenablage kopieren @@ -236,7 +236,7 @@ Drücke die Leertaste um das Seitenmenü zu öffnen. DBusUtils - + Unable to connect via DBus Kann nicht via DBus verbinden @@ -244,12 +244,12 @@ Drücke die Leertaste um das Seitenmenü zu öffnen. ExitTool - + Exit Beenden - + Leave the capture screen Auswahl beenden @@ -257,47 +257,47 @@ Drücke die Leertaste um das Seitenmenü zu öffnen. FileNameEditor - + Edit the name of your captures: Bearbeite den Namen deiner Aufnahmen: - + Edit: Bearbeite: - + Preview: Vorschau: - + Save Speichern - + Saves the pattern Speichere die Vorlage - + Reset Zurücksetzen - + Restores the saved pattern Setzt die gespeicherte Vorlage zurück - + Clear Löschen - + Deletes the name Löscht den Namen @@ -305,112 +305,112 @@ Drücke die Leertaste um das Seitenmenü zu öffnen. GeneneralConf - - + + Import Importieren - - - + + + Error Fehler - + Unable to read file. Datei kann nicht gelesen werden. - - + + Unable to write file. Datei kann nicht geschrieben werden. - + Save File Datei speichern - + Confirm Reset Zurücksetzen bestätigen - + Are you sure you want to reset the configuration? Sind Sie sicher, dass sie die Konfiguration zurücksetzen wollen? - + Show help message Hilfetext anzeigen - + Show the help message at the beginning in the capture mode. Hilfetext am Start der Auswahl anzeigen. - - + + Show desktop notifications Zeige Desktopbenachrichtigungen - + Show tray icon Zeige Taskleistensymbol - + Show the systemtray icon Zeigt das Taskleistensymbol - + Configuration File Konfigurationsdatei - + Export Exportieren - + Reset Zurücksetzen - + Launch at startup Automatisch starten - + Launch Flameshot Starte Flameshot - + Close after capture - + Close after taking a screenshot - + Copy URL after upload - + Copy URL and close window after upload @@ -418,48 +418,48 @@ Drücke die Leertaste um das Seitenmenü zu öffnen. ImgurUploader - + Upload to Imgur Zu Imgur hochladen - + Uploading Image Bild hochladen - + Copy URL URL kopieren - + Open URL URL öffnen - + Delete image Bild löschen - + Image to Clipboard. Bild in Zwischenablage. - - + + Unable to open the URL. Kann URL nicht öffnen. - + URL copied to clipboard. URL kopiert. - + Screenshot copied to clipboard. Bildschirmaufnahme in Zwischenablage kopiert. @@ -467,12 +467,12 @@ Drücke die Leertaste um das Seitenmenü zu öffnen. ImgurUploaderTool - + Image Uploader Bild hochladen - + Upload the selection to Imgur Auswahl zu Imgur hochladen @@ -480,7 +480,7 @@ Drücke die Leertaste um das Seitenmenü zu öffnen. InfoWindow - + About Über @@ -500,77 +500,77 @@ Drücke die Leertaste um das Seitenmenü zu öffnen. Mausrad - + Move selection 1px Verschiebe Auswahl um 1px - + Resize selection 1px Größenänderung um 1px - + Quit capture Auswahl verlassen - + Copy to clipboard In Zwischenablage kopieren - + Save selection as a file Speichere Auswahl als Datei - + Undo the last modification Letze Änderungen zurücksetzen - + Toggle visibility of sidebar with options of the selected tool Öffne/Schließe Seitenauswahlmenü des gewählten Werkzeugs - + Show color picker Zeige Farbauswahl - + Change the tool's thickness Ändere die Dicke des Werkzeugs - + Available shortcuts in the screen capture mode. Verfügbare Tastenkürzel im Aufnahmemodus. - + Key Taste - + Description Beschreibung - + <u><b>License</b></u> <u><b>Lizenz</b></u> - + <u><b>Version</b></u> <u><b>Version</b></u> - + <u><b>Shortcuts</b></u> <u><b>Tastenkürzel</b></u> @@ -578,12 +578,12 @@ Drücke die Leertaste um das Seitenmenü zu öffnen. LineTool - + Line Linie - + Set the Line as the paint tool Wähle Linie als Werkzeug @@ -591,12 +591,12 @@ Drücke die Leertaste um das Seitenmenü zu öffnen. MarkerTool - + Marker Markierer - + Set the Marker as the paint tool Wähle den Markierer als Werkzeug @@ -604,12 +604,12 @@ Drücke die Leertaste um das Seitenmenü zu öffnen. MoveTool - + Move Bewege - + Move the selection area Bewege den Auswahlbereich @@ -617,12 +617,12 @@ Drücke die Leertaste um das Seitenmenü zu öffnen. PencilTool - + Pencil Stift - + Set the Pencil as the paint tool Wähle den Stift als Werkzeug @@ -630,12 +630,12 @@ Drücke die Leertaste um das Seitenmenü zu öffnen. PinTool - + Pin Tool Pinnwand Werkzeug - + Pin image on the desktop Pinne Bild auf den Dekstop @@ -643,13 +643,13 @@ Drücke die Leertaste um das Seitenmenü zu öffnen. QObject - + Save Error Speicherfehler - + Capture saved as Aufnahme gespeichert als @@ -660,31 +660,31 @@ Drücke die Leertaste um das Seitenmenü zu öffnen. - + Error trying to save as Fehler beim Speichern unter - - - - + + + + Unable to connect via DBus Kann nicht via DBus verbinden - + Error Fehler - + Unable to write in Kein Schreibzugriff auf - + URL copied to clipboard. URL kopiert. @@ -692,12 +692,12 @@ Drücke die Leertaste um das Seitenmenü zu öffnen. RectangleTool - + Rectangle Rechteck - + Set the Rectangle as the paint tool Wähle ausgefülltes Rechteck als Werkzeug @@ -705,12 +705,12 @@ Drücke die Leertaste um das Seitenmenü zu öffnen. RedoTool - + Redo Wiederholen - + Redo the next modification Wiederhole die nächste Veränderung @@ -718,12 +718,12 @@ Drücke die Leertaste um das Seitenmenü zu öffnen. SaveTool - + Save Speichern - + Save the capture Speichere die Aufnahme @@ -731,7 +731,7 @@ Drücke die Leertaste um das Seitenmenü zu öffnen. ScreenGrabber - + Unable to capture screen Kann Bereich nicht aufnehmen @@ -739,12 +739,12 @@ Drücke die Leertaste um das Seitenmenü zu öffnen. SelectionTool - + Rectangular Selection Rechteckige Auswahl - + Set Selection as the paint tool Wähle Rechteck als Werkzeug @@ -752,22 +752,22 @@ Drücke die Leertaste um das Seitenmenü zu öffnen. SidePanelWidget - + Active thickness: Aktuelle Dicke - + Active color: Aktuelle Farbe: - + Press ESC to cancel Drücke ESC für Abbruch - + Grab Color Wähle Farbe @@ -775,12 +775,12 @@ Drücke die Leertaste um das Seitenmenü zu öffnen. SizeIndicatorTool - + Selection Size Indicator Auswahlgrößen Indentifikator - + Show the dimensions of the selection (X Y) Zeige die Dimensionen der Auswahl (X Y) @@ -788,107 +788,107 @@ Drücke die Leertaste um das Seitenmenü zu öffnen. StrftimeChooserWidget - + Century (00-99) Jarhhundert (00-99) - + Year (00-99) Jahr (00-99) - + Year (2000) Jahr (2000) - + Month Name (jan) Monatsname (Jan) - + Month Name (january) Monatsname (Januar) - + Month (01-12) Monat (01-12) - + Week Day (1-7) Wochentag (1-7) - + Week (01-53) Woche (01-53) - + Day Name (mon) Tagesname (Mon) - + Day Name (monday) Tagesname (Montag) - + Day (01-31) Tag (01-31) - + Day of Month (1-31) Tag des Monats (1-31) - + Day (001-366) Tag (001-366) - + Time (%H-%M-%S) Zeit (%H-%M-%S) - + Time (%H-%M) Zeit (%H-%M) - + Hour (00-23) Stunde (00-23) - + Hour (01-12) Stunde (01-12) - + Minute (00-59) Minute (00-59) - + Second (00-59) Sekunde (00-59) - + Full Date (%m/%d/%y) Komplettes Datum (%m/%d/%y) - + Full Date (%Y-%m-%d) Komplettes Datum (%Y-%m-%d) @@ -896,7 +896,7 @@ Drücke die Leertaste um das Seitenmenü zu öffnen. SystemNotification - + Flameshot Info Flameshot Info @@ -904,22 +904,22 @@ Drücke die Leertaste um das Seitenmenü zu öffnen. TextConfig - + StrikeOut Durchstreichen - + Underline Unterstrichen - + Bold Fettdruck - + Italic Kursiv @@ -927,12 +927,12 @@ Drücke die Leertaste um das Seitenmenü zu öffnen. TextTool - + Text Text - + Add text to your capture Füge Text zur Auswahl hinzu @@ -940,37 +940,37 @@ Drücke die Leertaste um das Seitenmenü zu öffnen. UIcolorEditor - + UI Color Editor UI Farb Editor - + Change the color moving the selectors and see the changes in the preview buttons. Ändere die Farbauswahl und betrachte die Vorschau in den Vorschau-Buttons. - + Select a Button to modify it Wähle einen Button um ihn zu verändern - + Main Color Hauptfarbe - + Click on this button to set the edition mode of the main color. Wähle diesen Button um den Bearbeitungsmodus der Hauptfarbe zu wählen. - + Contrast Color Kontrastfarbe - + Click on this button to set the edition mode of the contrast color. Wähle diesen Button um den Bearbeitungsmodus der Kontrastfarbe zu wählen. @@ -978,12 +978,12 @@ Drücke die Leertaste um das Seitenmenü zu öffnen. UndoTool - + Undo Verwerfen - + Undo the last modification Letzte Änderung verwerfen @@ -991,17 +991,17 @@ Drücke die Leertaste um das Seitenmenü zu öffnen. VisualsEditor - + Opacity of area outside selection: Deckkraft des Bereichs außerhalb der Auswahl: - + Button Selection Button Auswahl - + Select All Alle wählen diff --git a/data/translations/Internationalization_es.ts b/data/translations/Internationalization_es.ts index 5326d473..b0616360 100644 --- a/data/translations/Internationalization_es.ts +++ b/data/translations/Internationalization_es.ts @@ -4,12 +4,12 @@ AppLauncher - + App Launcher Lanzador de Aplicaciones - + Choose an app to open the capture Elige una aplicación con la que abrir la captura @@ -32,18 +32,18 @@ Mantener abierto tras la selección - - + + Error Error - + Unable to write in Imposible escribir en - + Unable to launch in terminal. Imposible lanzar en terminal. @@ -51,12 +51,12 @@ ArrowTool - + Arrow Flecha - + Set the Arrow as the paint tool Establece la Flecha como herramienta de dibujo @@ -64,12 +64,12 @@ BlurTool - + Blur Desenfoque - + Set Blur as the paint tool Establece el Desenfoque como herramienta de dibujo @@ -77,47 +77,47 @@ CaptureLauncher - + <b>Capture Mode</b> - + Rectangular Region - + Full Screen (All Monitors) - + No Delay - + second - + seconds - + Take new screenshot - + Area: - + Delay: @@ -125,12 +125,12 @@ CaptureWidget - + Unable to capture screen Imposible capturar la pantalla - + Select an area with the mouse, or press Esc to exit. Press Enter to capture the screen. Press Right Click to show the color picker. @@ -146,12 +146,12 @@ Presiona Espacio para abrir el panel lateral. CircleCountTool - + Circle Counter - + Add an autoincrementing counter bubble @@ -159,12 +159,12 @@ Presiona Espacio para abrir el panel lateral. CircleTool - + Circle Círculo - + Set the Circle as the paint tool Establece el Círculo como herramienta de dibujo @@ -172,7 +172,7 @@ Presiona Espacio para abrir el panel lateral. ConfigWindow - + Configuration Configuración @@ -182,7 +182,7 @@ Presiona Espacio para abrir el panel lateral. Interfaz - + Filename Editor Editor de Nombre @@ -195,27 +195,27 @@ Presiona Espacio para abrir el panel lateral. Controller - + &Take Screenshot &Tomar captura de pantalla - + &Open Launcher - + &Configuration &Configuración - + &Information &Información - + &Quit &Salir @@ -223,12 +223,12 @@ Presiona Espacio para abrir el panel lateral. CopyTool - + Copy Copiar - + Copy the selection into the clipboard Copia la selección al portapapeles @@ -236,7 +236,7 @@ Presiona Espacio para abrir el panel lateral. DBusUtils - + Unable to connect via DBus Imposible conectarse mediante DBus @@ -244,12 +244,12 @@ Presiona Espacio para abrir el panel lateral. ExitTool - + Exit Salir - + Leave the capture screen Salir de la pantalla de captura @@ -257,47 +257,47 @@ Presiona Espacio para abrir el panel lateral. FileNameEditor - + Edit the name of your captures: Edita el nombre de tus capturas: - + Edit: Editar: - + Preview: Previsualización: - + Save Guardar - + Saves the pattern Guarda el patrón - + Reset Reiniciar - + Restores the saved pattern Restaura el patrón guardado - + Clear Limpiar - + Deletes the name Borra el patrón @@ -305,112 +305,112 @@ Presiona Espacio para abrir el panel lateral. GeneneralConf - - + + Import Importar - - - + + + Error Error - + Unable to read file. Imposible leer el archivo. - - + + Unable to write file. Imposible escribir el archivo. - + Save File Guardar Archivo - + Confirm Reset Confirmar Reset - + Are you sure you want to reset the configuration? ¿Estás seguro de que quieres reiniciar la configuración? - + Show help message Mostrar mensaje de ayuda - + Show the help message at the beginning in the capture mode. Muestra el mensaje de ayuda al iniciar el modo de captura. - - + + Show desktop notifications Mostrar notificaciones del escritorio - + Show tray icon Mostrar icono en la barra de tareas - + Show the systemtray icon Mostrar el icono en la barra de tareas - + Configuration File Archivo de Configuración - + Export Exportar - + Reset Reset - + Launch at startup Lanzar en el arranque - + Launch Flameshot Lanzar Flameshot - + Close after capture - + Close after taking a screenshot - + Copy URL after upload - + Copy URL and close window after upload @@ -418,48 +418,48 @@ Presiona Espacio para abrir el panel lateral. ImgurUploader - + Upload to Imgur Subir a Imgur - + Uploading Image Subiendo Imagen - + Copy URL Copiar URL - + Open URL Abrir URL - + Delete image Borrar imagen - + Image to Clipboard. Imagen al Portapapeles. - - + + Unable to open the URL. No puede abrir la URL. - + URL copied to clipboard. URL copiada al portapapeles. - + Screenshot copied to clipboard. Captura copiada al portapapeles. @@ -467,12 +467,12 @@ Presiona Espacio para abrir el panel lateral. ImgurUploaderTool - + Image Uploader Subir Imagen - + Upload the selection to Imgur Sube la selección a Imgur @@ -480,7 +480,7 @@ Presiona Espacio para abrir el panel lateral. InfoWindow - + About Información @@ -500,77 +500,77 @@ Presiona Espacio para abrir el panel lateral. Rueda del Ratón - + Move selection 1px Mover la selección 1px - + Resize selection 1px Redimensionar la selección 1px - + Quit capture Salir de la captura - + Copy to clipboard Copiar al portapapeles - + Save selection as a file Guardar la selección como un archivo - + Undo the last modification Deshacer la última modificación - + Toggle visibility of sidebar with options of the selected tool Alternar la visualización de la barra lateral de opciones de la herramienta seleccionada - + Show color picker Mostrar el selector de color - + Change the tool's thickness Cambiar el grosor de la herramienta - + Available shortcuts in the screen capture mode. Atajos disponibles en el modo captura de pantalla. - + Key Tecla - + Description Descripción - + <u><b>License</b></u> <u><b>Licencia</b></u> - + <u><b>Version</b></u> <u><b>Versión</b></u> - + <u><b>Shortcuts</b></u> <u><b>Atajos</b></u> @@ -578,12 +578,12 @@ Presiona Espacio para abrir el panel lateral. LineTool - + Line Línea - + Set the Line as the paint tool Establece la Línea como herramienta de dibujo @@ -591,12 +591,12 @@ Presiona Espacio para abrir el panel lateral. MarkerTool - + Marker Marcador - + Set the Marker as the paint tool Establece el Marcador como herramienta de dibujo @@ -604,12 +604,12 @@ Presiona Espacio para abrir el panel lateral. MoveTool - + Move Mover Selección - + Move the selection area Mueve la selección @@ -617,12 +617,12 @@ Presiona Espacio para abrir el panel lateral. PencilTool - + Pencil Lápiz - + Set the Pencil as the paint tool Establece el Lápiz como herramienta de dibujo @@ -630,12 +630,12 @@ Presiona Espacio para abrir el panel lateral. PinTool - + Pin Tool Chincheta - + Pin image on the desktop Fija la imagen sobre el escritorio @@ -643,13 +643,13 @@ Presiona Espacio para abrir el panel lateral. QObject - + Save Error Error al Guardar - + Capture saved as Captura guardada como @@ -660,31 +660,31 @@ Presiona Espacio para abrir el panel lateral. - + Error trying to save as Error intentando guardar como - - - - + + + + Unable to connect via DBus Imposible conectar mediante DBus - + Error Error - + Unable to write in Imposible escribir en - + URL copied to clipboard. URL copiada al portapapeles. @@ -692,12 +692,12 @@ Presiona Espacio para abrir el panel lateral. RectangleTool - + Rectangle Rectángulo - + Set the Rectangle as the paint tool Establece el Rectángulo como herramienta de dibujo @@ -705,12 +705,12 @@ Presiona Espacio para abrir el panel lateral. RedoTool - + Redo Rehacer - + Redo the next modification Rehacer la siguiente modificación @@ -718,12 +718,12 @@ Presiona Espacio para abrir el panel lateral. SaveTool - + Save Guardar - + Save the capture Guardar la captura @@ -731,7 +731,7 @@ Presiona Espacio para abrir el panel lateral. ScreenGrabber - + Unable to capture screen Imposible capturar la pantalla @@ -739,12 +739,12 @@ Presiona Espacio para abrir el panel lateral. SelectionTool - + Rectangular Selection Selección Rectangular - + Set Selection as the paint tool Establece la Selección como herramienta de dibujo @@ -752,22 +752,22 @@ Presiona Espacio para abrir el panel lateral. SidePanelWidget - + Active thickness: Espesor activo: - + Active color: Color activo: - + Press ESC to cancel Presiona ESC para cancelar - + Grab Color Tomar Color @@ -775,12 +775,12 @@ Presiona Espacio para abrir el panel lateral. SizeIndicatorTool - + Selection Size Indicator Indicador de Tamaño de Selección - + Show the dimensions of the selection (X Y) Muestra la dimensión de la selección (X Y) @@ -788,107 +788,107 @@ Presiona Espacio para abrir el panel lateral. StrftimeChooserWidget - + Century (00-99) Siglo (00-99) - + Year (00-99) Año (00-99) - + Year (2000) Año (2000) - + Month Name (jan) Nombre del Mes (jul) - + Month Name (january) Nombre del Mes (julio) - + Month (01-12) Mes (01-12) - + Week Day (1-7) Día de la Semana (1-7) - + Week (01-53) Semana (01-53) - + Day Name (mon) Nombre del Día (dom) - + Day Name (monday) Nombre del Día (domingo) - + Day (01-31) Día (01-31) - + Day of Month (1-31) Día del Mes (1-31) - + Day (001-366) Día (001-366) - + Time (%H-%M-%S) Tiempo (%H-%M-%S) - + Time (%H-%M) Tiempo (%H-%M) - + Hour (00-23) Hora (00-23) - + Hour (01-12) Hora (01-12) - + Minute (00-59) Minuto (00-59) - + Second (00-59) Segundo (00-59) - + Full Date (%m/%d/%y) Fecha (%m/%d/%y) - + Full Date (%Y-%m-%d) Fecha (%Y-%m-%d) @@ -896,7 +896,7 @@ Presiona Espacio para abrir el panel lateral. SystemNotification - + Flameshot Info Información de Flameshot @@ -904,22 +904,22 @@ Presiona Espacio para abrir el panel lateral. TextConfig - + StrikeOut Tachado - + Underline Subrayado - + Bold Negrita - + Italic Cursiva @@ -927,12 +927,12 @@ Presiona Espacio para abrir el panel lateral. TextTool - + Text Texto - + Add text to your capture Agregar texto a la captura @@ -940,37 +940,37 @@ Presiona Espacio para abrir el panel lateral. UIcolorEditor - + UI Color Editor Editor de Color de Interfaz - + Change the color moving the selectors and see the changes in the preview buttons. Cambia el color moviendo los selectores y observa los cambios en los botones de previsualización. - + Select a Button to modify it Selecciona un Botón para modificarlo - + Main Color Color Principal - + Click on this button to set the edition mode of the main color. Clica en este botón para aplicar el modo edición para el color primario. - + Contrast Color Color de Contraste - + Click on this button to set the edition mode of the contrast color. Clica en este botón para aplicar el modo edición para el color de contraste. @@ -978,12 +978,12 @@ Presiona Espacio para abrir el panel lateral. UndoTool - + Undo Deshacer - + Undo the last modification Borra la última modificación @@ -991,17 +991,17 @@ Presiona Espacio para abrir el panel lateral. VisualsEditor - + Opacity of area outside selection: Opacidad del area fuera de la selección: - + Button Selection Selección de Botón - + Select All Seleccionar Todos diff --git a/data/translations/Internationalization_fr.ts b/data/translations/Internationalization_fr.ts index 41b8144f..c260f1ce 100644 --- a/data/translations/Internationalization_fr.ts +++ b/data/translations/Internationalization_fr.ts @@ -4,12 +4,12 @@ AppLauncher - + App Launcher Lanceur d'applications - + Choose an app to open the capture Sélectionner une application pour ouvrir la capture @@ -32,18 +32,18 @@ Maintenir ouvert après la sélection - - + + Error Erreur - + Unable to write in Imposible d'écrire dessus - + Unable to launch in terminal. Imposible de lancer dans le terminal. @@ -51,12 +51,12 @@ ArrowTool - + Arrow Flèche - + Set the Arrow as the paint tool Sélectionner l'outil Flèche @@ -64,12 +64,12 @@ BlurTool - + Blur Flou - + Set Blur as the paint tool Sélectionner l'outil Flou @@ -77,47 +77,47 @@ CaptureLauncher - + <b>Capture Mode</b> - + Rectangular Region - + Full Screen (All Monitors) - + No Delay - + second - + seconds - + Take new screenshot - + Area: - + Delay: @@ -125,12 +125,12 @@ CaptureWidget - + Unable to capture screen Imposible de capturer l'écran - + Select an area with the mouse, or press Esc to exit. Press Enter to capture the screen. Press Right Click to show the color picker. @@ -146,12 +146,12 @@ Appuyer sur Espace pour ouvrir le panneau latéral. CircleCountTool - + Circle Counter - + Add an autoincrementing counter bubble @@ -159,12 +159,12 @@ Appuyer sur Espace pour ouvrir le panneau latéral. CircleTool - + Circle Ellipse - + Set the Circle as the paint tool Sélectionner l'outil Ellipse @@ -172,7 +172,7 @@ Appuyer sur Espace pour ouvrir le panneau latéral. ConfigWindow - + Configuration Configuration @@ -182,7 +182,7 @@ Appuyer sur Espace pour ouvrir le panneau latéral. Interface - + Filename Editor Editeur de Noms @@ -195,27 +195,27 @@ Appuyer sur Espace pour ouvrir le panneau latéral. Controller - + &Take Screenshot &Capturer l'écran - + &Open Launcher - + &Configuration &Configuration - + &Information &Informations - + &Quit &Quitter @@ -223,12 +223,12 @@ Appuyer sur Espace pour ouvrir le panneau latéral. CopyTool - + Copy Copier - + Copy the selection into the clipboard Copier la sélection dans le presse-papier @@ -236,7 +236,7 @@ Appuyer sur Espace pour ouvrir le panneau latéral. DBusUtils - + Unable to connect via DBus Imposible de se connecter via DBus @@ -244,12 +244,12 @@ Appuyer sur Espace pour ouvrir le panneau latéral. ExitTool - + Exit Sortir - + Leave the capture screen Quitter l'écran de capture @@ -257,47 +257,47 @@ Appuyer sur Espace pour ouvrir le panneau latéral. FileNameEditor - + Edit the name of your captures: Editer le nom des captures: - + Edit: Editer: - + Preview: Prévisualisation: - + Save Sauvegarder - + Saves the pattern Sauvegarder le modèle - + Reset Réinitialiser - + Restores the saved pattern Réstaurer le modèle sauvegardé - + Clear Purger - + Deletes the name Supprime le nom @@ -305,112 +305,112 @@ Appuyer sur Espace pour ouvrir le panneau latéral. GeneneralConf - - + + Import Importer - - - + + + Error Erreur - + Unable to read file. Impossible de lire le fichier. - - + + Unable to write file. Impossible d'écrire le fichier. - + Save File Sauvegarder le fichier - + Confirm Reset Confirmer la Réinitialisation - + Are you sure you want to reset the configuration? Êtes-vous sûr de vouloir réinitialiser la configuration ? - + Show help message Montrer le message d'aide - + Show the help message at the beginning in the capture mode. Afficher ce message au lancement du mode capture. - - + + Show desktop notifications Afficher les notifications du bureau - + Show tray icon Afficher les icones de la barre d'état - + Show the systemtray icon Afficher l'icône dans la barre de tâches - + Configuration File Fichier de Configuration - + Export Exporter - + Reset Réinitialiser - + Launch at startup Lancer au démarrage - + Launch Flameshot Démarrer Flameshot - + Close after capture Fermer après une capture - + Close after taking a screenshot Fermer l'application après une capture d'écran - + Copy URL after upload - + Copy URL and close window after upload @@ -418,48 +418,48 @@ Appuyer sur Espace pour ouvrir le panneau latéral. ImgurUploader - + Upload to Imgur Mettre en ligne vers Imgur - + Uploading Image Mise en ligne de l'image - + Copy URL Copier l'URL - + Open URL Ouvrir l'URL - + Delete image - + Image to Clipboard. Image dans le Presse-papier. - - + + Unable to open the URL. Impossible d'ouvrir l'URL. - + URL copied to clipboard. URL copiée dans le Presse-papier. - + Screenshot copied to clipboard. Capture d'écran copiée dans le Presse-papier. @@ -467,12 +467,12 @@ Appuyer sur Espace pour ouvrir le panneau latéral. ImgurUploaderTool - + Image Uploader Mise en ligne d'images - + Upload the selection to Imgur Mettre en ligne la sélection vers Imgur @@ -480,7 +480,7 @@ Appuyer sur Espace pour ouvrir le panneau latéral. InfoWindow - + About À propos @@ -500,77 +500,77 @@ Appuyer sur Espace pour ouvrir le panneau latéral. Molette de la Souris - + Move selection 1px Déplacer la sélection 1px - + Resize selection 1px Redimensionner la sélection 1px - + Quit capture Quitter la capture d'écran - + Copy to clipboard Copier vers le Presse-papier - + Save selection as a file Sauvegarder la sélection vers un fichier - + Undo the last modification Annuler la dernière modification - + Toggle visibility of sidebar with options of the selected tool - + Show color picker Afficher la palette de couleurs - + Change the tool's thickness Changer l'épaisseur des outils - + Available shortcuts in the screen capture mode. Raccourcis disponibles en mode capture d'écran. - + Key Clé - + Description Description - + <u><b>License</b></u> <u><b>Licences</b></u> - + <u><b>Version</b></u> <u><b>Version</b></u> - + <u><b>Shortcuts</b></u> <u><b>Raccourci</b></u> @@ -578,12 +578,12 @@ Appuyer sur Espace pour ouvrir le panneau latéral. LineTool - + Line Ligne - + Set the Line as the paint tool Sélectionner l'outil Ligne @@ -591,12 +591,12 @@ Appuyer sur Espace pour ouvrir le panneau latéral. MarkerTool - + Marker Surligneur - + Set the Marker as the paint tool Sélectionner l'outil Surligneur @@ -604,12 +604,12 @@ Appuyer sur Espace pour ouvrir le panneau latéral. MoveTool - + Move Déplacer - + Move the selection area Déplacer la sélection @@ -617,12 +617,12 @@ Appuyer sur Espace pour ouvrir le panneau latéral. PencilTool - + Pencil Crayon - + Set the Pencil as the paint tool Sélectionner l'outil Crayon @@ -630,12 +630,12 @@ Appuyer sur Espace pour ouvrir le panneau latéral. PinTool - + Pin Tool Outil Épinglage - + Pin image on the desktop Épingler l'image sur le bureau @@ -643,13 +643,13 @@ Appuyer sur Espace pour ouvrir le panneau latéral. QObject - + Save Error Erreur lors de la sauvegarde - + Capture saved as Capture d'écran sauvegardée sous @@ -660,31 +660,31 @@ Appuyer sur Espace pour ouvrir le panneau latéral. - + Error trying to save as Erreur lors de la sauvegarde sous - - - - + + + + Unable to connect via DBus Impossible de se connecter via DBus - + Error Erreur - + Unable to write in Imposible d'écrire par dessus - + URL copied to clipboard. URL copiée dans le Presse-papier. @@ -692,12 +692,12 @@ Appuyer sur Espace pour ouvrir le panneau latéral. RectangleTool - + Rectangle Rectangle plein - + Set the Rectangle as the paint tool Sélectionner l'outil Rectangle plein @@ -705,12 +705,12 @@ Appuyer sur Espace pour ouvrir le panneau latéral. RedoTool - + Redo Rétablir - + Redo the next modification Refaire la prochaine modification @@ -718,12 +718,12 @@ Appuyer sur Espace pour ouvrir le panneau latéral. SaveTool - + Save Sauvegarder - + Save the capture Sauvegarder la capture d'écran @@ -731,7 +731,7 @@ Appuyer sur Espace pour ouvrir le panneau latéral. ScreenGrabber - + Unable to capture screen Imposible de capturer l'écran @@ -739,12 +739,12 @@ Appuyer sur Espace pour ouvrir le panneau latéral. SelectionTool - + Rectangular Selection Rectangle - + Set Selection as the paint tool Sélectionner l'outil Rectangle @@ -752,22 +752,22 @@ Appuyer sur Espace pour ouvrir le panneau latéral. SidePanelWidget - + Active color: Couleur actuelle: - + Press ESC to cancel Appuyer sur Echap pour annuler - + Grab Color Saisir la couleur - + Active thickness: @@ -775,12 +775,12 @@ Appuyer sur Espace pour ouvrir le panneau latéral. SizeIndicatorTool - + Selection Size Indicator Indicateur de la taille de la sélection - + Show the dimensions of the selection (X Y) Montre les dimmensions de la sélection (X Y) @@ -788,107 +788,107 @@ Appuyer sur Espace pour ouvrir le panneau latéral. StrftimeChooserWidget - + Century (00-99) Siècle (00-99) - + Year (00-99) Année (00-99) - + Year (2000) Année (2000) - + Month Name (jan) Nom des Mois (jan) - + Month Name (january) nom des Mois (janvier) - + Month (01-12) Mois (01-12) - + Week Day (1-7) Jour de la Semaine (1-7) - + Week (01-53) Semaine (01-53) - + Day Name (mon) Nom du Jour (lun) - + Day Name (monday) Nom du Jour (lundi) - + Day (01-31) Jour (01-31) - + Day of Month (1-31) Jour du Mois (1-31) - + Day (001-366) Jour de l'année (001-366) - + Time (%H-%M-%S) Heure (%H-%M-%S) - + Time (%H-%M) Heure (%H-%M) - + Hour (00-23) Heure (00-23) - + Hour (01-12) Heure (01-12) - + Minute (00-59) Minute (00-59) - + Second (00-59) Seconde (00-59) - + Full Date (%m/%d/%y) Date (%m/%d/%y) - + Full Date (%Y-%m-%d) Date Complête (%Y-%m-%d) @@ -896,7 +896,7 @@ Appuyer sur Espace pour ouvrir le panneau latéral. SystemNotification - + Flameshot Info Info Flameshot @@ -904,22 +904,22 @@ Appuyer sur Espace pour ouvrir le panneau latéral. TextConfig - + StrikeOut Rayer - + Underline Souligner - + Bold Gras - + Italic Italique @@ -927,12 +927,12 @@ Appuyer sur Espace pour ouvrir le panneau latéral. TextTool - + Text Texte - + Add text to your capture Ajouter du texte à la capture @@ -940,37 +940,37 @@ Appuyer sur Espace pour ouvrir le panneau latéral. UIcolorEditor - + UI Color Editor Editeur de la Couleur de l'interface - + Change the color moving the selectors and see the changes in the preview buttons. Modifiez la couleur en déplaçant les sélecteur et voir les changements dans les boutons de prévisualisation. - + Select a Button to modify it Sélectionner un bouton pour le modifier - + Main Color Couleur Principale - + Click on this button to set the edition mode of the main color. Cliquer sur ce boutton pour définir le mode édition de la couleur principale. - + Contrast Color Couleur de Contraste - + Click on this button to set the edition mode of the contrast color. Cliquer sur ce boutton pour définir le mode édition de la couleur de contraste. @@ -978,12 +978,12 @@ Appuyer sur Espace pour ouvrir le panneau latéral. UndoTool - + Undo Annuler - + Undo the last modification Annuler la dernière modification @@ -991,17 +991,17 @@ Appuyer sur Espace pour ouvrir le panneau latéral. VisualsEditor - + Opacity of area outside selection: Opacité de la zone en dehors de la sélection: - + Button Selection Boutton de sélection - + Select All Sélectionner Tout diff --git a/data/translations/Internationalization_ja.ts b/data/translations/Internationalization_ja.ts index e809e5d4..19fcfbb9 100644 --- a/data/translations/Internationalization_ja.ts +++ b/data/translations/Internationalization_ja.ts @@ -4,12 +4,12 @@ AppLauncher - + App Launcher アプリケーションランチャー - + Choose an app to open the capture キャプチャーを開くアプリケーションを選択する @@ -32,18 +32,18 @@ 選択後も開いたままにする - - + + Error エラー - + Unable to launch in terminal. 端末内で起動できません。 - + Unable to write in 書き込めません: @@ -51,12 +51,12 @@ ArrowTool - + Arrow 矢印 - + Set the Arrow as the paint tool ペイントツールとして「矢印」をセットする @@ -64,12 +64,12 @@ BlurTool - + Blur ぼかし - + Set Blur as the paint tool ペイントツールとして「ぼかし」をセットする @@ -77,47 +77,47 @@ CaptureLauncher - + <b>Capture Mode</b> - + Rectangular Region - + Full Screen (All Monitors) - + No Delay - + second - + seconds - + Take new screenshot - + Area: - + Delay: @@ -125,12 +125,12 @@ CaptureWidget - + Unable to capture screen 画面をキャプチャーできません - + Select an area with the mouse, or press Esc to exit. Press Enter to capture the screen. Press Right Click to show the color picker. @@ -146,12 +146,12 @@ Enter を押すと画面をキャプチャー。 CircleCountTool - + Circle Counter - + Add an autoincrementing counter bubble @@ -159,12 +159,12 @@ Enter を押すと画面をキャプチャー。 CircleTool - + Circle 円形 - + Set the Circle as the paint tool ペイントツールとして「円形」をセットする @@ -172,7 +172,7 @@ Enter を押すと画面をキャプチャー。 ConfigWindow - + Configuration 設定 @@ -182,7 +182,7 @@ Enter を押すと画面をキャプチャー。 インターフェース - + Filename Editor ファイル名エディター @@ -195,27 +195,27 @@ Enter を押すと画面をキャプチャー。 Controller - + &Take Screenshot スクリーンショットを撮る(&T) - + &Open Launcher - + &Configuration 設定(&C) - + &Information 情報(&I) - + &Quit 終了(&Q) @@ -223,12 +223,12 @@ Enter を押すと画面をキャプチャー。 CopyTool - + Copy コピー - + Copy the selection into the clipboard 選択範囲をクリップボードにコピーする @@ -236,7 +236,7 @@ Enter を押すと画面をキャプチャー。 DBusUtils - + Unable to connect via DBus DBus に接続できません @@ -244,12 +244,12 @@ Enter を押すと画面をキャプチャー。 ExitTool - + Exit 終了 - + Leave the capture screen 画面キャプチャーを終了する @@ -257,47 +257,47 @@ Enter を押すと画面をキャプチャー。 FileNameEditor - + Edit the name of your captures: キャプチャー名の編集: - + Edit: 編集: - + Preview: プレビュー: - + Save 保存 - + Saves the pattern パターンを保存する - + Reset リセット - + Restores the saved pattern 保存されたパターンに戻す - + Clear 消去 - + Deletes the name 名前を削除する @@ -305,112 +305,112 @@ Enter を押すと画面をキャプチャー。 GeneneralConf - + Show help message ヘルプメッセージを表示する - + Show the help message at the beginning in the capture mode. キャプチャーモード開始時にヘルプメッセージを表示する。 - - + + Show desktop notifications デスクトップの通知を表示する - + Show tray icon トレイアイコンを表示する - + Show the systemtray icon システムトレイアイコンを表示する - - + + Import インポート - - - + + + Error エラー - + Unable to read file. ファイルを読み込めません。 - - + + Unable to write file. ファイルに書き込めません。 - + Save File ファイルを保存 - + Confirm Reset リセットの確認 - + Are you sure you want to reset the configuration? 設定をリセットしてもよろしいですか? - + Configuration File 設定ファイル - + Export エクスポート - + Reset リセット - + Launch at startup スタートアップ時に起動する - + Launch Flameshot Flameshot を起動する - + Close after capture - + Close after taking a screenshot - + Copy URL after upload - + Copy URL and close window after upload @@ -418,48 +418,48 @@ Enter を押すと画面をキャプチャー。 ImgurUploader - + Upload to Imgur Imgur にアップロード - + Uploading Image 画像をアップロード中 - + Copy URL URL をコピー - + Open URL URL を開く - + Delete image 画像を削除 - + Image to Clipboard. 画像をクリップボードへ。 - - + + Unable to open the URL. URL を開けません。 - + URL copied to clipboard. URL をクリップボードにコピーしました。 - + Screenshot copied to clipboard. スクリーンショットをクリップボードにコピーしました。 @@ -467,12 +467,12 @@ Enter を押すと画面をキャプチャー。 ImgurUploaderTool - + Image Uploader 画像アップローダー - + Upload the selection to Imgur Imgur に選択範囲をアップロードする @@ -480,7 +480,7 @@ Enter を押すと画面をキャプチャー。 InfoWindow - + About このアプリケーションについて @@ -500,77 +500,77 @@ Enter を押すと画面をキャプチャー。 マウスホイール - + Move selection 1px 選択範囲を 1px 動かす - + Resize selection 1px 選択範囲を 1px リサイズする - + Quit capture キャプチャーを終了する - + Copy to clipboard クリップボードにコピーする - + Save selection as a file 選択範囲をファイルに保存する - + Undo the last modification 最後の変更を元に戻す - + Toggle visibility of sidebar with options of the selected tool - + Show color picker カラーピッカーを表示する - + Change the tool's thickness ツールの値 (太さや濃さ) を変更する - + Key キー - + Description 説明 - + <u><b>License</b></u> <u><b>ライセンス</b></u> - + <u><b>Version</b></u> <u><b>バージョン</b></u> - + <u><b>Shortcuts</b></u> <u><b>ショートカット</b></u> - + Available shortcuts in the screen capture mode. スクリーンキャプチャーモードで利用可能なショートカット。 @@ -578,12 +578,12 @@ Enter を押すと画面をキャプチャー。 LineTool - + Line 直線 - + Set the Line as the paint tool ペイントツールとして「直線」をセットする @@ -591,12 +591,12 @@ Enter を押すと画面をキャプチャー。 MarkerTool - + Marker マーカー - + Set the Marker as the paint tool ペイントツールとして「マーカー」をセットする @@ -604,12 +604,12 @@ Enter を押すと画面をキャプチャー。 MoveTool - + Move 移動 - + Move the selection area 選択範囲を移動する @@ -617,12 +617,12 @@ Enter を押すと画面をキャプチャー。 PencilTool - + Pencil 鉛筆 - + Set the Pencil as the paint tool ペイントツールとして「鉛筆」をセットする @@ -630,12 +630,12 @@ Enter を押すと画面をキャプチャー。 PinTool - + Pin Tool 固定ツール - + Pin image on the desktop 選択範囲をデスクトップ上に配置する @@ -643,13 +643,13 @@ Enter を押すと画面をキャプチャー。 QObject - + Save Error 保存エラー - + Capture saved as キャプチャーを保存しました: @@ -660,31 +660,31 @@ Enter を押すと画面をキャプチャー。 - + Error trying to save as 保存時にエラーが発生しました: - - - - + + + + Unable to connect via DBus DBus に接続できません - + Error エラー - + Unable to write in 書き込めません: - + URL copied to clipboard. URL をクリップボードにコピーしました。 @@ -692,12 +692,12 @@ Enter を押すと画面をキャプチャー。 RectangleTool - + Rectangle 矩形 - + Set the Rectangle as the paint tool ペイントツールとして「矩形」をセットする @@ -705,12 +705,12 @@ Enter を押すと画面をキャプチャー。 RedoTool - + Redo やり直し - + Redo the next modification 次の変更にやり直す @@ -718,12 +718,12 @@ Enter を押すと画面をキャプチャー。 SaveTool - + Save 保存 - + Save the capture キャプチャーを保存する @@ -731,7 +731,7 @@ Enter を押すと画面をキャプチャー。 ScreenGrabber - + Unable to capture screen 画面をキャプチャーできません @@ -739,12 +739,12 @@ Enter を押すと画面をキャプチャー。 SelectionTool - + Rectangular Selection 矩形選択 - + Set Selection as the paint tool ペイントツールとして「矩形選択」をセットする @@ -752,22 +752,22 @@ Enter を押すと画面をキャプチャー。 SidePanelWidget - + Active thickness: - + Active color: アクティブな色: - + Press ESC to cancel ESC でキャンセル - + Grab Color 色の取得 @@ -775,12 +775,12 @@ Enter を押すと画面をキャプチャー。 SizeIndicatorTool - + Selection Size Indicator 選択サイズインジケーター - + Show the dimensions of the selection (X Y) 選択範囲の寸法 (X Y) を表示する @@ -788,107 +788,107 @@ Enter を押すと画面をキャプチャー。 StrftimeChooserWidget - + Century (00-99) 世紀 (00-99) - + Year (00-99) 年 (00-99) - + Year (2000) 年 (2000) - + Month Name (jan) 月 (jan) - + Month Name (january) 月 (january) - + Month (01-12) 月 (01-12) - + Week Day (1-7) 週日 (1-7) - + Week (01-53) 週 (01-53) - + Day Name (mon) 曜日 (月) - + Day Name (monday) 曜日 (月曜日) - + Day (01-31) 日 (01-31) - + Day of Month (1-31) 日 (1-31) - + Day (001-366) 日 (001-366) - + Time (%H-%M-%S) 時刻 (%H-%M-%S) - + Time (%H-%M) 時刻 (%H-%M) - + Hour (00-23) 時 (00-23) - + Hour (01-12) 時 (01-12) - + Minute (00-59) 分 (00-59) - + Second (00-59) 秒 (00-59) - + Full Date (%m/%d/%y) 年月日 (%m/%d/%y) - + Full Date (%Y-%m-%d) 年月日 (%Y-%m-%d) @@ -896,7 +896,7 @@ Enter を押すと画面をキャプチャー。 SystemNotification - + Flameshot Info Flameshot の情報 @@ -904,22 +904,22 @@ Enter を押すと画面をキャプチャー。 TextConfig - + StrikeOut 取り消し線 - + Underline 下線 - + Bold 太字 - + Italic 斜体 @@ -927,12 +927,12 @@ Enter を押すと画面をキャプチャー。 TextTool - + Text テキスト - + Add text to your capture キャプチャーにテキストを追加する @@ -940,37 +940,37 @@ Enter を押すと画面をキャプチャー。 UIcolorEditor - + UI Color Editor UI カラーエディター - + Change the color moving the selectors and see the changes in the preview buttons. セレクターを動かして色を変更し、プレビューボタンの色がどう変化するか確認してください。 - + Select a Button to modify it 変更するボタンを選択してください - + Main Color メインカラー - + Click on this button to set the edition mode of the main color. このボタンをクリックすると、メインカラーの編集モードをセットします。 - + Contrast Color コントラストカラー - + Click on this button to set the edition mode of the contrast color. このボタンをクリックすると、コントラストカラーの編集モードをセットします。 @@ -978,12 +978,12 @@ Enter を押すと画面をキャプチャー。 UndoTool - + Undo 元に戻す - + Undo the last modification 最後の変更を元に戻す @@ -991,17 +991,17 @@ Enter を押すと画面をキャプチャー。 VisualsEditor - + Opacity of area outside selection: 選択範囲外の不透明度: - + Button Selection ボタンの選択 - + Select All すべて選択 diff --git a/data/translations/Internationalization_ka.ts b/data/translations/Internationalization_ka.ts index bb7f2da3..df8d8a6d 100644 --- a/data/translations/Internationalization_ka.ts +++ b/data/translations/Internationalization_ka.ts @@ -4,12 +4,12 @@ AppLauncher - + App Launcher აპლიკაციის გამშვები - + Choose an app to open the capture აირჩიეთ აპლიკაცია სურათის გასახსნელად @@ -32,18 +32,18 @@ არ დახურო დიალოგი არჩევის შემდეგ - - + + Error შეცდომა - + Unable to write in შემდეგ მისამართზე ჩაწერა ვერ მოხერხდა: - + Unable to launch in terminal. ტერმინალში გაშვება ვერ მოხერხდა. @@ -51,12 +51,12 @@ ArrowTool - + Arrow ისარი - + Set the Arrow as the paint tool ისრის ხელსაწყოს არჩევა სახატავად @@ -64,12 +64,12 @@ BlurTool - + Blur გაბუნდოვნება - + Set Blur as the paint tool გაბუნდოვნების ხელსაწყოს არჩევა სახატავად @@ -77,47 +77,47 @@ CaptureLauncher - + <b>Capture Mode</b> - + Rectangular Region - + Full Screen (All Monitors) - + No Delay - + second - + seconds - + Take new screenshot - + Area: - + Delay: @@ -125,12 +125,12 @@ CaptureWidget - + Unable to capture screen ეკრანის გადაღება ვერ მოხერხდა - + Select an area with the mouse, or press Esc to exit. Press Enter to capture the screen. Press Right Click to show the color picker. @@ -142,12 +142,12 @@ Press Space to open the side panel. CircleCountTool - + Circle Counter - + Add an autoincrementing counter bubble @@ -155,12 +155,12 @@ Press Space to open the side panel. CircleTool - + Circle წრე - + Set the Circle as the paint tool წრის ხელსაწყოს არჩევა სახატავად @@ -168,7 +168,7 @@ Press Space to open the side panel. ConfigWindow - + Configuration პარამეტრები @@ -178,7 +178,7 @@ Press Space to open the side panel. ინტერფეისი - + Filename Editor ფაილის სახელის რედაქტორი @@ -191,27 +191,27 @@ Press Space to open the side panel. Controller - + &Take Screenshot - + &Open Launcher - + &Configuration &პარამეტრები - + &Information &ინფორმაცია - + &Quit &გამოსვლა @@ -219,12 +219,12 @@ Press Space to open the side panel. CopyTool - + Copy კოპირება - + Copy the selection into the clipboard @@ -232,7 +232,7 @@ Press Space to open the side panel. DBusUtils - + Unable to connect via DBus DBus-ით დაკავშირება ვერ მოხერხდა @@ -240,12 +240,12 @@ Press Space to open the side panel. ExitTool - + Exit გამოსვლა - + Leave the capture screen ეკრანის გადაღების დატოვება @@ -253,47 +253,47 @@ Press Space to open the side panel. FileNameEditor - + Edit the name of your captures: შეცვალეთ თქვენი სურათების სახელი: - + Edit: თარგი: - + Preview: გადახედვა: - + Save შენახვა - + Saves the pattern თარგის შენახვა - + Reset განულება - + Restores the saved pattern შენახული შაბლონის განულება - + Clear გაწმენდა - + Deletes the name სახელის წაშლა @@ -301,112 +301,112 @@ Press Space to open the side panel. GeneneralConf - - + + Import იმპორტირება - - - + + + Error შეცდომა - + Unable to read file. ფაილის წაკითხვა ვერ მოხერხდა. - - + + Unable to write file. ფაილის ჩაწერა ვერ მოხერხდა. - + Save File ფაილის შენახვა - + Confirm Reset განულების დადასტურება - + Are you sure you want to reset the configuration? დარწმუნებული ხართ, რომ გსურთ პარამეტრების განულება? - + Show help message დახმარების შეტყობინების ნახვა - + Show the help message at the beginning in the capture mode. დახმარების შეტყობინების ნახვა გადაღების რეჟიმის დაწყებისას. - - + + Show desktop notifications ცნობების ჩვენება სამუშაო მაგიდაზე - + Show tray icon ხატულის ჩვენება სისტემურ პანელზე - + Show the systemtray icon ხატულის ჩვენება სისტემურ პანელზე - + Configuration File პარამეტრების ფაილი - + Export ექსპორტირება - + Reset განულება - + Launch at startup გაშვება სისტემის ჩატვირთვისას - + Launch Flameshot - + Close after capture - + Close after taking a screenshot - + Copy URL after upload - + Copy URL and close window after upload @@ -414,48 +414,48 @@ Press Space to open the side panel. ImgurUploader - + Upload to Imgur Imgur-ზე ატვირთვა - + Uploading Image სურათის ატვირთვა - + Copy URL URL-ის კოპირება - + Open URL URL-ის გახსნა - + Delete image - + Image to Clipboard. სურათის გაცვლის ბუფერში გაგზავნა - - + + Unable to open the URL. URL-ის გახსნა ვერ მოხერხდა. - + URL copied to clipboard. URL დაკოპირდა გაცვლის ბუფერში. - + Screenshot copied to clipboard. სურათი დაკოპირდა გაცვლის ბუფერში. @@ -463,12 +463,12 @@ Press Space to open the side panel. ImgurUploaderTool - + Image Uploader სურათის ამტვირთველი - + Upload the selection to Imgur შერჩეულის Imgur-ზე ატვირთვა @@ -476,7 +476,7 @@ Press Space to open the side panel. InfoWindow - + About პროგრამის შესახებ @@ -496,77 +496,77 @@ Press Space to open the side panel. მაუსის გორგოლაჭი - + Move selection 1px შერჩეულის გადაადგილება 1px-ით - + Resize selection 1px შერჩეულის ზომის შეცვლა 1px-ით - + Quit capture გადაღებიდან გამოსვლა - + Copy to clipboard გაცვლის ბუფერში კოპირება - + Save selection as a file შერჩეულის ფაილად შენახვა - + Undo the last modification ბოლო ცვლილების გაუქმება - + Toggle visibility of sidebar with options of the selected tool - + Show color picker ფერის შესარჩევის ჩვენება - + Change the tool's thickness ხელსაწყოს სისქის შეცვლა - + Available shortcuts in the screen capture mode. გადაღების რეჟიმში ხელმისაწვდომი მალსახმობები. - + Key კლავიში - + Description აღწერა - + <u><b>License</b></u> <u><b>ლიცენზია</b></u> - + <u><b>Version</b></u> <u><b>ვერსია</b></u> - + <u><b>Shortcuts</b></u> <u><b>მალსახმობები</b></u> @@ -574,12 +574,12 @@ Press Space to open the side panel. LineTool - + Line ხაზი - + Set the Line as the paint tool ხაზის ხელსაწყოს არჩევა სახატავად @@ -587,12 +587,12 @@ Press Space to open the side panel. MarkerTool - + Marker მარკერი - + Set the Marker as the paint tool მარკერის ხელსაწყოს არჩევა სახატავად @@ -600,12 +600,12 @@ Press Space to open the side panel. MoveTool - + Move გადაადგილება - + Move the selection area შერჩეული არის გადაადგილება @@ -613,12 +613,12 @@ Press Space to open the side panel. PencilTool - + Pencil ფანქარი - + Set the Pencil as the paint tool ფანქრის ხელსაწყოს არჩევა სახატავად @@ -626,12 +626,12 @@ Press Space to open the side panel. PinTool - + Pin Tool - + Pin image on the desktop @@ -639,13 +639,13 @@ Press Space to open the side panel. QObject - + Save Error შეცდომა შენახვისას - + Capture saved as სურათი შენახულია როგორც: @@ -656,31 +656,31 @@ Press Space to open the side panel. - + Error trying to save as შეცდომა მცდელობისას შენახულიყო როგორც: - - - - + + + + Unable to connect via DBus DBus-ით დაკავშირება ვერ მოხერხდა - + Error შეცდომა - + Unable to write in შემდეგ მისამართზე ჩაწერა ვერ მოხერხდა: - + URL copied to clipboard. URL დაკოპირდა გაცვლის ბუფერში. @@ -688,12 +688,12 @@ Press Space to open the side panel. RectangleTool - + Rectangle მართკუთხედი - + Set the Rectangle as the paint tool მართკუთხედის ხელსაწყოს არჩევა სახატავად @@ -701,12 +701,12 @@ Press Space to open the side panel. RedoTool - + Redo - + Redo the next modification @@ -714,12 +714,12 @@ Press Space to open the side panel. SaveTool - + Save შენახვა - + Save the capture სურათის შენახვა @@ -727,7 +727,7 @@ Press Space to open the side panel. ScreenGrabber - + Unable to capture screen ეკრანის გადაღება ვერ მოხერხდა @@ -735,12 +735,12 @@ Press Space to open the side panel. SelectionTool - + Rectangular Selection მართკუთხა შერჩევა - + Set Selection as the paint tool შერჩევის ხელსაწყოს არჩევა სახატავად @@ -748,22 +748,22 @@ Press Space to open the side panel. SidePanelWidget - + Active thickness: - + Active color: - + Press ESC to cancel - + Grab Color @@ -771,12 +771,12 @@ Press Space to open the side panel. SizeIndicatorTool - + Selection Size Indicator შერჩეულის ზომის მაჩვენებელი - + Show the dimensions of the selection (X Y) აჩვენებს შერჩეული არის განზომილებებს (X Y) @@ -784,107 +784,107 @@ Press Space to open the side panel. StrftimeChooserWidget - + Century (00-99) საუკუნე (00-99) - + Year (00-99) წელი (00-99) - + Year (2000) წელი (2000) - + Month Name (jan) თვის სახელი (იან) - + Month Name (january) თვის სახელი (იანვარი) - + Month (01-12) თვე (01-12) - + Week Day (1-7) კვირის დღე (1-7) - + Week (01-53) კვირა (01-53) - + Day Name (mon) დღის სახელი (ორშ) - + Day Name (monday) დღის სახელი (ორშაბათი) - + Day (01-31) დღე (01-31) - + Day of Month (1-31) თვის დღე (1-31) - + Day (001-366) დღე (001-366) - + Time (%H-%M-%S) - + Time (%H-%M) - + Hour (00-23) საათი (00-23) - + Hour (01-12) საათი (01-12) - + Minute (00-59) წუთი (00-59) - + Second (00-59) წამი (00-59) - + Full Date (%m/%d/%y) სრული თარიღი (%m/%d/%y) - + Full Date (%Y-%m-%d) სრული თარიღი (%Y-%m-%d) @@ -892,7 +892,7 @@ Press Space to open the side panel. SystemNotification - + Flameshot Info @@ -900,22 +900,22 @@ Press Space to open the side panel. TextConfig - + StrikeOut - + Underline - + Bold - + Italic @@ -923,12 +923,12 @@ Press Space to open the side panel. TextTool - + Text - + Add text to your capture @@ -936,37 +936,37 @@ Press Space to open the side panel. UIcolorEditor - + UI Color Editor ინტერფეისის ფერის რედაქტორი - + Change the color moving the selectors and see the changes in the preview buttons. შეცვალეთ ფერი ნიშნულის გადაადგილებით და შეხედეთ ცვლილებებს გადასახედ ღილაკებზე. - + Select a Button to modify it აირჩიეთ ღილაკი მის შესაცვლელად - + Main Color ძირითადი ფერი - + Click on this button to set the edition mode of the main color. დააწექით ამ ღილაკს ძირითადი ფერის არჩევის რეჟიმის ჩასართავად. - + Contrast Color კონტრასტული ფერი - + Click on this button to set the edition mode of the contrast color. დააწექით ამ ღილაკს კონტრასტული ფერის არჩევის რეჟიმის ჩასართავად. @@ -974,12 +974,12 @@ Press Space to open the side panel. UndoTool - + Undo უკუქმნა - + Undo the last modification ბოლო ცვლილების გაუქმება @@ -987,17 +987,17 @@ Press Space to open the side panel. VisualsEditor - + Opacity of area outside selection: შერჩეულის გარე არეს გაუმჭვირვალობა - + Button Selection ღილაკის არჩევა - + Select All ყველაფრის შერჩევა diff --git a/data/translations/Internationalization_nl.ts b/data/translations/Internationalization_nl.ts index 6404d7b5..a9dc2ddc 100644 --- a/data/translations/Internationalization_nl.ts +++ b/data/translations/Internationalization_nl.ts @@ -4,12 +4,12 @@ AppLauncher - + App Launcher App-starter - + Choose an app to open the capture Kies een app om de schermafdruk mee te openen @@ -32,18 +32,18 @@ Openhouden na selectie - - + + Error Fout - + Unable to write in Kan niet schrijven naar - + Unable to launch in terminal. Kan niet openen in terminalvenster. @@ -51,12 +51,12 @@ ArrowTool - + Arrow Cursor - + Set the Arrow as the paint tool Cursor instellen als verfgereedschap @@ -64,12 +64,12 @@ BlurTool - + Blur Vervaging - + Set Blur as the paint tool Vervaging instellen als verfgereedschap @@ -77,47 +77,47 @@ CaptureLauncher - + <b>Capture Mode</b> - + Rectangular Region - + Full Screen (All Monitors) - + No Delay - + second - + seconds - + Take new screenshot - + Area: - + Delay: @@ -125,12 +125,12 @@ CaptureWidget - + Unable to capture screen Kan scherm niet vastleggen - + Select an area with the mouse, or press Esc to exit. Press Enter to capture the screen. Press Right Click to show the color picker. @@ -146,12 +146,12 @@ Druk op spatie om het zijpaneel te openen. CircleCountTool - + Circle Counter - + Add an autoincrementing counter bubble @@ -159,12 +159,12 @@ Druk op spatie om het zijpaneel te openen. CircleTool - + Circle Cirkel - + Set the Circle as the paint tool Cirkel instellen als verfgereedschap @@ -172,7 +172,7 @@ Druk op spatie om het zijpaneel te openen. ConfigWindow - + Configuration Configuratie @@ -182,7 +182,7 @@ Druk op spatie om het zijpaneel te openen. Uiterlijk - + Filename Editor Bestandsnaambewerker @@ -195,27 +195,27 @@ Druk op spatie om het zijpaneel te openen. Controller - + &Take Screenshot Schermafdruk &maken - + &Open Launcher - + &Configuration &Configuratie - + &Information &Informatie - + &Quit &Afsluiten @@ -223,12 +223,12 @@ Druk op spatie om het zijpaneel te openen. CopyTool - + Copy Kopiëren - + Copy the selection into the clipboard Selectie kopiëren naar klembord @@ -236,7 +236,7 @@ Druk op spatie om het zijpaneel te openen. DBusUtils - + Unable to connect via DBus Kan niet verbinden via DBus @@ -244,12 +244,12 @@ Druk op spatie om het zijpaneel te openen. ExitTool - + Exit Afsluiten - + Leave the capture screen Verlaat het vastlegscherm @@ -257,47 +257,47 @@ Druk op spatie om het zijpaneel te openen. FileNameEditor - + Edit the name of your captures: Bewerk de naam van je schermafdrukken: - + Edit: Bewerken: - + Preview: Voorbeeld: - + Save Opslaan - + Saves the pattern Slaat het patroon op - + Reset Standaardwaarden - + Restores the saved pattern Herstelt het standaardpatroon - + Clear Wissen - + Deletes the name Wist de naam @@ -305,112 +305,112 @@ Druk op spatie om het zijpaneel te openen. GeneneralConf - - + + Import Importeren - - - + + + Error Fout - + Unable to read file. Kan bestand niet uitlezen. - - + + Unable to write file. Kan bestand niet wegschrijven. - + Save File Bestand opslaan - + Confirm Reset Herstellen bevestigen - + Are you sure you want to reset the configuration? Weet je zeker dat je de standwaardwaarden van de configuratie wilt herstellen? - + Show help message Uitleg tonen - + Show the help message at the beginning in the capture mode. Toont een bericht met uitleg bij het openen van de vastlegmodus. - - + + Show desktop notifications Bureaubladmeldingen tonen - + Show tray icon Systeemvakpictogram tonen - + Show the systemtray icon Toont het systeemvakpictogram - + Configuration File Configuratiebestand - + Export Exporteren - + Reset Standaardwaarden - + Launch at startup Automatisch opstarten - + Launch Flameshot Flameshot openen - + Close after capture - + Close after taking a screenshot - + Copy URL after upload - + Copy URL and close window after upload @@ -418,48 +418,48 @@ Druk op spatie om het zijpaneel te openen. ImgurUploader - + Upload to Imgur Uploaden naar Imgur - + Uploading Image Bezig met uploaden van afbeelding... - + Copy URL URL kopiëren - + Open URL URL openen - + Delete image Afbeelding verwijderen - + Image to Clipboard. Afbeelding naar klembord. - - + + Unable to open the URL. Kan URL niet openen. - + URL copied to clipboard. URL gekopieerd naar klembord. - + Screenshot copied to clipboard. Schermafdruk gekopieerd naar klembord. @@ -467,12 +467,12 @@ Druk op spatie om het zijpaneel te openen. ImgurUploaderTool - + Image Uploader Afbeeldingsuploader - + Upload the selection to Imgur Upload de selectie naar Imgur @@ -480,7 +480,7 @@ Druk op spatie om het zijpaneel te openen. InfoWindow - + About Over @@ -500,77 +500,77 @@ Druk op spatie om het zijpaneel te openen. Muiswiel - + Move selection 1px Selectie 1px verplaatsen - + Resize selection 1px Afmetingen van selectie 1px aanpassen - + Quit capture Vastleggen afsluiten - + Copy to clipboard Kopiëren naar klembord - + Save selection as a file Selectie opslaan als bestand - + Undo the last modification Laatste wijziging ongedaan maken - + Toggle visibility of sidebar with options of the selected tool Zijbalk met gereedschapsopties tonen/verbergen - + Show color picker Kleurkiezer tonen - + Change the tool's thickness Wijzig de gereedschapsdikte - + Available shortcuts in the screen capture mode. Beschikbare sneltoetsen in de vastlegmodus. - + Key Toets - + Description Omschrijving - + <u><b>License</b></u> <u><b>Лиценца</b></u> - + <u><b>Version</b></u> <u><b>Верзија</b></u> - + <u><b>Shortcuts</b></u> <u><b>Пречице</b></u> @@ -578,12 +578,12 @@ Druk op spatie om het zijpaneel te openen. LineTool - + Line Lijn - + Set the Line as the paint tool Lijn instellen als verfgereedschap @@ -591,12 +591,12 @@ Druk op spatie om het zijpaneel te openen. MarkerTool - + Marker Markeerstift - + Set the Marker as the paint tool Markeerstift instellen als verfgereedschap @@ -604,12 +604,12 @@ Druk op spatie om het zijpaneel te openen. MoveTool - + Move Verplaatsen - + Move the selection area Selectiegebied verplaatsen @@ -617,12 +617,12 @@ Druk op spatie om het zijpaneel te openen. PencilTool - + Pencil Potlood - + Set the Pencil as the paint tool Potlood instellen als verfgereedschap @@ -630,12 +630,12 @@ Druk op spatie om het zijpaneel te openen. PinTool - + Pin Tool Vastmaken - + Pin image on the desktop Afbeelding vastmaken op bureaublad @@ -643,13 +643,13 @@ Druk op spatie om het zijpaneel te openen. QObject - + Save Error Fout tijdens opslaan - + Capture saved as Schermafdruk opgeslagen als @@ -660,31 +660,31 @@ Druk op spatie om het zijpaneel te openen. - + Error trying to save as Fout tijdens opslaan als - - - - + + + + Unable to connect via DBus Kan niet verbinden via DBus - + Error Fout - + Unable to write in Kan niet wegschrijven naar - + URL copied to clipboard. URL gekopieerd naar klembord. @@ -692,12 +692,12 @@ Druk op spatie om het zijpaneel te openen. RectangleTool - + Rectangle Rechthoek - + Set the Rectangle as the paint tool Rechthoek instellen als verfgereedschap @@ -705,12 +705,12 @@ Druk op spatie om het zijpaneel te openen. RedoTool - + Redo Opnieuw - + Redo the next modification Volgende wijziging opnieuw toepassen @@ -718,13 +718,13 @@ Druk op spatie om het zijpaneel te openen. SaveTool - + Save Сачувај Opslaan - + Save the capture Schermafdruk opslaan @@ -732,7 +732,7 @@ Druk op spatie om het zijpaneel te openen. ScreenGrabber - + Unable to capture screen Kan scherm niet vastleggen @@ -740,12 +740,12 @@ Druk op spatie om het zijpaneel te openen. SelectionTool - + Rectangular Selection Rechthoekige selectie - + Set Selection as the paint tool Selectie instellen als verfgereedschap @@ -753,22 +753,22 @@ Druk op spatie om het zijpaneel te openen. SidePanelWidget - + Active thickness: Actieve dikte: - + Active color: Actieve kleur: - + Press ESC to cancel Druk op Esc om te annuleren - + Grab Color Kleur opnemen @@ -776,12 +776,12 @@ Druk op spatie om het zijpaneel te openen. SizeIndicatorTool - + Selection Size Indicator Grootteindicatie van selectie - + Show the dimensions of the selection (X Y) Toon de afmetingen van de selectie (X Y) @@ -789,107 +789,107 @@ Druk op spatie om het zijpaneel te openen. StrftimeChooserWidget - + Century (00-99) Eeuw (00-99) - + Year (00-99) Jaar (00-99) - + Year (2000) Jaar (2000) - + Month Name (jan) Naam van de maand (јаn) - + Month Name (january) Naam van de maand (јаnuari) - + Month (01-12) Maand (01-12) - + Week Day (1-7) Weekdag (1-7) - + Week (01-53) Week (01-53) - + Day Name (mon) Naam van de dag (ma) - + Day Name (monday) Naam van de dag (maandag) - + Day (01-31) Dag (01-31) - + Day of Month (1-31) Dag van de maand (1-31) - + Day (001-366) Dag (001-366) - + Time (%H-%M-%S) Tijd (%H-%M-%S) - + Time (%H-%M) Tijd (%H-%M) - + Hour (00-23) Uur (00-23) - + Hour (01-12) Uur (01-12) - + Minute (00-59) Minuten (00-59) - + Second (00-59) Seconden (00-59) - + Full Date (%m/%d/%y) Volledige datum (%m/%d/%y) - + Full Date (%Y-%m-%d) Volledige datum (%Y-%m-%d) @@ -897,7 +897,7 @@ Druk op spatie om het zijpaneel te openen. SystemNotification - + Flameshot Info Flameshot-informatie @@ -905,22 +905,22 @@ Druk op spatie om het zijpaneel te openen. TextConfig - + StrikeOut Doorhalen - + Underline Onderstrepen - + Bold Vetgedrukt - + Italic Cursief @@ -928,12 +928,12 @@ Druk op spatie om het zijpaneel te openen. TextTool - + Text Tekst - + Add text to your capture Voeg tekst toe aan je schermafdruk @@ -941,37 +941,37 @@ Druk op spatie om het zijpaneel te openen. UIcolorEditor - + UI Color Editor Kleurenschemabewerker - + Change the color moving the selectors and see the changes in the preview buttons. Wijzig de kleur d.m.v. de selectie-indicators en bekijk de wijzigingen op de voorbeeldknoppen. - + Select a Button to modify it Kies een te bewerken knop - + Main Color Hoofdkleur - + Click on this button to set the edition mode of the main color. Klik op deze knop om de hoofdkleur te bwerken. - + Contrast Color Contrastkleur - + Click on this button to set the edition mode of the contrast color. Klik op deze knop om de contrastkleur te bewerken. @@ -979,12 +979,12 @@ Druk op spatie om het zijpaneel te openen. UndoTool - + Undo Ongedaan mken - + Undo the last modification Laatste wijziging ongedaan maken @@ -992,17 +992,17 @@ Druk op spatie om het zijpaneel te openen. VisualsEditor - + Opacity of area outside selection: Doorzichtigheid van gebied buiten selectie: - + Button Selection Knopselectie - + Select All Alles selecteren diff --git a/data/translations/Internationalization_pl.ts b/data/translations/Internationalization_pl.ts index c0b2d696..e16c4d0e 100644 --- a/data/translations/Internationalization_pl.ts +++ b/data/translations/Internationalization_pl.ts @@ -4,12 +4,12 @@ AppLauncher - + App Launcher Uruchamianie aplikacji - + Choose an app to open the capture Wybierz aplikację do otwierania zrzutu @@ -32,18 +32,18 @@ Pozostaw otwarte po zaznaczeniu - - + + Error Błąd - + Unable to write in Nie można zapisać - + Unable to launch in terminal. Nie można uruchomić w terminalu. @@ -51,12 +51,12 @@ ArrowTool - + Arrow Strzałka - + Set the Arrow as the paint tool Rysowanie strzałek @@ -64,12 +64,12 @@ BlurTool - + Blur Rozmycie - + Set Blur as the paint tool Rozmywanie obszarów @@ -77,47 +77,47 @@ CaptureLauncher - + <b>Capture Mode</b> - + Rectangular Region - + Full Screen (All Monitors) - + No Delay - + second - + seconds - + Take new screenshot - + Area: - + Delay: @@ -125,12 +125,12 @@ CaptureWidget - + Unable to capture screen Nie można przechwycić ekranu - + Select an area with the mouse, or press Esc to exit. Press Enter to capture the screen. Press Right Click to show the color picker. @@ -145,12 +145,12 @@ Spacja, aby pokazać panel boczny. CircleCountTool - + Circle Counter - + Add an autoincrementing counter bubble @@ -158,12 +158,12 @@ Spacja, aby pokazać panel boczny. CircleTool - + Circle Okręgi - + Set the Circle as the paint tool Rysowanie okręgów i elips @@ -171,7 +171,7 @@ Spacja, aby pokazać panel boczny. ConfigWindow - + Configuration Konfiguracja @@ -181,7 +181,7 @@ Spacja, aby pokazać panel boczny. Interfejs - + Filename Editor Edytor nazw plików @@ -194,27 +194,27 @@ Spacja, aby pokazać panel boczny. Controller - + &Take Screenshot &Zrzut ekranu - + &Open Launcher - + &Configuration &Konfiguracja - + &Information &Informacje - + &Quit &Wyjdź @@ -222,12 +222,12 @@ Spacja, aby pokazać panel boczny. CopyTool - + Copy Kopiuj - + Copy the selection into the clipboard @@ -235,7 +235,7 @@ Spacja, aby pokazać panel boczny. DBusUtils - + Unable to connect via DBus Nie można się połączyć za pomocą DBus @@ -243,12 +243,12 @@ Spacja, aby pokazać panel boczny. ExitTool - + Exit Wyjdź - + Leave the capture screen Opuść ekran przechwytywania @@ -256,47 +256,47 @@ Spacja, aby pokazać panel boczny. FileNameEditor - + Edit the name of your captures: Edycja wzorca nazwy plików: - + Edit: Edytuj: - + Preview: Podgląd: - + Save Zapisz - + Saves the pattern Zapisuje wzorzec - + Reset Reset - + Restores the saved pattern Resetuje wzorzec - + Clear Wyczyść - + Deletes the name Czyści wzorzec @@ -304,112 +304,112 @@ Spacja, aby pokazać panel boczny. GeneneralConf - - + + Import Import - - - + + + Error Błąd - + Unable to read file. Nie można odczytać pliku. - - + + Unable to write file. Nie można zapisać pliku. - + Save File Zapisz plik - + Confirm Reset Potwierdź Reset - + Are you sure you want to reset the configuration? Czy na pewno chcesz zresetować konfigurację? - + Show help message Pokaż podpowiedzi - + Show the help message at the beginning in the capture mode. Pokaż podpowiedzi na początku trybu przechwytywania. - - + + Show desktop notifications Pokaż powiadomienia ekranowe - + Show tray icon Pokaż ikonę w trayu - + Show the systemtray icon Pokaż ikonę w zasobniku systemowym - + Configuration File Plik konfiguracyjny - + Export Export - + Reset Reset - + Launch at startup Uruchom podczas startu - + Launch Flameshot Uruchom Flameshot - + Close after capture - + Close after taking a screenshot - + Copy URL after upload - + Copy URL and close window after upload @@ -417,48 +417,48 @@ Spacja, aby pokazać panel boczny. ImgurUploader - + Upload to Imgur Wyślij do Imgur - + Uploading Image Wysyłanie obrazka - + Copy URL Kopiuj URL - + Open URL Otwórz URL - + Delete image Usuń obrazek - + Image to Clipboard. Obrazek do schowka. - - + + Unable to open the URL. Nie można otworzyć adresu URL. - + URL copied to clipboard. URL skopiowany do schowka. - + Screenshot copied to clipboard. Zrzut ekranu skopiowany do schowka. @@ -466,12 +466,12 @@ Spacja, aby pokazać panel boczny. ImgurUploaderTool - + Image Uploader Uploader obrazów - + Upload the selection to Imgur Wyślij zaznaczenie do Imgur @@ -479,7 +479,7 @@ Spacja, aby pokazać panel boczny. InfoWindow - + About O programie @@ -499,77 +499,77 @@ Spacja, aby pokazać panel boczny. Kółko myszy - + Move selection 1px Przesuń zaznaczenie o 1px - + Resize selection 1px Zmień rozmiar zaznaczenia o 1px - + Quit capture Zakończ przechwytywanie - + Copy to clipboard Kopiuj do schowka - + Save selection as a file Zapisz zaznaczenie jako plik - + Undo the last modification Cofnij ostatnią modyfikację - + Toggle visibility of sidebar with options of the selected tool - + Show color picker Pokaż próbnik kolorów - + Change the tool's thickness Zmień grubość narzędzia - + Available shortcuts in the screen capture mode. Dostępne skróty w trybie przechwytywania obrazu. - + Key Klawisz - + Description Działanie - + <u><b>License</b></u> <u><b>Licencja</b></u> - + <u><b>Version</b></u> <u><b>Wersja</b></u> - + <u><b>Shortcuts</b></u> <u><b>Skróty klawiszowe</b></u> @@ -577,12 +577,12 @@ Spacja, aby pokazać panel boczny. LineTool - + Line Linia - + Set the Line as the paint tool Ustawia linię jako narzędzie do rysowania @@ -590,12 +590,12 @@ Spacja, aby pokazać panel boczny. MarkerTool - + Marker Marker - + Set the Marker as the paint tool Ustawia Marker jako narzędzie rysowania @@ -603,12 +603,12 @@ Spacja, aby pokazać panel boczny. MoveTool - + Move Przesuwanie - + Move the selection area Przesuwa zaznaczenie @@ -616,12 +616,12 @@ Spacja, aby pokazać panel boczny. PencilTool - + Pencil Ołówek - + Set the Pencil as the paint tool Ustawia ołówek jako narzędzie do rysowania @@ -629,12 +629,12 @@ Spacja, aby pokazać panel boczny. PinTool - + Pin Tool Narzędzie przypinania - + Pin image on the desktop Przypnij obrazek do pulpitu @@ -642,13 +642,13 @@ Spacja, aby pokazać panel boczny. QObject - + Save Error Błąd zapisu - + Capture saved as Zaznaczenie zapisano jako @@ -659,31 +659,31 @@ Spacja, aby pokazać panel boczny. - + Error trying to save as Błąd przy próbie zapisu jako - - - - + + + + Unable to connect via DBus Nie udało się połączyć za pomocą DBus - + Error Błąd - + Unable to write in Nie można zapisać w - + URL copied to clipboard. URL skopiowany do schowka. @@ -691,12 +691,12 @@ Spacja, aby pokazać panel boczny. RectangleTool - + Rectangle Prostokąt - + Set the Rectangle as the paint tool Ustawia prostokąt jako narzędzie do rysowania @@ -704,12 +704,12 @@ Spacja, aby pokazać panel boczny. RedoTool - + Redo Cofnij - + Redo the next modification @@ -717,12 +717,12 @@ Spacja, aby pokazać panel boczny. SaveTool - + Save Zapisz - + Save the capture Zapisz zaznaczenie @@ -730,7 +730,7 @@ Spacja, aby pokazać panel boczny. ScreenGrabber - + Unable to capture screen Nie można przechwycić ekranu @@ -738,12 +738,12 @@ Spacja, aby pokazać panel boczny. SelectionTool - + Rectangular Selection Zaznaczenie prostokątne - + Set Selection as the paint tool Ustawia zaznaczenie prostokątne jako narzędzie do rysowania @@ -751,22 +751,22 @@ Spacja, aby pokazać panel boczny. SidePanelWidget - + Active thickness: - + Active color: Aktywny kolor: - + Press ESC to cancel Wciśnij ESC, aby anulować - + Grab Color Pobierz kolor @@ -774,12 +774,12 @@ Spacja, aby pokazać panel boczny. SizeIndicatorTool - + Selection Size Indicator Miernik zaznaczenia - + Show the dimensions of the selection (X Y) Pokazuje wymiary zaznaczenia (X Y) @@ -787,107 +787,107 @@ Spacja, aby pokazać panel boczny. StrftimeChooserWidget - + Century (00-99) Wiek (00-99) - + Year (00-99) Rok (00-99) - + Year (2000) Rok (2000) - + Month Name (jan) Nazwa miesiąca (cze) - + Month Name (january) Nazwa miesiąca (czerwiec) - + Month (01-12) Miesiąc (01-12) - + Week Day (1-7) Dzień tygodnia (1-7) - + Week (01-53) Tydzień (01-53) - + Day Name (mon) Nazwa dniaa (pią) - + Day Name (monday) Nazwa dnia (piątek) - + Day (01-31) Dzień (01-31) - + Day of Month (1-31) Dzień miesiąca (1-31) - + Day (001-366) Dzień (001-366) - + Time (%H-%M-%S) Czas (%H-%M-%S) - + Time (%H-%M) Czas (%H-%M) - + Hour (00-23) Godzina (00-23) - + Hour (01-12) Godzina (01-12) - + Minute (00-59) Minuta (00-59) - + Second (00-59) Sekunda (00-59) - + Full Date (%m/%d/%y) Data (%m/%d/%y) - + Full Date (%Y-%m-%d) Data (%Y-%m-%d) @@ -895,7 +895,7 @@ Spacja, aby pokazać panel boczny. SystemNotification - + Flameshot Info Flameshot Info @@ -903,22 +903,22 @@ Spacja, aby pokazać panel boczny. TextConfig - + StrikeOut Przekreślenie - + Underline Podkreślenie - + Bold Pogrubienie - + Italic Kursywa @@ -926,12 +926,12 @@ Spacja, aby pokazać panel boczny. TextTool - + Text Tekst - + Add text to your capture Dodaje tekst do zrzutu @@ -939,37 +939,37 @@ Spacja, aby pokazać panel boczny. UIcolorEditor - + UI Color Editor Edytor kolorów interfejsu - + Change the color moving the selectors and see the changes in the preview buttons. Zmień kolor przesuwając selektory i obserwując podgląd przycisków. - + Select a Button to modify it Wybierz przycisk do zmodyfikowania - + Main Color Kolor główny - + Click on this button to set the edition mode of the main color. Kliknij na przycisk aby móc modyfikować kolor główny. - + Contrast Color Kolor kontrastowy - + Click on this button to set the edition mode of the contrast color. Kliknij na przycisk aby móc modyfikować kolor kontrastowy. @@ -977,12 +977,12 @@ Spacja, aby pokazać panel boczny. UndoTool - + Undo Cofnij - + Undo the last modification Cofnij ostatnią zmianę @@ -990,17 +990,17 @@ Spacja, aby pokazać panel boczny. VisualsEditor - + Opacity of area outside selection: Przezroczystość obszaru poza zaznaczeniem: - + Button Selection Wybór przycisków - + Select All Wybierz wszystkie diff --git a/data/translations/Internationalization_pt_br.ts b/data/translations/Internationalization_pt_br.ts index 0b453255..15499804 100644 --- a/data/translations/Internationalization_pt_br.ts +++ b/data/translations/Internationalization_pt_br.ts @@ -4,12 +4,12 @@ AppLauncher - + App Launcher App Launcher - + Choose an app to open the capture Escolha uma aplicação para abrir a captura @@ -32,18 +32,18 @@ Manter aberto após seleção - - + + Error Erro - + Unable to write in Não é possível escrever em - + Unable to launch in terminal. Não foi possível abrir no terminal. @@ -51,12 +51,12 @@ ArrowTool - + Arrow Flecha - + Set the Arrow as the paint tool Usa a Flecha como ferramenta de desenho @@ -64,12 +64,12 @@ BlurTool - + Blur Desfoque - + Set Blur as the paint tool Usa o Desfoque como ferramenta de desenho @@ -77,47 +77,47 @@ CaptureLauncher - + <b>Capture Mode</b> - + Rectangular Region - + Full Screen (All Monitors) - + No Delay - + second - + seconds - + Take new screenshot - + Area: - + Delay: @@ -125,12 +125,12 @@ CaptureWidget - + Unable to capture screen Não foi possível capturar a tela - + Select an area with the mouse, or press Esc to exit. Press Enter to capture the screen. Press Right Click to show the color picker. @@ -146,12 +146,12 @@ Pressione espaço abrir o painel lateral. CircleCountTool - + Circle Counter - + Add an autoincrementing counter bubble @@ -159,12 +159,12 @@ Pressione espaço abrir o painel lateral. CircleTool - + Circle Círculo - + Set the Circle as the paint tool Usa o Círculo como ferramenta de desenho @@ -172,7 +172,7 @@ Pressione espaço abrir o painel lateral. ConfigWindow - + Configuration Configuração @@ -182,7 +182,7 @@ Pressione espaço abrir o painel lateral. Interface - + Filename Editor Editor de nome de arquivo @@ -195,27 +195,27 @@ Pressione espaço abrir o painel lateral. Controller - + &Take Screenshot &Tirar Screenshot - + &Open Launcher - + &Configuration &Configuração - + &Information &Informações - + &Quit &Sair @@ -223,12 +223,12 @@ Pressione espaço abrir o painel lateral. CopyTool - + Copy Copiar - + Copy the selection into the clipboard Copia a seleção para o clipboard @@ -236,7 +236,7 @@ Pressione espaço abrir o painel lateral. DBusUtils - + Unable to connect via DBus Não foi possível conectar via DBus @@ -244,12 +244,12 @@ Pressione espaço abrir o painel lateral. ExitTool - + Exit Sair - + Leave the capture screen Sair da ferramenta de captura @@ -257,47 +257,47 @@ Pressione espaço abrir o painel lateral. FileNameEditor - + Edit the name of your captures: Edite o nome das suas capturas: - + Edit: Editar: - + Preview: Preview: - + Save Salvar - + Saves the pattern Salva o padrão - + Reset Reiniciar - + Restores the saved pattern Restaura o padrão salvo - + Clear Limpar - + Deletes the name Deleta o nome @@ -305,112 +305,112 @@ Pressione espaço abrir o painel lateral. GeneneralConf - - + + Import Importar - - - + + + Error Erro - + Unable to read file. Não foi possível ler o arquivo. - - + + Unable to write file. Não foi possível escrever no arquivo. - + Save File Salvar Arquivo - + Confirm Reset Confirmar Reset - + Are you sure you want to reset the configuration? Tem certeza que deseja resetar a configuração? - + Show help message Mostrar mensagem de ajuda - + Show the help message at the beginning in the capture mode. Mostrar mensagem de ajuda no início do modo de captura. - - + + Show desktop notifications Mostrar notificações de Desktop - + Show tray icon Mostrar ícone de tray - + Show the systemtray icon Mosrar ícone na barra de aplicações - + Configuration File Arquivo de Configurações - + Export Exportar - + Reset Reset - + Launch at startup Iniciar junto com o sistema - + Launch Flameshot Iniciar Flameshot - + Close after capture - + Close after taking a screenshot - + Copy URL after upload - + Copy URL and close window after upload @@ -418,48 +418,48 @@ Pressione espaço abrir o painel lateral. ImgurUploader - + Upload to Imgur Upload no Imgur - + Uploading Image Upando Imagem - + Copy URL Copiar URL - + Open URL Abrir URL - + Delete image Deletar imagem - + Image to Clipboard. Imagem no Clipboard. - - + + Unable to open the URL. Não foi possível abrir a URL. - + URL copied to clipboard. URL copiada para o clipboard. - + Screenshot copied to clipboard. Screenshot copiada para o clipboard. @@ -467,12 +467,12 @@ Pressione espaço abrir o painel lateral. ImgurUploaderTool - + Image Uploader Uploader de imagens - + Upload the selection to Imgur Upa a seleção no Imgur @@ -480,7 +480,7 @@ Pressione espaço abrir o painel lateral. InfoWindow - + About Sobre @@ -500,77 +500,77 @@ Pressione espaço abrir o painel lateral. Roda do mouse - + Move selection 1px Move a seleção em 1px - + Resize selection 1px Redimensiona a seleção em 1px - + Quit capture Sair da captura - + Copy to clipboard Copiar ao clipboard - + Save selection as a file Salva seleção em um arquivo - + Undo the last modification Desfazer última modificação - + Toggle visibility of sidebar with options of the selected tool - + Show color picker Mostra seletor de cores - + Change the tool's thickness Muda a grossura do pincel - + Available shortcuts in the screen capture mode. Atalhos disponívels na tela de captura. - + Key Tecla - + Description Descrição - + <u><b>License</b></u> <u><b>Licença</b></u> - + <u><b>Version</b></u> <u><b>Versão</b></u> - + <u><b>Shortcuts</b></u> <u><b>Atalhos</b></u> @@ -578,12 +578,12 @@ Pressione espaço abrir o painel lateral. LineTool - + Line Linha - + Set the Line as the paint tool Usa a Linha como ferramenta de desenho @@ -591,12 +591,12 @@ Pressione espaço abrir o painel lateral. MarkerTool - + Marker Marcador - + Set the Marker as the paint tool Usa o marcador como ferramenta de desenho @@ -604,12 +604,12 @@ Pressione espaço abrir o painel lateral. MoveTool - + Move Mover - + Move the selection area Move a área de seleção @@ -617,12 +617,12 @@ Pressione espaço abrir o painel lateral. PencilTool - + Pencil Pincel - + Set the Pencil as the paint tool Usa o Lápis como ferramenta de desenho @@ -630,12 +630,12 @@ Pressione espaço abrir o painel lateral. PinTool - + Pin Tool Ferramenta de Pin - + Pin image on the desktop Pinnar imagem no desktop @@ -643,13 +643,13 @@ Pressione espaço abrir o painel lateral. QObject - + Save Error Salvar erro - + Capture saved as Captura salva como @@ -660,31 +660,31 @@ Pressione espaço abrir o painel lateral. - + Error trying to save as Erro tentando salvar como - - - - + + + + Unable to connect via DBus Não foi possível conectar via DBus - + Error Erro - + Unable to write in Não foi possível escrever em - + URL copied to clipboard. URL copiada para o clipboard. @@ -692,12 +692,12 @@ Pressione espaço abrir o painel lateral. RectangleTool - + Rectangle Retângulo - + Set the Rectangle as the paint tool Seta o Retângulo como ferramenta de desenho @@ -705,12 +705,12 @@ Pressione espaço abrir o painel lateral. RedoTool - + Redo Refazer - + Redo the next modification Refazer última modificação @@ -718,12 +718,12 @@ Pressione espaço abrir o painel lateral. SaveTool - + Save Salvar - + Save the capture Salva a captura @@ -731,7 +731,7 @@ Pressione espaço abrir o painel lateral. ScreenGrabber - + Unable to capture screen Não foi possível capturar a tela @@ -739,12 +739,12 @@ Pressione espaço abrir o painel lateral. SelectionTool - + Rectangular Selection Seleção Retangular - + Set Selection as the paint tool Estabelece o Selecionador como ferramenta de desenho @@ -752,22 +752,22 @@ Pressione espaço abrir o painel lateral. SidePanelWidget - + Active thickness: - + Active color: Cor ativa: - + Press ESC to cancel Presione Esc para cancelar - + Grab Color Usar Cor @@ -775,12 +775,12 @@ Pressione espaço abrir o painel lateral. SizeIndicatorTool - + Selection Size Indicator Indicador do Tamanho da Seleção - + Show the dimensions of the selection (X Y) Mostra a dimensão da seleção (X Y) @@ -788,107 +788,107 @@ Pressione espaço abrir o painel lateral. StrftimeChooserWidget - + Century (00-99) Século (00-99) - + Year (00-99) Ano (00-99) - + Year (2000) Ano (2000) - + Month Name (jan) Nome do mês (jan) - + Month Name (january) Nome do mês (janeiro) - + Month (01-12) Mês (01-12) - + Week Day (1-7) Dia da semana (1-7) - + Week (01-53) Semana (01-53) - + Day Name (mon) Nome do dia (seg) - + Day Name (monday) Nome do dia (segunda) - + Day (01-31) Dia (01-31) - + Day of Month (1-31) Dia do Mês (1-31) - + Day (001-366) Dia (001-366) - + Time (%H-%M-%S) Tempo (%H-%M-%S) - + Time (%H-%M) Tempo (%H-%M) - + Hour (00-23) Hora (00-23) - + Hour (01-12) Hora (01-12) - + Minute (00-59) Minuto (00-59) - + Second (00-59) Segundo (00-59) - + Full Date (%m/%d/%y) Data Completa (%m/%d/%y) - + Full Date (%Y-%m-%d) Data Completa (%Y-%m-%d) @@ -896,7 +896,7 @@ Pressione espaço abrir o painel lateral. SystemNotification - + Flameshot Info Informações do Flameshot @@ -904,22 +904,22 @@ Pressione espaço abrir o painel lateral. TextConfig - + StrikeOut Sobrescrito - + Underline Sublinhado - + Bold Negrito - + Italic Itálico @@ -927,12 +927,12 @@ Pressione espaço abrir o painel lateral. TextTool - + Text Texto - + Add text to your capture Adicionar texto à captura @@ -940,37 +940,37 @@ Pressione espaço abrir o painel lateral. UIcolorEditor - + UI Color Editor Interface de Edição de Cores - + Change the color moving the selectors and see the changes in the preview buttons. Modifique a cor movendo os seletores e veja as mudanças nos botões de preview. - + Select a Button to modify it Selecione um botão para modificá-lo - + Main Color Cor Principal - + Click on this button to set the edition mode of the main color. Clique neste botão para setar o modo de edição da cor principal. - + Contrast Color Cor de Contraste - + Click on this button to set the edition mode of the contrast color. Clique neste botão para setar o modo de edição da cor de contraste. @@ -978,12 +978,12 @@ Pressione espaço abrir o painel lateral. UndoTool - + Undo Desfazer - + Undo the last modification Desfaz a última modificação @@ -991,17 +991,17 @@ Pressione espaço abrir o painel lateral. VisualsEditor - + Opacity of area outside selection: Opacidade da área de seleção: - + Button Selection Botão de seleção - + Select All Selecionar Todos diff --git a/data/translations/Internationalization_ru.ts b/data/translations/Internationalization_ru.ts index 50c5e731..70940cfa 100644 --- a/data/translations/Internationalization_ru.ts +++ b/data/translations/Internationalization_ru.ts @@ -4,12 +4,12 @@ AppLauncher - + App Launcher Запуск приложения - + Choose an app to open the capture Выберите приложение, которым открыть снимок @@ -32,18 +32,18 @@ Оставить запущенным после выделения - - + + Error Ошибка - + Unable to write in Не удалось сохранить - + Unable to launch in terminal. Не удалось запустить в терминале. @@ -51,12 +51,12 @@ ArrowTool - + Arrow Стрелка - + Set the Arrow as the paint tool Выбрать Стрелку инструментом для рисования @@ -64,12 +64,12 @@ BlurTool - + Blur Размытие - + Set Blur as the paint tool Выбрать Размытие инструментом для рисования @@ -77,47 +77,47 @@ CaptureLauncher - + <b>Capture Mode</b> - + Rectangular Region - + Full Screen (All Monitors) - + No Delay - + second - + seconds - + Take new screenshot - + Area: - + Delay: @@ -125,12 +125,12 @@ CaptureWidget - + Unable to capture screen Не удалось захватить экран - + Select an area with the mouse, or press Esc to exit. Press Enter to capture the screen. Press Right Click to show the color picker. @@ -146,12 +146,12 @@ Press Space to open the side panel. CircleCountTool - + Circle Counter - + Add an autoincrementing counter bubble @@ -159,12 +159,12 @@ Press Space to open the side panel. CircleTool - + Circle Окружность - + Set the Circle as the paint tool Выбрать Окружность инструментом для рисования @@ -172,7 +172,7 @@ Press Space to open the side panel. ConfigWindow - + Configuration Настройка @@ -182,7 +182,7 @@ Press Space to open the side panel. Интерфейс - + Filename Editor Редактор имен файлов @@ -195,27 +195,27 @@ Press Space to open the side panel. Controller - + &Take Screenshot &Сделать снимок - + &Open Launcher - + &Configuration &Настройка - + &Information &Информация - + &Quit &Выход @@ -223,12 +223,12 @@ Press Space to open the side panel. CopyTool - + Copy Скопировать - + Copy the selection into the clipboard Скопировать выделение в буфер обмена @@ -236,7 +236,7 @@ Press Space to open the side panel. DBusUtils - + Unable to connect via DBus Не удалось подключиться через DBus @@ -244,12 +244,12 @@ Press Space to open the side panel. ExitTool - + Exit Выход - + Leave the capture screen Покинуть захват экрана @@ -257,47 +257,47 @@ Press Space to open the side panel. FileNameEditor - + Edit the name of your captures: Отредактируйте имя ваших снимков: - + Edit: Шаблон: - + Preview: Предпросмотр: - + Save Сохранить - + Saves the pattern Сохранить шаблон - + Reset Сбросить - + Restores the saved pattern Восстанавливает сохраненный шаблон - + Clear Очистить - + Deletes the name Удаляет имя @@ -305,112 +305,112 @@ Press Space to open the side panel. GeneneralConf - - + + Import Импорт - - - + + + Error Ошибка - + Unable to read file. Не удалось прочитать файл. - - + + Unable to write file. Не удалось записать файл. - + Save File Сохранить файл - + Confirm Reset Подтвердить сброс - + Are you sure you want to reset the configuration? Вы действительно хотите сбросить настройки? - + Show help message Показывать справочное сообщение - + Show the help message at the beginning in the capture mode. Показывать справочное сообщение перед началом захвата экрана. - - + + Show desktop notifications Показывать уведомления - + Show tray icon Показывать значок в трее - + Show the systemtray icon Показать значок в системном трее - + Configuration File Файл конфигурации - + Export Экспорт - + Reset Сброс - + Launch at startup Запускать при старте системы - + Launch Flameshot Запустить Flameshot - + Close after capture - + Close after taking a screenshot - + Copy URL after upload - + Copy URL and close window after upload @@ -418,48 +418,48 @@ Press Space to open the side panel. ImgurUploader - + Upload to Imgur Загрузить в Imgur - + Uploading Image Загрузка изображения - + Copy URL Скопировать URL - + Open URL Открыть URL - + Delete image Удалить изображение - + Image to Clipboard. Изображение в буфер обмена. - - + + Unable to open the URL. Не удалось открыть URL. - + URL copied to clipboard. URL скопирован в буфер обмена. - + Screenshot copied to clipboard. Снимок скопирован в буфер обмена. @@ -467,12 +467,12 @@ Press Space to open the side panel. ImgurUploaderTool - + Image Uploader Отправка изображений - + Upload the selection to Imgur Загрузить выделение на Imgur @@ -480,7 +480,7 @@ Press Space to open the side panel. InfoWindow - + About Информация @@ -500,77 +500,77 @@ Press Space to open the side panel. Колесико мыши - + Move selection 1px Переместить выделение на 1px - + Resize selection 1px Изменить размер выделения на 1px - + Quit capture Выйти из захвата экрана - + Copy to clipboard Скопировать в буфер обмена - + Save selection as a file Сохранить выделение в файл - + Undo the last modification Отменить последнее изменение - + Toggle visibility of sidebar with options of the selected tool Показать боковую панель с настройками выбранного инструмента - + Show color picker Показать выбор цвета - + Change the tool's thickness Изменить толщину инструмента - + Available shortcuts in the screen capture mode. Доступные горячие клавиши в режиме захвата экрана. - + Key Клавиша - + Description Описание - + <u><b>License</b></u> <u><b>Лицензия</b></u> - + <u><b>Version</b></u> <u><b>Версия</b></u> - + <u><b>Shortcuts</b></u> <u><b>Горячие клавиши</b></u> @@ -578,12 +578,12 @@ Press Space to open the side panel. LineTool - + Line Линия - + Set the Line as the paint tool Выбрать Линию инструментом для рисования @@ -591,12 +591,12 @@ Press Space to open the side panel. MarkerTool - + Marker Маркер - + Set the Marker as the paint tool Выбрать Маркер инструментом для рисования @@ -604,12 +604,12 @@ Press Space to open the side panel. MoveTool - + Move Перемещение - + Move the selection area Выбрать Перемещение инструментом для рисования @@ -617,12 +617,12 @@ Press Space to open the side panel. PencilTool - + Pencil Карандаш - + Set the Pencil as the paint tool Выбрать Карандаш инструментом для рисования @@ -630,12 +630,12 @@ Press Space to open the side panel. PinTool - + Pin Tool Булавка - + Pin image on the desktop Прикрепить изображение к рабочему столу @@ -643,13 +643,13 @@ Press Space to open the side panel. QObject - + Save Error Ошибка сохранения - + Capture saved as Снимок сохранён как @@ -660,31 +660,31 @@ Press Space to open the side panel. - + Error trying to save as Ошибка при попытке сохранить как - - - - + + + + Unable to connect via DBus Не удалось подключиться через DBus - + Error Ошибка - + Unable to write in Не удалось сохранить - + URL copied to clipboard. URL скопирован в буфер обмена. @@ -692,12 +692,12 @@ Press Space to open the side panel. RectangleTool - + Rectangle Прямоугольник - + Set the Rectangle as the paint tool Выбрать Прямоугольник инструментом для рисования @@ -705,12 +705,12 @@ Press Space to open the side panel. RedoTool - + Redo Повторить - + Redo the next modification Повторить последнее изменение @@ -718,12 +718,12 @@ Press Space to open the side panel. SaveTool - + Save Сохранить - + Save the capture Сохранить снимок @@ -731,7 +731,7 @@ Press Space to open the side panel. ScreenGrabber - + Unable to capture screen Не удалось захватить экран @@ -739,12 +739,12 @@ Press Space to open the side panel. SelectionTool - + Rectangular Selection Прямоугольное выделение - + Set Selection as the paint tool Выбрать Прямоугольное выделение инструментом для рисования @@ -752,22 +752,22 @@ Press Space to open the side panel. SidePanelWidget - + Active thickness: Активная толщина: - + Active color: Активный цвет: - + Press ESC to cancel Нажмите Esc для отмены - + Grab Color Захватить цвет с экрана @@ -775,12 +775,12 @@ Press Space to open the side panel. SizeIndicatorTool - + Selection Size Indicator Индикатор размера выделения - + Show the dimensions of the selection (X Y) Показывает размер выделения (X Y) @@ -788,107 +788,107 @@ Press Space to open the side panel. StrftimeChooserWidget - + Century (00-99) Век (00-99) - + Year (00-99) Год (00-99) - + Year (2000) Год (2000) - + Month Name (jan) Название месяца (янв) - + Month Name (january) Название месяца (январь) - + Month (01-12) Месяц (01-12) - + Week Day (1-7) День недели (1-7) - + Week (01-53) Неделя (01-53) - + Day Name (mon) День недели (пн) - + Day Name (monday) День недели (понедельник) - + Day (01-31) День (01-31) - + Day of Month (1-31) День месяца (1-31) - + Day (001-366) День (001-366) - + Time (%H-%M-%S) Время (%H-%M-%S) - + Time (%H-%M) Время (%H-%M) - + Hour (00-23) Час (00-23) - + Hour (01-12) Час (01-12) - + Minute (00-59) Минута (00-59) - + Second (00-59) Секунда (00-59) - + Full Date (%m/%d/%y) Полная дата (%m/%d/%y) - + Full Date (%Y-%m-%d) Полная дата (%Y-%m-%d) @@ -896,7 +896,7 @@ Press Space to open the side panel. SystemNotification - + Flameshot Info Flameshot Инфо @@ -904,22 +904,22 @@ Press Space to open the side panel. TextConfig - + StrikeOut Зачеркнутый - + Underline Подчеркнутый - + Bold Полужирный - + Italic Курсив @@ -927,12 +927,12 @@ Press Space to open the side panel. TextTool - + Text Текст - + Add text to your capture Добавить текст на снимок @@ -940,37 +940,37 @@ Press Space to open the side panel. UIcolorEditor - + UI Color Editor Редактор цвета интерфейса - + Change the color moving the selectors and see the changes in the preview buttons. Измените цвет, перемещая выделение, и посмотрите изменения в кнопках предварительного просмотра. - + Select a Button to modify it Выберите кнопку, чтобы изменить ее - + Main Color Основной цвет - + Click on this button to set the edition mode of the main color. Нажмите на эту кнопку, чтобы перейти в режим редактирования основного цвета. - + Contrast Color Контрастный цвет - + Click on this button to set the edition mode of the contrast color. Нажмите на эту кнопку, чтобы перейти в режим редактирования контрастного цвета. @@ -978,12 +978,12 @@ Press Space to open the side panel. UndoTool - + Undo Отменить - + Undo the last modification Отменить последнее изменение @@ -991,17 +991,17 @@ Press Space to open the side panel. VisualsEditor - + Opacity of area outside selection: Затемнение невыделенной области: - + Button Selection Выбор кнопок - + Select All Выбрать все diff --git a/data/translations/Internationalization_sk.ts b/data/translations/Internationalization_sk.ts index 3dd9948d..3b0295a4 100644 --- a/data/translations/Internationalization_sk.ts +++ b/data/translations/Internationalization_sk.ts @@ -4,12 +4,12 @@ AppLauncher - + App Launcher Spúšťač aplikácií - + Choose an app to open the capture Vyberte aplikáciu na otvorenie snímky obrazovky @@ -32,18 +32,18 @@ Nechať otvorené po výbere - - + + Error Chyba - + Unable to write in Zlyhal zápis do - + Unable to launch in terminal. Nepodarilo sa spustiť v termináli. @@ -51,12 +51,12 @@ ArrowTool - + Arrow Šípka - + Set the Arrow as the paint tool Nastaviť Šípku ako nástroj pre úpravy @@ -64,12 +64,12 @@ BlurTool - + Blur Rozmazanie - + Set Blur as the paint tool Nastaviť Rozmazanie ako nástroj pre úpravy @@ -77,47 +77,47 @@ CaptureLauncher - + <b>Capture Mode</b> <b>Režim zachytávania</b> - + Rectangular Region Pravouhlá oblasť - + Full Screen (All Monitors) Celá obrazovka (všetky monitory) - + No Delay Bez oneskorenia - + second sekunda - + seconds sekundy - + Take new screenshot Urobiť novú snímku - + Area: Oblasť: - + Delay: Oneskorenie: @@ -125,12 +125,12 @@ CaptureWidget - + Unable to capture screen Nepodarilo sa zachytiť obrazovku - + Select an area with the mouse, or press Esc to exit. Press Enter to capture the screen. Press Right Click to show the color picker. @@ -146,12 +146,12 @@ Stlačte medzerník pre otvorenie postranného panelu. CircleCountTool - + Circle Counter - + Add an autoincrementing counter bubble @@ -159,12 +159,12 @@ Stlačte medzerník pre otvorenie postranného panelu. CircleTool - + Circle Kruh - + Set the Circle as the paint tool @@ -172,7 +172,7 @@ Stlačte medzerník pre otvorenie postranného panelu. ConfigWindow - + Configuration Konfigurácia @@ -182,7 +182,7 @@ Stlačte medzerník pre otvorenie postranného panelu. Interfejs - + Filename Editor Editor názvov súborov @@ -195,27 +195,27 @@ Stlačte medzerník pre otvorenie postranného panelu. Controller - + &Take Screenshot &Vytvoriť snímku - + &Open Launcher - + &Configuration &Konfigurácia - + &Information &Informácie - + &Quit &Ukončiť @@ -223,12 +223,12 @@ Stlačte medzerník pre otvorenie postranného panelu. CopyTool - + Copy Kopírovať - + Copy the selection into the clipboard Kopírovať výber do schránky @@ -236,7 +236,7 @@ Stlačte medzerník pre otvorenie postranného panelu. DBusUtils - + Unable to connect via DBus Nie je možné pripojiť sa prostredníctvom DBus @@ -244,12 +244,12 @@ Stlačte medzerník pre otvorenie postranného panelu. ExitTool - + Exit Ukončiť - + Leave the capture screen Opustiť obrazovku so zachytávaním obrazovky @@ -257,47 +257,47 @@ Stlačte medzerník pre otvorenie postranného panelu. FileNameEditor - + Edit the name of your captures: Upraviť meno vašich snímok obrazovky: - + Edit: Upraviť: - + Preview: Náhľad: - + Save Uložiť - + Saves the pattern Uloží vzor - + Reset Resetovať - + Restores the saved pattern Vráti zmeny - + Clear Vyčistiť - + Deletes the name Vymaže meno @@ -305,112 +305,112 @@ Stlačte medzerník pre otvorenie postranného panelu. GeneneralConf - - + + Import Importovať - - - + + + Error Chyba - + Unable to read file. Zlyhalo čítanie súboru. - - + + Unable to write file. Zlyhal zápis do súboru. - + Save File Uložiť súbor - + Confirm Reset Potvrdiť Reset - + Are you sure you want to reset the configuration? Naozaj si želáte resetovať aktuálnu konfiguráciu? - + Show help message Zobraziť nápovedu - + Show the help message at the beginning in the capture mode. Zobraziť nápovedu na začiatku počas režimu zachytávania obrazovky. - - + + Show desktop notifications Zobraziť systémové upozornenia - + Show tray icon Zobraziť stavovú ikonu - + Show the systemtray icon Zobraziť ikonu v stavovej oblasti - + Configuration File Súbor s konfiguráciou - + Export Exportovať - + Reset Resetovať - + Launch at startup Spúšťať pri štarte - + Launch Flameshot Spustiť Flameshot - + Close after capture Zavrieť po vytvorení snímky - + Close after taking a screenshot Zatvoriť po vytvorení snímky obrazovky - + Copy URL after upload - + Copy URL and close window after upload @@ -418,48 +418,48 @@ Stlačte medzerník pre otvorenie postranného panelu. ImgurUploader - + Upload to Imgur Nahrať na Imgur - + Uploading Image Nahrávam obrázok - + Copy URL Kopírovať URL - + Open URL Otvoriť URL - + Delete image Vymazať obrázok - + Image to Clipboard. Obrázok do schránky. - - + + Unable to open the URL. Nepodarilo sa otvoriť URL. - + URL copied to clipboard. URL skopírovaná do schránky. - + Screenshot copied to clipboard. Snímka obrazovky bola skopírovaná do schránky. @@ -467,12 +467,12 @@ Stlačte medzerník pre otvorenie postranného panelu. ImgurUploaderTool - + Image Uploader Uploader obrázkov - + Upload the selection to Imgur Nahrať výber na Imgur @@ -480,7 +480,7 @@ Stlačte medzerník pre otvorenie postranného panelu. InfoWindow - + About O programe @@ -500,77 +500,77 @@ Stlačte medzerník pre otvorenie postranného panelu. Kolečko myši - + Move selection 1px Presunúť výber o 1 px - + Resize selection 1px Zmeniť rozmery výberu o 1 px - + Quit capture Ukončiť zachytávanie obrazovky - + Copy to clipboard Kopírovať do schránky - + Save selection as a file Zapísať výber do súboru - + Undo the last modification Vrátiť poslednú úpravu - + Toggle visibility of sidebar with options of the selected tool Prepnúť viditeľnosť bočnej lišty s možnosťami vybraného nástroja - + Show color picker Zobraziť dialóg na výber farby - + Change the tool's thickness Zmena hrúbky nástroja - + Available shortcuts in the screen capture mode. Dostupné klávesové skratky v režime zachytávania obrazovky. - + Key Kláves - + Description Popis - + <u><b>License</b></u> <u><b>Licencia</b></u> - + <u><b>Version</b></u> <u><b>Verzia</b></u> - + <u><b>Shortcuts</b></u> <u><b>Klávesové skratky</b></u> @@ -578,12 +578,12 @@ Stlačte medzerník pre otvorenie postranného panelu. LineTool - + Line Čiara - + Set the Line as the paint tool Nastaviť Čiaru ako nástroj pre úpravy @@ -591,12 +591,12 @@ Stlačte medzerník pre otvorenie postranného panelu. MarkerTool - + Marker Fixka - + Set the Marker as the paint tool Nastaviť Fixku ako nástroj pre úpravy @@ -604,12 +604,12 @@ Stlačte medzerník pre otvorenie postranného panelu. MoveTool - + Move Presun - + Move the selection area Presunúť oblasť výberu @@ -617,12 +617,12 @@ Stlačte medzerník pre otvorenie postranného panelu. PencilTool - + Pencil Ceruzka - + Set the Pencil as the paint tool Nastaviť Ceruzku ako nástroj pre úpravy @@ -630,12 +630,12 @@ Stlačte medzerník pre otvorenie postranného panelu. PinTool - + Pin Tool Špendlík - + Pin image on the desktop Pripnúť obrázok na plochu @@ -643,21 +643,21 @@ Stlačte medzerník pre otvorenie postranného panelu. QObject - - - - + + + + Unable to connect via DBus Nie je možné pripojiť sa prostredníctvom DBus - + Error Chyba - + Unable to write in Zlyhal zápis do @@ -668,23 +668,23 @@ Stlačte medzerník pre otvorenie postranného panelu. - + Capture saved as Snímka uložená ako - + Error trying to save as Chyba pri ukladaní do - + Save Error Chyba pri ukladaní - + URL copied to clipboard. URL skopírovaná do schránky. @@ -692,12 +692,12 @@ Stlačte medzerník pre otvorenie postranného panelu. RectangleTool - + Rectangle Obdĺžnik - + Set the Rectangle as the paint tool Nastaviť Obdĺžnik ako nástroj pre úpravy @@ -705,12 +705,12 @@ Stlačte medzerník pre otvorenie postranného panelu. RedoTool - + Redo Znova - + Redo the next modification Zopakovať úpravu @@ -718,12 +718,12 @@ Stlačte medzerník pre otvorenie postranného panelu. SaveTool - + Save Uložiť - + Save the capture Uložiť snímku obrazovky @@ -731,7 +731,7 @@ Stlačte medzerník pre otvorenie postranného panelu. ScreenGrabber - + Unable to capture screen Nepodarilo sa zachytiť obrazovku @@ -739,12 +739,12 @@ Stlačte medzerník pre otvorenie postranného panelu. SelectionTool - + Rectangular Selection Obdĺžnikový výber - + Set Selection as the paint tool Nastaviť Výber ako nástroj pre úpravy @@ -752,22 +752,22 @@ Stlačte medzerník pre otvorenie postranného panelu. SidePanelWidget - + Active thickness: Aktívna hrúbka: - + Active color: Aktívna farba: - + Press ESC to cancel Stlačte ESC pre zrušenie - + Grab Color Snímať farbu @@ -775,12 +775,12 @@ Stlačte medzerník pre otvorenie postranného panelu. SizeIndicatorTool - + Selection Size Indicator Ukazovateľ veľkosti výberu - + Show the dimensions of the selection (X Y) Zobraziť rozmery výberu (X Y) @@ -788,107 +788,107 @@ Stlačte medzerník pre otvorenie postranného panelu. StrftimeChooserWidget - + Century (00-99) Storočie (00-99) - + Year (00-99) Rok (00-99) - + Year (2000) Rok (2000) - + Month Name (jan) Meno mesiaca (jan) - + Month Name (january) Meno mesiaca (január) - + Month (01-12) Mesiac (01-12) - + Week Day (1-7) Deň v týždni (1-7) - + Week (01-53) Týždeň (01-53) - + Day Name (mon) Meno dňa (pon) - + Day Name (monday) Meno dňa (pondelok) - + Day (01-31) Deň (01-31) - + Day of Month (1-31) Deň v mesiaci (1-31) - + Day (001-366) Deň (001-366) - + Time (%H-%M-%S) Čas (%H-%M-%S) - + Time (%H-%M) Čas (%H-%M) - + Hour (00-23) Hodina (00-23) - + Hour (01-12) Hodina (01-12) - + Minute (00-59) Minúta (00-59) - + Second (00-59) Sekunda (00-59) - + Full Date (%m/%d/%y) Celý dátum (%m/%d/%y) - + Full Date (%Y-%m-%d) Celý dátum (%Y-%m-%d) @@ -896,7 +896,7 @@ Stlačte medzerník pre otvorenie postranného panelu. SystemNotification - + Flameshot Info Informácie o programe Flameshot @@ -904,22 +904,22 @@ Stlačte medzerník pre otvorenie postranného panelu. TextConfig - + StrikeOut Preškrtnuté - + Underline Podčiarknuté - + Bold Tučné - + Italic Kurzíva @@ -927,12 +927,12 @@ Stlačte medzerník pre otvorenie postranného panelu. TextTool - + Text Text - + Add text to your capture Pridať text do snímky @@ -940,37 +940,37 @@ Stlačte medzerník pre otvorenie postranného panelu. UIcolorEditor - + UI Color Editor Editor farieb interfejsu - + Change the color moving the selectors and see the changes in the preview buttons. Presunom bežcov nastavte farbu a sledujte tieto zmeny v náhľade. - + Select a Button to modify it Kliknite na tlačidlo pre jeho úpravu - + Main Color Hlavná farba - + Click on this button to set the edition mode of the main color. Pre nastavenie hlavnej farby kliknite na toto tlačidlo. - + Contrast Color Kontrastná farba - + Click on this button to set the edition mode of the contrast color. Pre nastavenie kontrastnej farby kliknite na toto tlačidlo. @@ -978,12 +978,12 @@ Stlačte medzerník pre otvorenie postranného panelu. UndoTool - + Undo Späť - + Undo the last modification Vrátiť poslednú úpravu @@ -991,17 +991,17 @@ Stlačte medzerník pre otvorenie postranného panelu. VisualsEditor - + Opacity of area outside selection: Priehľadnosť oblasti mimo výberu: - + Button Selection Výber tlačidiel - + Select All Vybrať všetky diff --git a/data/translations/Internationalization_sr.ts b/data/translations/Internationalization_sr.ts index 152535ec..a6e6d522 100644 --- a/data/translations/Internationalization_sr.ts +++ b/data/translations/Internationalization_sr.ts @@ -4,12 +4,12 @@ AppLauncher - + App Launcher Покретач - + Choose an app to open the capture Изаберите програм у ком желите да отворите снимак @@ -32,18 +32,18 @@ Остави отворено након избора - - + + Error Грешка - + Unable to write in Нисам успео да сачувам - + Unable to launch in terminal. Нисам успео да покренем у терминалу. @@ -51,12 +51,12 @@ ArrowTool - + Arrow Стрелица - + Set the Arrow as the paint tool Избор цртања стрелице @@ -64,12 +64,12 @@ BlurTool - + Blur Замућење - + Set Blur as the paint tool Избор цртања замућене области @@ -77,47 +77,47 @@ CaptureLauncher - + <b>Capture Mode</b> - + Rectangular Region - + Full Screen (All Monitors) - + No Delay - + second - + seconds - + Take new screenshot - + Area: - + Delay: @@ -125,12 +125,12 @@ CaptureWidget - + Unable to capture screen Нисам успео да снимим екран - + Select an area with the mouse, or press Esc to exit. Press Enter to capture the screen. Press Right Click to show the color picker. @@ -146,12 +146,12 @@ Press Space to open the side panel. CircleCountTool - + Circle Counter - + Add an autoincrementing counter bubble @@ -159,12 +159,12 @@ Press Space to open the side panel. CircleTool - + Circle Круг - + Set the Circle as the paint tool Избор цртања круга @@ -172,7 +172,7 @@ Press Space to open the side panel. ConfigWindow - + Configuration Подешавања @@ -182,7 +182,7 @@ Press Space to open the side panel. Изглед - + Filename Editor Избор имена датотеке @@ -195,27 +195,27 @@ Press Space to open the side panel. Controller - + &Take Screenshot &Направи снимак екрана - + &Open Launcher - + &Configuration &Подешавања - + &Information Ин&формације - + &Quit &Излаз @@ -223,12 +223,12 @@ Press Space to open the side panel. CopyTool - + Copy Запамти - + Copy the selection into the clipboard Копира избор у привремену оставу @@ -236,7 +236,7 @@ Press Space to open the side panel. DBusUtils - + Unable to connect via DBus Нисам успео да се повежем кроз DBus @@ -244,12 +244,12 @@ Press Space to open the side panel. ExitTool - + Exit Излаз - + Leave the capture screen Напусти екран за снимање @@ -257,47 +257,47 @@ Press Space to open the side panel. FileNameEditor - + Edit the name of your captures: Уређивање имена снимака: - + Edit: Уређивање: - + Preview: Преглед: - + Save Сачувај - + Saves the pattern Сачувај шаблон - + Reset Ресетуј - + Restores the saved pattern Поврати сачувани шаблон - + Clear Очисти - + Deletes the name Брише име @@ -305,112 +305,112 @@ Press Space to open the side panel. GeneneralConf - - + + Import Увоз - - - + + + Error Грешка - + Unable to read file. Нисам успео да прочитам датотеку. - - + + Unable to write file. Нисам успео да сачувам датотеку. - + Save File Сачувај датотеку - + Confirm Reset Потврда поништавања - + Are you sure you want to reset the configuration? Да ли сте сигурни да желите да поништите сва прилагођена подешавања? - + Show help message Приказуј поруку са упутством - + Show the help message at the beginning in the capture mode. Приказуј поруку са кратким упутством на почетку снимања екрана. - - + + Show desktop notifications Користи системска обавештења - + Show tray icon Иконица на системској полици - + Show the systemtray icon Приказуј иконицу на системској полици - + Configuration File Датотека са подешавањима - + Export Извоз - + Reset Поништи - + Launch at startup Покрени на почетку - + Launch Flameshot Покрени Flameshot - + Close after capture - + Close after taking a screenshot - + Copy URL after upload - + Copy URL and close window after upload @@ -418,48 +418,48 @@ Press Space to open the side panel. ImgurUploader - + Upload to Imgur Објави на Imgur - + Uploading Image Објављујем слику - + Copy URL Запамти интернет адресу - + Open URL Посети интернет адресу - + Delete image Избриши слику - + Image to Clipboard. Сачувај у привремену меморију. - - + + Unable to open the URL. Нисам успео да посетим интернет адресу. - + URL copied to clipboard. Интернет адреса је сачувана у привременој меморији. - + Screenshot copied to clipboard. Слика је сачувана у привременој меморији. @@ -467,12 +467,12 @@ Press Space to open the side panel. ImgurUploaderTool - + Image Uploader Објављивање слике - + Upload the selection to Imgur Објави избор на Imgur сајту @@ -480,7 +480,7 @@ Press Space to open the side panel. InfoWindow - + About О програму @@ -500,77 +500,77 @@ Press Space to open the side panel. Точкић миша - + Move selection 1px Помери избор за 1px - + Resize selection 1px Увећај избор за 1px - + Quit capture Излаз из снимача екрана - + Copy to clipboard Запамти у привременој меморији - + Save selection as a file Сачувај избор у датотеку - + Undo the last modification Поништи последње измене - + Toggle visibility of sidebar with options of the selected tool - + Show color picker Прикажи избор боје - + Change the tool's thickness Измени дебљину линије алата - + Available shortcuts in the screen capture mode. Доступне пречице у моду снимка екрана. - + Key Тастер - + Description Опис - + <u><b>License</b></u> <u><b>Лиценца</b></u> - + <u><b>Version</b></u> <u><b>Верзија</b></u> - + <u><b>Shortcuts</b></u> <u><b>Пречице</b></u> @@ -578,12 +578,12 @@ Press Space to open the side panel. LineTool - + Line Линија - + Set the Line as the paint tool Избор цртања линије @@ -591,12 +591,12 @@ Press Space to open the side panel. MarkerTool - + Marker Маркер - + Set the Marker as the paint tool Избор цртања маркером @@ -604,12 +604,12 @@ Press Space to open the side panel. MoveTool - + Move Премештање - + Move the selection area Премешта изабрану област @@ -617,12 +617,12 @@ Press Space to open the side panel. PencilTool - + Pencil Оловка - + Set the Pencil as the paint tool Избор цртања оловком @@ -630,12 +630,12 @@ Press Space to open the side panel. PinTool - + Pin Tool Закачка - + Pin image on the desktop Закачи слику за радну површину @@ -643,13 +643,13 @@ Press Space to open the side panel. QObject - + Save Error Грешка приликом упусивања - + Capture saved as Сачувај снимак као @@ -660,31 +660,31 @@ Press Space to open the side panel. - + Error trying to save as Грешка приликом уписивања као - - - - + + + + Unable to connect via DBus Нисам успео да се повежем кроз DBus - + Error Грешка - + Unable to write in Нисам успео са сачувам - + URL copied to clipboard. Интернет адреса је сачувана у привременој меморији. @@ -692,12 +692,12 @@ Press Space to open the side panel. RectangleTool - + Rectangle Правоугаоник - + Set the Rectangle as the paint tool Избор цртања обојеног правоугаоника @@ -705,12 +705,12 @@ Press Space to open the side panel. RedoTool - + Redo Понови - + Redo the next modification Понови поништену измену @@ -718,13 +718,13 @@ Press Space to open the side panel. SaveTool - + Save Сачувај Сохранить - + Save the capture Сачувај снимак @@ -732,7 +732,7 @@ Press Space to open the side panel. ScreenGrabber - + Unable to capture screen Нисам успео да снимим екран @@ -740,12 +740,12 @@ Press Space to open the side panel. SelectionTool - + Rectangular Selection Правоугаони оквир - + Set Selection as the paint tool Избор цртања правоугаоног оквира @@ -753,22 +753,22 @@ Press Space to open the side panel. SidePanelWidget - + Active thickness: - + Active color: Активна боја: - + Press ESC to cancel Притисните ESC за прекид - + Grab Color Преузмите боју @@ -776,12 +776,12 @@ Press Space to open the side panel. SizeIndicatorTool - + Selection Size Indicator Приказ величине избора - + Show the dimensions of the selection (X Y) Приказује величину избора (X Y) @@ -789,107 +789,107 @@ Press Space to open the side panel. StrftimeChooserWidget - + Century (00-99) Век (00-99) - + Year (00-99) Година (00-99) - + Year (2000) Година (2000) - + Month Name (jan) Име месеца (јан) - + Month Name (january) Име месеца (јануар) - + Month (01-12) Месец (01-12) - + Week Day (1-7) Дани у недељи (1-7) - + Week (01-53) Недеља (01-53) - + Day Name (mon) Дан у недељи (пон) - + Day Name (monday) Дан у недељи (понедељак) - + Day (01-31) Дан (01-31) - + Day of Month (1-31) Дан месеца (1-31) - + Day (001-366) Дан (001-366) - + Time (%H-%M-%S) Време (%H-%M-%S) - + Time (%H-%M) Време (%H-%M) - + Hour (00-23) Сат (00-23) - + Hour (01-12) Сат (01-12) - + Minute (00-59) Минута (00-59) - + Second (00-59) Секунда (00-59) - + Full Date (%m/%d/%y) Комплетан датум (%m/%d/%y) - + Full Date (%Y-%m-%d) Комплетан датум (%Y-%m-%d) @@ -897,7 +897,7 @@ Press Space to open the side panel. SystemNotification - + Flameshot Info Информације о Flameshot-у @@ -905,22 +905,22 @@ Press Space to open the side panel. TextConfig - + StrikeOut Прецртано - + Underline Подвучено - + Bold Задебљано - + Italic Накошено @@ -928,12 +928,12 @@ Press Space to open the side panel. TextTool - + Text Текст - + Add text to your capture Додаје текст на снимак @@ -941,37 +941,37 @@ Press Space to open the side panel. UIcolorEditor - + UI Color Editor Уређивање боје сучеља - + Change the color moving the selectors and see the changes in the preview buttons. Измените боју померањем изборника и видите резултат у прегледу дугмића. - + Select a Button to modify it Изаберите дугме да би га изменили - + Main Color Основна боја - + Click on this button to set the edition mode of the main color. Кликните на дугме да би прешли у режим уређивања основне боје. - + Contrast Color Боја контраста - + Click on this button to set the edition mode of the contrast color. Кликните на дугме да би прешли у режим уређивања боје контраста. @@ -979,12 +979,12 @@ Press Space to open the side panel. UndoTool - + Undo Поништи - + Undo the last modification Поништи последњу измену @@ -992,17 +992,17 @@ Press Space to open the side panel. VisualsEditor - + Opacity of area outside selection: Провидност подручја ван избора: - + Button Selection Избор дугмића - + Select All Изабери све diff --git a/data/translations/Internationalization_tr.ts b/data/translations/Internationalization_tr.ts index 01b0aeab..195fea82 100644 --- a/data/translations/Internationalization_tr.ts +++ b/data/translations/Internationalization_tr.ts @@ -4,12 +4,12 @@ AppLauncher - + App Launcher Uygulama Başlatıcı - + Choose an app to open the capture Yakalamayı açmak için bir uygulama seçin @@ -32,18 +32,18 @@ Seçimden sonra açık tutun - - + + Error Hata - + Unable to write in Yazma mümkün değil - + Unable to launch in terminal. Terminalde başlatılamadı. @@ -51,12 +51,12 @@ ArrowTool - + Arrow Ok - + Set the Arrow as the paint tool Oku çizim aracı olarak ayarlar @@ -64,12 +64,12 @@ BlurTool - + Blur Bulanıklık - + Set Blur as the paint tool Bulnıklığı boyama aracı olarak ayarlar @@ -77,47 +77,47 @@ CaptureLauncher - + <b>Capture Mode</b> - + Rectangular Region - + Full Screen (All Monitors) - + No Delay - + second - + seconds - + Take new screenshot - + Area: - + Delay: @@ -125,12 +125,12 @@ CaptureWidget - + Unable to capture screen Ekran resmi alınamadı - + Select an area with the mouse, or press Esc to exit. Press Enter to capture the screen. Press Right Click to show the color picker. @@ -146,12 +146,12 @@ Yan paneli açmak için Boşluk tuşuna basın. CircleCountTool - + Circle Counter - + Add an autoincrementing counter bubble @@ -159,12 +159,12 @@ Yan paneli açmak için Boşluk tuşuna basın. CircleTool - + Circle Çember - + Set the Circle as the paint tool Çemberi boyama aracı olarak ayarlar @@ -172,7 +172,7 @@ Yan paneli açmak için Boşluk tuşuna basın. ConfigWindow - + Configuration Ayarlar @@ -182,7 +182,7 @@ Yan paneli açmak için Boşluk tuşuna basın. Arayüz - + Filename Editor Dosya Adı Düzenleyici @@ -195,27 +195,27 @@ Yan paneli açmak için Boşluk tuşuna basın. Controller - + &Take Screenshot &Ekran Resmi Al - + &Open Launcher - + &Configuration &Ayarlar - + &Information &Bilgi - + &Quit &Çıkış @@ -223,12 +223,12 @@ Yan paneli açmak için Boşluk tuşuna basın. CopyTool - + Copy Kopyala - + Copy the selection into the clipboard Seçimi panoya kopyalar @@ -236,7 +236,7 @@ Yan paneli açmak için Boşluk tuşuna basın. DBusUtils - + Unable to connect via DBus DBus ile bağlanılamadı @@ -244,12 +244,12 @@ Yan paneli açmak için Boşluk tuşuna basın. ExitTool - + Exit Çıkış - + Leave the capture screen Yakalama ekranından ayrıl @@ -257,47 +257,47 @@ Yan paneli açmak için Boşluk tuşuna basın. FileNameEditor - + Edit the name of your captures: Çekimlerinizin adını düzenleyin: - + Edit: Düzenle: - + Preview: Önizleme: - + Save Kaydet - + Saves the pattern Desenini kaydeder - + Reset Sıfırla - + Restores the saved pattern Kaydedilen deseni geri yükler - + Clear Temizle - + Deletes the name İsmi siler @@ -305,112 +305,112 @@ Yan paneli açmak için Boşluk tuşuna basın. GeneneralConf - - + + Import Dışa aktar - - - + + + Error Hata - + Unable to read file. Dosya okunamıyor. - - + + Unable to write file. Dosya yazılamıyor. - + Save File Dosyayı Kaydet - + Confirm Reset Sıfırlamayı Onayla - + Are you sure you want to reset the configuration? Ayarları sıfırlamak istediğinizden emin misiniz? - + Show help message Yardım mesajını göster - + Show the help message at the beginning in the capture mode. Yakalama modunda başında yardım mesajını gösterin. - - + + Show desktop notifications Masaüstü bildirimlerini göster - + Show tray icon Tepsi simgesini göster - + Show the systemtray icon Sistem tepsisi simgesini göster - + Configuration File Yapılandırma Dosyası - + Export Dışa aktar - + Reset Sıfırla - + Launch at startup Başlangıçta başlatın - + Launch Flameshot Flameshot'ı başlat - + Close after capture - + Close after taking a screenshot - + Copy URL after upload - + Copy URL and close window after upload @@ -418,48 +418,48 @@ Yan paneli açmak için Boşluk tuşuna basın. ImgurUploader - + Upload to Imgur Imgur'a yükle - + Uploading Image Resim Yükleniyor - + Copy URL URL Kopyala - + Open URL URL Aç - + Delete image Resmi sil - + Image to Clipboard. Resim Pano'ya. - - + + Unable to open the URL. URL açılamıyor. - + URL copied to clipboard. URL panoya kopyalandı. - + Screenshot copied to clipboard. Ekran görüntüsü panoya kopyalandı. @@ -467,12 +467,12 @@ Yan paneli açmak için Boşluk tuşuna basın. ImgurUploaderTool - + Image Uploader Resim Yükleme Aracı - + Upload the selection to Imgur Seçimi Imgur'a yükler @@ -480,7 +480,7 @@ Yan paneli açmak için Boşluk tuşuna basın. InfoWindow - + About Hakkında @@ -500,77 +500,77 @@ Yan paneli açmak için Boşluk tuşuna basın. Fare Tekerleği - + Move selection 1px 1px seçimini hareket ettir - + Resize selection 1px 1px seçimini yeniden boyutlandır - + Quit capture Çıkış - + Copy to clipboard Panoya kopyala - + Save selection as a file Seçimi dosya olarak kaydet - + Undo the last modification Son değişikliği geri al - + Toggle visibility of sidebar with options of the selected tool - + Show color picker Renk seçici göster - + Change the tool's thickness Araç kalınlığını değiştirin - + Available shortcuts in the screen capture mode. Ekran yakalama modunda kullanılabilir kısayollar. - + Key Anahtar - + Description Tanım - + <u><b>License</b></u> <u><b>Lisans</b></u> - + <u><b>Version</b></u> <u><b>Sürüm</b></u> - + <u><b>Shortcuts</b></u> <u><b>Kısayollar</b></u> @@ -578,12 +578,12 @@ Yan paneli açmak için Boşluk tuşuna basın. LineTool - + Line Çizgi - + Set the Line as the paint tool Çizgiyi boyama aracı olarak ayarlar @@ -591,12 +591,12 @@ Yan paneli açmak için Boşluk tuşuna basın. MarkerTool - + Marker İşaretleyici - + Set the Marker as the paint tool İşaretleyiciyi boyama aracı olarak ayarlar @@ -604,12 +604,12 @@ Yan paneli açmak için Boşluk tuşuna basın. MoveTool - + Move Oynat - + Move the selection area Seçim alanını hareket ettir @@ -617,12 +617,12 @@ Yan paneli açmak için Boşluk tuşuna basın. PencilTool - + Pencil Kurşun Kalem - + Set the Pencil as the paint tool Kurşun Kalemi çizim aracı olarak ayarlar @@ -630,12 +630,12 @@ Yan paneli açmak için Boşluk tuşuna basın. PinTool - + Pin Tool Pin Aracı - + Pin image on the desktop Masaüstündeki PIN resmi @@ -643,13 +643,13 @@ Yan paneli açmak için Boşluk tuşuna basın. QObject - + Save Error Kaydetme Hatası - + Capture saved as Yakalama farklı kaydedildi @@ -660,31 +660,31 @@ Yan paneli açmak için Boşluk tuşuna basın. - + Error trying to save as Farklı kaydetmeye çalışılırken hata oluştu - - - - + + + + Unable to connect via DBus DBus ile bağlanılamadı - + Error Hata - + Unable to write in Yazma mümkün değil - + URL copied to clipboard. URL panoya kopyalandı. @@ -692,12 +692,12 @@ Yan paneli açmak için Boşluk tuşuna basın. RectangleTool - + Rectangle Dikdörtgen - + Set the Rectangle as the paint tool Dikdörtgeni boyama aracı olarak ayarlar @@ -705,12 +705,12 @@ Yan paneli açmak için Boşluk tuşuna basın. RedoTool - + Redo Yeniden - + Redo the next modification @@ -718,12 +718,12 @@ Yan paneli açmak için Boşluk tuşuna basın. SaveTool - + Save Kaydet - + Save the capture Yakalamayı kaydet @@ -731,7 +731,7 @@ Yan paneli açmak için Boşluk tuşuna basın. ScreenGrabber - + Unable to capture screen Ekran resmi alınamadı @@ -739,12 +739,12 @@ Yan paneli açmak için Boşluk tuşuna basın. SelectionTool - + Rectangular Selection Dikdörtgen Seçim - + Set Selection as the paint tool Seçimi boyama aracı olarak ayarlar @@ -752,22 +752,22 @@ Yan paneli açmak için Boşluk tuşuna basın. SidePanelWidget - + Active thickness: - + Active color: Aktif Renk: - + Press ESC to cancel Çıkmak için ESC'ye tıklayın - + Grab Color @@ -775,12 +775,12 @@ Yan paneli açmak için Boşluk tuşuna basın. SizeIndicatorTool - + Selection Size Indicator Seçim Boyutu Göstergesi - + Show the dimensions of the selection (X Y) Seçimin boyutlarını gösterir (X Y) @@ -788,107 +788,107 @@ Yan paneli açmak için Boşluk tuşuna basın. StrftimeChooserWidget - + Century (00-99) Ülke (00-99) - + Year (00-99) Yıl (00-99) - + Year (2000) Yıl (2000) - + Month Name (jan) Ay Adı (Oca) - + Month Name (january) Ay Adı (Ocak) - + Month (01-12) Ay (01-12) - + Week Day (1-7) Haftanın Günü (1-7) - + Week (01-53) Hafta (01-53) - + Day Name (mon) Gün Adı (pzt) - + Day Name (monday) Gün Adı (pazartesi) - + Day (01-31) Gün (01-31) - + Day of Month (1-31) Ayın Günü (1-31) - + Day (001-366) Gün (001-366) - + Time (%H-%M-%S) - + Time (%H-%M) - + Hour (00-23) Saat (00-23) - + Hour (01-12) Saat (01-12) - + Minute (00-59) Dakika (00-59) - + Second (00-59) Saniye (00-59) - + Full Date (%m/%d/%y) Tam Tarih (%d/%m/%y) - + Full Date (%Y-%m-%d) Tam Tarih (%d-%m-%Y) @@ -896,7 +896,7 @@ Yan paneli açmak için Boşluk tuşuna basın. SystemNotification - + Flameshot Info Flameshot Hakkında @@ -904,22 +904,22 @@ Yan paneli açmak için Boşluk tuşuna basın. TextConfig - + StrikeOut - + Underline Altçizgi - + Bold Kalın - + Italic Eğik @@ -927,12 +927,12 @@ Yan paneli açmak için Boşluk tuşuna basın. TextTool - + Text Metin - + Add text to your capture Bilgisayardan yazı ekle @@ -940,37 +940,37 @@ Yan paneli açmak için Boşluk tuşuna basın. UIcolorEditor - + UI Color Editor UI Renk Editörü - + Change the color moving the selectors and see the changes in the preview buttons. Seçicileri hareket ettiren rengi değiştirin ve önizleme düğmelerindeki değişiklikleri görün. - + Select a Button to modify it Değiştirmek için bir buton seçin - + Main Color Ana Renk - + Click on this button to set the edition mode of the main color. Ana rengin baskı modunu ayarlamak için bu butonu tıklayın. - + Contrast Color Kontrast Renk - + Click on this button to set the edition mode of the contrast color. Kontrast renginin baskı modunu ayarlamak için bu butonu tıklayın. @@ -978,12 +978,12 @@ Yan paneli açmak için Boşluk tuşuna basın. UndoTool - + Undo Geri - + Undo the last modification Son değişikliği geri al @@ -991,17 +991,17 @@ Yan paneli açmak için Boşluk tuşuna basın. VisualsEditor - + Opacity of area outside selection: Seçimin dışındaki alanın opaklığı: - + Button Selection Buton Seçimi - + Select All Tümünü Seç diff --git a/data/translations/Internationalization_uk.ts b/data/translations/Internationalization_uk.ts index 1211a83a..c8f1801d 100644 --- a/data/translations/Internationalization_uk.ts +++ b/data/translations/Internationalization_uk.ts @@ -4,12 +4,12 @@ AppLauncher - + App Launcher Запуск програми - + Choose an app to open the capture Виберіть програму, щоб відкрити знімок @@ -32,18 +32,18 @@ Не закривати після вибору - - + + Error Помилка - + Unable to write in Не вдалось записати - + Unable to launch in terminal. Не вдалось запустити у терміналі. @@ -51,12 +51,12 @@ ArrowTool - + Arrow Стрілка - + Set the Arrow as the paint tool Вибрати стрілку інструментом малювання @@ -64,12 +64,12 @@ BlurTool - + Blur Розмиття - + Set Blur as the paint tool Вибрати розмиття інструментом малювання @@ -77,47 +77,47 @@ CaptureLauncher - + <b>Capture Mode</b> - + Rectangular Region - + Full Screen (All Monitors) - + No Delay - + second - + seconds - + Take new screenshot - + Area: - + Delay: @@ -125,12 +125,12 @@ CaptureWidget - + Unable to capture screen Не вдалось захопити екран - + Select an area with the mouse, or press Esc to exit. Press Enter to capture the screen. Press Right Click to show the color picker. @@ -146,12 +146,12 @@ Press Space to open the side panel. CircleCountTool - + Circle Counter - + Add an autoincrementing counter bubble @@ -159,12 +159,12 @@ Press Space to open the side panel. CircleTool - + Circle Коло - + Set the Circle as the paint tool Вибрати коло інструментом малювання @@ -172,7 +172,7 @@ Press Space to open the side panel. ConfigWindow - + Configuration Налаштування @@ -182,7 +182,7 @@ Press Space to open the side panel. Інтерфейс - + Filename Editor Редактор імені файлів @@ -195,27 +195,27 @@ Press Space to open the side panel. Controller - + &Take Screenshot &Зробити знімок - + &Open Launcher - + &Configuration &Налаштування - + &Information &Інформація - + &Quit Ви&йти @@ -223,12 +223,12 @@ Press Space to open the side panel. CopyTool - + Copy Копіювати - + Copy the selection into the clipboard Копіювати вибране до буферу обміну @@ -236,7 +236,7 @@ Press Space to open the side panel. DBusUtils - + Unable to connect via DBus Не вдалось підключитись через DBus @@ -244,12 +244,12 @@ Press Space to open the side panel. ExitTool - + Exit Вийти - + Leave the capture screen Вийти із захоплення екрану @@ -257,47 +257,47 @@ Press Space to open the side panel. FileNameEditor - + Edit the name of your captures: Відредагуйте ім'я ваших знімків: - + Edit: Шаблон: - + Preview: Перегляд: - + Save Зберегти - + Saves the pattern Зберегти шаблон - + Reset Скинути - + Restores the saved pattern Відновлює збережений шаблон - + Clear Очистити - + Deletes the name Видаляє ім'я @@ -305,112 +305,112 @@ Press Space to open the side panel. GeneneralConf - - + + Import Імпорт - - - + + + Error Помилка - + Unable to read file. Не вдалось прочитати файл. - - + + Unable to write file. Не вдалось записати файл. - + Save File Зберегти файл - + Confirm Reset Підтвердити скидання - + Are you sure you want to reset the configuration? Ви дійсно хочете скинути налаштування? - + Show help message Показувати повідомлення довідки - + Show the help message at the beginning in the capture mode. Показувати повідомлення довідки на початку режиму захоплення. - - + + Show desktop notifications Показувати повідомлення - + Show tray icon Показувати значок на панелі - + Show the systemtray icon Показувати значок на панелі повідомленнь - + Configuration File Файл налаштувань - + Export Експорт - + Reset Скинути - + Launch at startup Запускати при старті системи - + Launch Flameshot Запускати Flameshot - + Close after capture - + Close after taking a screenshot - + Copy URL after upload - + Copy URL and close window after upload @@ -418,48 +418,48 @@ Press Space to open the side panel. ImgurUploader - + Upload to Imgur Вивантажити до Imgur - + Uploading Image Вивантаження зображення - + Copy URL Скопіювати URL - + Open URL Відкрити URL - + Delete image Видалити зображення - + Image to Clipboard. Зображення до буферу обміну. - - + + Unable to open the URL. Не вдалось відкрити URL. - + URL copied to clipboard. URL скопійовано до буферу обміну. - + Screenshot copied to clipboard. Знімок скопійовано до буферу обміну. @@ -467,12 +467,12 @@ Press Space to open the side panel. ImgurUploaderTool - + Image Uploader Вивантаження зображень - + Upload the selection to Imgur Вивантажити вибране до Imgur @@ -480,7 +480,7 @@ Press Space to open the side panel. InfoWindow - + About Про... @@ -500,77 +500,77 @@ Press Space to open the side panel. Колесо миші - + Move selection 1px Перемістити виділення на 1px - + Resize selection 1px Змінити розмір виділення на 1px - + Quit capture Вийти із захоплення екрану - + Copy to clipboard Копіювати до буферу обміну - + Save selection as a file Зберегти вибране до файлу - + Undo the last modification Скасувати останню зміну - + Toggle visibility of sidebar with options of the selected tool Переключити видимість бічної панелі - + Show color picker Показати вибір кольору - + Change the tool's thickness Змінити товщину інструменту - + Available shortcuts in the screen capture mode. Доступні комбінації клавіш у режимі захоплення екрану. - + Key Клавіша - + Description Опис - + <u><b>License</b></u> <u><b>Ліцензія</b></u> - + <u><b>Version</b></u> <u><b>Версія</b></u> - + <u><b>Shortcuts</b></u> <u><b>Комбінації клавіш</b></u> @@ -578,12 +578,12 @@ Press Space to open the side panel. LineTool - + Line Лінія - + Set the Line as the paint tool Вибрати лінію інструментом малювання @@ -591,12 +591,12 @@ Press Space to open the side panel. MarkerTool - + Marker Маркер - + Set the Marker as the paint tool Вибрати маркер інструментом малювання @@ -604,12 +604,12 @@ Press Space to open the side panel. MoveTool - + Move Переміщення - + Move the selection area Перемістити вибір @@ -617,12 +617,12 @@ Press Space to open the side panel. PencilTool - + Pencil Олівець - + Set the Pencil as the paint tool Вибрати олівець інструментом малювання @@ -630,12 +630,12 @@ Press Space to open the side panel. PinTool - + Pin Tool Прикріплення - + Pin image on the desktop Прикріпити зображення до робочого столу @@ -643,13 +643,13 @@ Press Space to open the side panel. QObject - + Save Error Помилка збереження - + Capture saved as Знімок збережено як @@ -660,31 +660,31 @@ Press Space to open the side panel. - + Error trying to save as Помилка під час збереження як - - - - + + + + Unable to connect via DBus Не вдалось підключитись через DBus - + Error Помилка - + Unable to write in Не вдалось зберегти - + URL copied to clipboard. URL скопійовано до буферу обміну. @@ -692,12 +692,12 @@ Press Space to open the side panel. RectangleTool - + Rectangle Прямокутник - + Set the Rectangle as the paint tool Вибрати прямокутник інструментом малювання @@ -705,12 +705,12 @@ Press Space to open the side panel. RedoTool - + Redo Повторити - + Redo the next modification Повторити наступну зміну @@ -718,12 +718,12 @@ Press Space to open the side panel. SaveTool - + Save Зберегти - + Save the capture Зберегти знімок @@ -731,7 +731,7 @@ Press Space to open the side panel. ScreenGrabber - + Unable to capture screen Не вдалось захопити екран @@ -739,12 +739,12 @@ Press Space to open the side panel. SelectionTool - + Rectangular Selection Прямокутне виділення - + Set Selection as the paint tool Вибрати прямокутне виділення інструментом малювання @@ -752,22 +752,22 @@ Press Space to open the side panel. SidePanelWidget - + Active thickness: Активна товщина: - + Active color: Активний колір: - + Press ESC to cancel Натисніть Esc для скасування - + Grab Color Визначити колір з екрану @@ -775,12 +775,12 @@ Press Space to open the side panel. SizeIndicatorTool - + Selection Size Indicator Індикатор розміру виділення - + Show the dimensions of the selection (X Y) Показує розмір виділення (X Y) @@ -788,107 +788,107 @@ Press Space to open the side panel. StrftimeChooserWidget - + Century (00-99) Століття (00-99) - + Year (00-99) Рік (00-99) - + Year (2000) Рік (2000) - + Month Name (jan) Назва місяця (січ) - + Month Name (january) Назва місяця (січень) - + Month (01-12) Місяць (01-12) - + Week Day (1-7) День тижня (1-7) - + Week (01-53) Тиждень (01-53) - + Day Name (mon) Назва дня тижня (пн) - + Day Name (monday) Назва дня тижня (понеділок) - + Day (01-31) День (01-31) - + Day of Month (1-31) День місяця (1-31) - + Day (001-366) День (001-366) - + Time (%H-%M-%S) Час (%H-%M-%S) - + Time (%H-%M) Час (%H-%M) - + Hour (00-23) Година (00-23) - + Hour (01-12) Година (01-12) - + Minute (00-59) Хвилина (00-59) - + Second (00-59) Секунда (00-59) - + Full Date (%m/%d/%y) Повна дата (%m/%d/%y) - + Full Date (%Y-%m-%d) Повна дата (%Y-%m-%d) @@ -896,7 +896,7 @@ Press Space to open the side panel. SystemNotification - + Flameshot Info Довідка Flameshot @@ -904,22 +904,22 @@ Press Space to open the side panel. TextConfig - + StrikeOut Перекреслення - + Underline Підкреслення - + Bold Жирний - + Italic Курсив @@ -927,12 +927,12 @@ Press Space to open the side panel. TextTool - + Text Текст - + Add text to your capture Додати текст на знімок @@ -940,37 +940,37 @@ Press Space to open the side panel. UIcolorEditor - + UI Color Editor Редактор кольору інтерфейсу - + Change the color moving the selectors and see the changes in the preview buttons. Змініть колір пересуваючи виділення та перегляньте зміни у кнопках перегляду. - + Select a Button to modify it Виберіть кнопку, щоб змінити її - + Main Color Основний колір - + Click on this button to set the edition mode of the main color. Натисніть на цю кнопку, щоб включити режим редагування основного кольору. - + Contrast Color Контрасний колір - + Click on this button to set the edition mode of the contrast color. Натисніть на цю кнопку, щоб включити режим редагування контрасного кольору. @@ -978,12 +978,12 @@ Press Space to open the side panel. UndoTool - + Undo Скасувати - + Undo the last modification Скасувати останню зміну @@ -991,17 +991,17 @@ Press Space to open the side panel. VisualsEditor - + Opacity of area outside selection: Нерозорість області за межами вибору: - + Button Selection Вибір кнопок - + Select All Вибрати все diff --git a/data/translations/Internationalization_zh_CN.ts b/data/translations/Internationalization_zh_CN.ts index 7a9e476a..d79fb15a 100644 --- a/data/translations/Internationalization_zh_CN.ts +++ b/data/translations/Internationalization_zh_CN.ts @@ -4,12 +4,12 @@ AppLauncher - + App Launcher 应用启动器 - + Choose an app to open the capture 选择一个应用打开此截图 @@ -32,18 +32,18 @@ 选择后保持此窗口打开 - - + + Error 错误 - + Unable to launch in terminal. 无法在终端中启动。 - + Unable to write in 无法写入 @@ -51,12 +51,12 @@ ArrowTool - + Arrow 箭头 - + Set the Arrow as the paint tool 选择箭头作为绘画工具 @@ -64,12 +64,12 @@ BlurTool - + Blur 模糊 - + Set Blur as the paint tool 选择模糊作为绘画工具 @@ -77,47 +77,47 @@ CaptureLauncher - + <b>Capture Mode</b> <b>捕获模式</b> - + Rectangular Region 方形区域 - + Full Screen (All Monitors) 全屏(所有显示器) - + No Delay 无延迟 - + second - + seconds - + Take new screenshot 获取新屏幕截图 - + Area: 区域: - + Delay: 延迟: @@ -125,13 +125,13 @@ CaptureWidget - + Unable to capture screen 无法捕获屏幕 无法捕获屏幕 - + Select an area with the mouse, or press Esc to exit. Press Enter to capture the screen. Press Right Click to show the color picker. @@ -147,12 +147,12 @@ Press Space to open the side panel. CircleCountTool - + Circle Counter - + Add an autoincrementing counter bubble @@ -160,12 +160,12 @@ Press Space to open the side panel. CircleTool - + Circle 圆环 - + Set the Circle as the paint tool 选择圆环作为绘画工具 @@ -173,7 +173,7 @@ Press Space to open the side panel. ConfigWindow - + Configuration 配置 @@ -183,7 +183,7 @@ Press Space to open the side panel. 界面 - + Filename Editor 文件名编辑器 @@ -196,27 +196,27 @@ Press Space to open the side panel. Controller - + &Take Screenshot 进行截图(&T) - + &Open Launcher 打开启动器(&O) - + &Configuration 配置(&C) - + &Information 信息(&I) - + &Quit 退出(&Q) @@ -224,12 +224,12 @@ Press Space to open the side panel. CopyTool - + Copy 复制 - + Copy the selection into the clipboard 复制选择到剪贴板 @@ -237,7 +237,7 @@ Press Space to open the side panel. DBusUtils - + Unable to connect via DBus 无法通过 DBus 进行连接 @@ -245,12 +245,12 @@ Press Space to open the side panel. ExitTool - + Exit 退出 - + Leave the capture screen 离开屏幕捕获 @@ -258,47 +258,47 @@ Press Space to open the side panel. FileNameEditor - + Edit the name of your captures: 编辑您的截图名称: - + Edit: 编辑器: - + Preview: 预览: - + Save 保存 - + Saves the pattern 保存样式 - + Reset 恢复 - + Restores the saved pattern 恢复保存的样式 - + Clear 清空 - + Deletes the name 删除这个名字 @@ -306,112 +306,112 @@ Press Space to open the side panel. GeneneralConf - + Show help message 显示帮助文档 - + Show the help message at the beginning in the capture mode. 在捕获之前显示帮助信息。 - - + + Show desktop notifications 显示桌面通知 - + Show tray icon 显示托盘图标 - + Show the systemtray icon 显示任务栏图标 - - + + Import 导入 - - - + + + Error 错误 - + Unable to read file. 无法读取文件。 - - + + Unable to write file. 无法写入文件。 - + Save File 保存到文件 - + Confirm Reset 确定重置 - + Are you sure you want to reset the configuration? 你确定你想要重置配置? - + Configuration File 配置文件 - + Export 导出 - + Reset 重置 - + Launch at startup 开机时启动 - + Launch Flameshot 启动 Flameshot - + Close after capture 捕获后关闭 - + Close after taking a screenshot 获取屏幕截图后关闭 - + Copy URL after upload - + Copy URL and close window after upload @@ -419,48 +419,48 @@ Press Space to open the side panel. ImgurUploader - + Upload to Imgur 上传到Imgur - + Uploading Image 正在上传 - + Copy URL 复制链接 - + Open URL 打开链接 - + Delete image 删除图像 - + Image to Clipboard. 保存文件到剪贴板。 - - + + Unable to open the URL. 无法打开此链接。 - + URL copied to clipboard. 复制链接到剪贴板。 - + Screenshot copied to clipboard. 截图复制到剪贴板。 @@ -468,12 +468,12 @@ Press Space to open the side panel. ImgurUploaderTool - + Image Uploader 上传图片 - + Upload the selection to Imgur 上传选择到 Imgur @@ -481,7 +481,7 @@ Press Space to open the side panel. InfoWindow - + About 关于 @@ -501,77 +501,77 @@ Press Space to open the side panel. 鼠标滑轮 - + Move selection 1px 移动选择 1 px - + Resize selection 1px 调整选择大小 1 px - + Quit capture 退出捕获 - + Copy to clipboard 复制到剪贴板 - + Save selection as a file 将选择保存为文件 - + Undo the last modification 撤消上次修改 - + Toggle visibility of sidebar with options of the selected tool 切换侧边栏可见性 - + Show color picker 显示颜色选择器 - + Change the tool's thickness 改变工具的厚度 - + Key - + Description 描述 - + <u><b>License</b></u> <u><b>许可证</b></u> - + <u><b>Version</b></u> <u><b>版本</b></u> - + <u><b>Shortcuts</b></u> <u><b>快捷键</b></u> - + Available shortcuts in the screen capture mode. 屏幕捕捉模式中的可用快捷键。 @@ -579,12 +579,12 @@ Press Space to open the side panel. LineTool - + Line 直线 - + Set the Line as the paint tool 将直线线设置为绘画工具 @@ -592,12 +592,12 @@ Press Space to open the side panel. MarkerTool - + Marker 标记 - + Set the Marker as the paint tool 将标记设置为绘画工具 @@ -605,12 +605,12 @@ Press Space to open the side panel. MoveTool - + Move 移动 - + Move the selection area 移动选择区域 @@ -618,12 +618,12 @@ Press Space to open the side panel. PencilTool - + Pencil 铅笔 - + Set the Pencil as the paint tool 将铅笔设置为绘画工具 @@ -631,12 +631,12 @@ Press Space to open the side panel. PinTool - + Pin Tool 贴图工具 - + Pin image on the desktop 在桌面上固定图像 @@ -644,13 +644,13 @@ Press Space to open the side panel. QObject - + Save Error 保存错误 - + Capture saved as 捕获已保存为 @@ -661,31 +661,31 @@ Press Space to open the side panel. - + Error trying to save as 尝试另存为时出错 - - - - + + + + Unable to connect via DBus 无法通过DBus进行连接 - + Error 错误 - + Unable to write in 无法写入 - + URL copied to clipboard. 复制链接到剪贴板。 @@ -693,12 +693,12 @@ Press Space to open the side panel. RectangleTool - + Rectangle 实心矩形 - + Set the Rectangle as the paint tool 将实心矩形设置为绘画工具 @@ -706,12 +706,12 @@ Press Space to open the side panel. RedoTool - + Redo 重做 - + Redo the next modification 重做上次修改 @@ -719,12 +719,12 @@ Press Space to open the side panel. SaveTool - + Save 保存 - + Save the capture 保存捕获 @@ -732,7 +732,7 @@ Press Space to open the side panel. ScreenGrabber - + Unable to capture screen 无法捕获屏幕 @@ -740,12 +740,12 @@ Press Space to open the side panel. SelectionTool - + Rectangular Selection 矩形选择 - + Set Selection as the paint tool 将矩形选择设置为绘画工具 @@ -753,22 +753,22 @@ Press Space to open the side panel. SidePanelWidget - + Active thickness: 当前宽度: - + Active color: 活动颜色: - + Press ESC to cancel 按下 ESC 键以取消 - + Grab Color 获取颜色 @@ -776,12 +776,12 @@ Press Space to open the side panel. SizeIndicatorTool - + Selection Size Indicator 选择尺寸指示 - + Show the dimensions of the selection (X Y) 显示选择的尺寸 (X Y) @@ -789,107 +789,107 @@ Press Space to open the side panel. StrftimeChooserWidget - + Century (00-99) 世纪(00-99) - + Year (00-99) 年(00-99) - + Year (2000) 年(2000) - + Month Name (jan) 月(1月 - 12月) - + Month Name (january) 月(一月 - 十二月) - + Month (01-12) 月 (01-12) - + Week Day (1-7) 周内的日(1-7) - + Week (01-53) 周(01-53) - + Day Name (mon) 星期(一 - 七) - + Day Name (monday) 星期(星期一 - 星期日) - + Day (01-31) 天(01-31) - + Day of Month (1-31) 一月中的某天(1-31) - + Day (001-366) 天(001-366) - + Time (%H-%M-%S) 时间(%H-%M-%S) - + Time (%H-%M) 时间(%H-%M) - + Hour (00-23) 小时(00-23) - + Hour (01-12) 小时(01-12) - + Minute (00-59) 分钟(00-59) - + Second (00-59) 秒(00-59) - + Full Date (%m/%d/%y) 完整日期(%m/%d/%y) - + Full Date (%Y-%m-%d) 完整日期(%Y-%m-%d) @@ -897,7 +897,7 @@ Press Space to open the side panel. SystemNotification - + Flameshot Info Flameshot 消息 @@ -905,22 +905,22 @@ Press Space to open the side panel. TextConfig - + StrikeOut 删除线 - + Underline 下划线 - + Bold 粗体 - + Italic 斜体 @@ -928,12 +928,12 @@ Press Space to open the side panel. TextTool - + Text 文本 - + Add text to your capture 在您的捕获中添加文本 @@ -941,37 +941,37 @@ Press Space to open the side panel. UIcolorEditor - + UI Color Editor 用户界面颜色编辑器 - + Change the color moving the selectors and see the changes in the preview buttons. 移动颜色选择并在预览按钮查看。 - + Select a Button to modify it 选择一个按钮以进行修改 - + Main Color 主色 - + Click on this button to set the edition mode of the main color. 点击按钮设置主色。 - + Contrast Color 对比色 - + Click on this button to set the edition mode of the contrast color. 点击按钮设置对比色。 @@ -979,12 +979,12 @@ Press Space to open the side panel. UndoTool - + Undo 撤消 - + Undo the last modification 撤消上次修改 @@ -992,17 +992,17 @@ Press Space to open the side panel. VisualsEditor - + Opacity of area outside selection: 选中区域之外的不透明度: - + Button Selection 按钮选择 - + Select All 全选 diff --git a/data/translations/Internationalization_zh_TW.ts b/data/translations/Internationalization_zh_TW.ts index b0c649a9..4e82b12a 100644 --- a/data/translations/Internationalization_zh_TW.ts +++ b/data/translations/Internationalization_zh_TW.ts @@ -4,12 +4,12 @@ AppLauncher - + App Launcher 應用程式啟動器 - + Choose an app to open the capture 選擇一個程式打開此截圖 @@ -32,18 +32,18 @@ 選擇後維持此視窗開啟 - - + + Error 錯誤 - + Unable to launch in terminal. 無法在終端機中啟動 - + Unable to write in 無法寫入 @@ -51,12 +51,12 @@ ArrowTool - + Arrow 箭頭 - + Set the Arrow as the paint tool 選擇箭頭作為繪製工具 @@ -64,12 +64,12 @@ BlurTool - + Blur 模糊 - + Set Blur as the paint tool 選擇模糊作為繪製工具 @@ -77,47 +77,47 @@ CaptureLauncher - + <b>Capture Mode</b> - + Rectangular Region - + Full Screen (All Monitors) - + No Delay - + second - + seconds - + Take new screenshot - + Area: - + Delay: @@ -125,12 +125,12 @@ CaptureWidget - + Unable to capture screen 無法擷取螢幕 - + Select an area with the mouse, or press Esc to exit. Press Enter to capture the screen. Press Right Click to show the color picker. @@ -142,12 +142,12 @@ Press Space to open the side panel. CircleCountTool - + Circle Counter - + Add an autoincrementing counter bubble @@ -155,12 +155,12 @@ Press Space to open the side panel. CircleTool - + Circle 圈型 - + Set the Circle as the paint tool 選擇圈型作為繪畫工具 @@ -168,7 +168,7 @@ Press Space to open the side panel. ConfigWindow - + Configuration 設定 @@ -178,7 +178,7 @@ Press Space to open the side panel. 介面 - + Filename Editor 檔案名稱編輯器 @@ -191,27 +191,27 @@ Press Space to open the side panel. Controller - + &Take Screenshot - + &Open Launcher - + &Configuration &設定 - + &Information &資訊 - + &Quit &結束 @@ -219,12 +219,12 @@ Press Space to open the side panel. CopyTool - + Copy 複製 - + Copy the selection into the clipboard @@ -232,7 +232,7 @@ Press Space to open the side panel. DBusUtils - + Unable to connect via DBus 無法透過 DBus 進行連接 @@ -240,12 +240,12 @@ Press Space to open the side panel. ExitTool - + Exit 離開 - + Leave the capture screen 離開螢幕擷取 @@ -253,47 +253,47 @@ Press Space to open the side panel. FileNameEditor - + Edit the name of your captures: 編輯您的截圖名稱: - + Edit: 編輯器: - + Preview: 預覽: - + Save 存檔 - + Saves the pattern 儲存樣式 - + Reset 重設 - + Restores the saved pattern 恢復儲存的樣式 - + Clear 清空 - + Deletes the name 刪除這個名稱 @@ -301,112 +301,112 @@ Press Space to open the side panel. GeneneralConf - + Show help message 顯示説明資訊 - + Show the help message at the beginning in the capture mode. 在擷取之前顯示説明資訊 - - + + Show desktop notifications 顯示桌面通知 - + Show tray icon 顯示託盤圖示 - + Show the systemtray icon 顯示工作列圖示 - - + + Import 匯入 - - - + + + Error 錯誤 - + Unable to read file. 無法讀取檔案 - - + + Unable to write file. 無法寫入檔案 - + Save File 存檔 - + Confirm Reset 確認重設 - + Are you sure you want to reset the configuration? 你確定你想要重設? - + Configuration File 設定檔 - + Export 匯出 - + Reset 重設 - + Launch at startup 自動啟動 - + Launch Flameshot - + Close after capture - + Close after taking a screenshot - + Copy URL after upload - + Copy URL and close window after upload @@ -414,48 +414,48 @@ Press Space to open the side panel. ImgurUploader - + Upload to Imgur 上傳到 Imgur - + Uploading Image 正在上傳 - + Copy URL 複製連結 - + Open URL 打開連結 - + Delete image - + Image to Clipboard. 將檔案複製到剪貼簿 - - + + Unable to open the URL. 無法打開此連結 - + URL copied to clipboard. 連結已複製到剪貼簿 - + Screenshot copied to clipboard. 截圖已複製到剪貼簿 @@ -463,12 +463,12 @@ Press Space to open the side panel. ImgurUploaderTool - + Image Uploader 上傳圖片 - + Upload the selection to Imgur 上傳到 Imgur @@ -476,7 +476,7 @@ Press Space to open the side panel. InfoWindow - + About 關於 @@ -496,77 +496,77 @@ Press Space to open the side panel. 滑鼠滑輪 - + Move selection 1px 移動 1px - + Resize selection 1px 調整大小 1px - + Quit capture 結束擷取 - + Copy to clipboard 複製到剪貼簿 - + Save selection as a file 將選擇範圍另存新檔 - + Undo the last modification 復原上次修改 - + Toggle visibility of sidebar with options of the selected tool - + Show color picker 顯示顏色選擇器 - + Change the tool's thickness 改變工具的寬度 - + Key - + Description 描述 - + <u><b>License</b></u> <u><b>授權條款</b></u> - + <u><b>Version</b></u> <u><b>版本</b></u> - + <u><b>Shortcuts</b></u> <u><b>快速鍵</b></u> - + Available shortcuts in the screen capture mode. 螢幕擷取模式中的可用快速鍵 @@ -574,12 +574,12 @@ Press Space to open the side panel. LineTool - + Line 直線 - + Set the Line as the paint tool 將直線線設定為繪畫工具 @@ -587,12 +587,12 @@ Press Space to open the side panel. MarkerTool - + Marker 標記 - + Set the Marker as the paint tool 將標記設定為繪畫工具 @@ -600,12 +600,12 @@ Press Space to open the side panel. MoveTool - + Move 移動 - + Move the selection area 移動選擇區域 @@ -613,12 +613,12 @@ Press Space to open the side panel. PencilTool - + Pencil 鉛筆 - + Set the Pencil as the paint tool 將鉛筆設定為繪畫工具 @@ -626,12 +626,12 @@ Press Space to open the side panel. PinTool - + Pin Tool - + Pin image on the desktop @@ -639,13 +639,13 @@ Press Space to open the side panel. QObject - + Save Error 存檔錯誤 - + Capture saved as 截圖已另存為 @@ -656,31 +656,31 @@ Press Space to open the side panel. - + Error trying to save as 嘗試另存新檔時發生錯誤 - - - - + + + + Unable to connect via DBus 無法透過 DBus 進行連接 - + Error 錯誤 - + Unable to write in 無法寫入 - + URL copied to clipboard. 連結已複製到剪貼簿 @@ -688,12 +688,12 @@ Press Space to open the side panel. RectangleTool - + Rectangle 實心矩形 - + Set the Rectangle as the paint tool 將實心矩形設定為繪畫工具 @@ -701,12 +701,12 @@ Press Space to open the side panel. RedoTool - + Redo - + Redo the next modification @@ -714,12 +714,12 @@ Press Space to open the side panel. SaveTool - + Save 儲存 - + Save the capture 儲存擷取 @@ -727,7 +727,7 @@ Press Space to open the side panel. ScreenGrabber - + Unable to capture screen 無法擷取螢幕 @@ -735,12 +735,12 @@ Press Space to open the side panel. SelectionTool - + Rectangular Selection 矩形選擇 - + Set Selection as the paint tool 將矩形選擇設定為繪畫工具 @@ -748,22 +748,22 @@ Press Space to open the side panel. SidePanelWidget - + Active thickness: - + Active color: - + Press ESC to cancel - + Grab Color @@ -771,12 +771,12 @@ Press Space to open the side panel. SizeIndicatorTool - + Selection Size Indicator 選擇尺寸指示 - + Show the dimensions of the selection (X Y) 顯示選擇的尺寸 (X Y) @@ -784,107 +784,107 @@ Press Space to open the side panel. StrftimeChooserWidget - + Century (00-99) 世紀 (00-99) - + Year (00-99) 年 (00-99) - + Year (2000) 年 (2000) - + Month Name (jan) 月 (jul) - + Month Name (january) 月 (juliol) - + Month (01-12) 月 (01-12) - + Week Day (1-7) 平常日 (1-7) - + Week (01-53) 周 (01-53) - + Day Name (mon) 星期 (dg) - + Day Name (monday) 星期 (diumenge) - + Day (01-31) 天 (01-31) - + Day of Month (1-31) 一月中的某天 (1-31) - + Day (001-366) 天 (001-366) - + Time (%H-%M-%S) - + Time (%H-%M) - + Hour (00-23) 小時 (00-23) - + Hour (01-12) 小時 (01-12) - + Minute (00-59) 分鐘 (00-59) - + Second (00-59) 秒 (00-59) - + Full Date (%m/%d/%y) 日期 (%m/%d/%y) - + Full Date (%Y-%m-%d) 日期 (%Y-%m-%d) @@ -892,7 +892,7 @@ Press Space to open the side panel. SystemNotification - + Flameshot Info @@ -900,22 +900,22 @@ Press Space to open the side panel. TextConfig - + StrikeOut - + Underline - + Bold - + Italic @@ -923,12 +923,12 @@ Press Space to open the side panel. TextTool - + Text - + Add text to your capture @@ -936,37 +936,37 @@ Press Space to open the side panel. UIcolorEditor - + UI Color Editor UI 顏色編輯器 - + Change the color moving the selectors and see the changes in the preview buttons. 移動顏色選擇並在預覽按鈕檢視 - + Select a Button to modify it 選擇一個按鈕來修改它 - + Main Color 主色 - + Click on this button to set the edition mode of the main color. 點選按鈕設定主色 - + Contrast Color 對比色 - + Click on this button to set the edition mode of the contrast color. 點選按鈕設定對比色 @@ -974,12 +974,12 @@ Press Space to open the side panel. UndoTool - + Undo 復原 - + Undo the last modification 復原上次修改 @@ -987,17 +987,17 @@ Press Space to open the side panel. VisualsEditor - + Opacity of area outside selection: 選擇區域以外的不透明度 - + Button Selection 按鈕選擇 - + Select All 全選 diff --git a/external/Qt-Color-Widgets/src/color_utils.cpp b/external/Qt-Color-Widgets/src/color_utils.cpp index e0bdb793..e459381d 100644 --- a/external/Qt-Color-Widgets/src/color_utils.cpp +++ b/external/Qt-Color-Widgets/src/color_utils.cpp @@ -24,59 +24,59 @@ namespace color_widgets { namespace detail { -QColor color_from_lch(qreal hue, qreal chroma, qreal luma, qreal alpha ) +QColor +color_from_lch(qreal hue, qreal chroma, qreal luma, qreal alpha) { - qreal h1 = hue*6; - qreal x = chroma*(1-qAbs(std::fmod(h1,2)-1)); - QColor col; - if ( h1 >= 0 && h1 < 1 ) - col = QColor::fromRgbF(chroma,x,0); - else if ( h1 < 2 ) - col = QColor::fromRgbF(x,chroma,0); - else if ( h1 < 3 ) - col = QColor::fromRgbF(0,chroma,x); - else if ( h1 < 4 ) - col = QColor::fromRgbF(0,x,chroma); - else if ( h1 < 5 ) - col = QColor::fromRgbF(x,0,chroma); - else if ( h1 < 6 ) - col = QColor::fromRgbF(chroma,0,x); + qreal h1 = hue * 6; + qreal x = chroma * (1 - qAbs(std::fmod(h1, 2) - 1)); + QColor col; + if (h1 >= 0 && h1 < 1) + col = QColor::fromRgbF(chroma, x, 0); + else if (h1 < 2) + col = QColor::fromRgbF(x, chroma, 0); + else if (h1 < 3) + col = QColor::fromRgbF(0, chroma, x); + else if (h1 < 4) + col = QColor::fromRgbF(0, x, chroma); + else if (h1 < 5) + col = QColor::fromRgbF(x, 0, chroma); + else if (h1 < 6) + col = QColor::fromRgbF(chroma, 0, x); - qreal m = luma - color_lumaF(col); + qreal m = luma - color_lumaF(col); - return QColor::fromRgbF( - qBound(0.0,col.redF()+m,1.0), - qBound(0.0,col.greenF()+m,1.0), - qBound(0.0,col.blueF()+m,1.0), - alpha); + return QColor::fromRgbF(qBound(0.0, col.redF() + m, 1.0), + qBound(0.0, col.greenF() + m, 1.0), + qBound(0.0, col.blueF() + m, 1.0), + alpha); } -QColor color_from_hsl(qreal hue, qreal sat, qreal lig, qreal alpha ) +QColor +color_from_hsl(qreal hue, qreal sat, qreal lig, qreal alpha) { - qreal chroma = (1 - qAbs(2*lig-1))*sat; - qreal h1 = hue*6; - qreal x = chroma*(1-qAbs(std::fmod(h1,2)-1)); - QColor col; - if ( h1 >= 0 && h1 < 1 ) - col = QColor::fromRgbF(chroma,x,0); - else if ( h1 < 2 ) - col = QColor::fromRgbF(x,chroma,0); - else if ( h1 < 3 ) - col = QColor::fromRgbF(0,chroma,x); - else if ( h1 < 4 ) - col = QColor::fromRgbF(0,x,chroma); - else if ( h1 < 5 ) - col = QColor::fromRgbF(x,0,chroma); - else if ( h1 < 6 ) - col = QColor::fromRgbF(chroma,0,x); + qreal chroma = (1 - qAbs(2 * lig - 1)) * sat; + qreal h1 = hue * 6; + qreal x = chroma * (1 - qAbs(std::fmod(h1, 2) - 1)); + QColor col; + if (h1 >= 0 && h1 < 1) + col = QColor::fromRgbF(chroma, x, 0); + else if (h1 < 2) + col = QColor::fromRgbF(x, chroma, 0); + else if (h1 < 3) + col = QColor::fromRgbF(0, chroma, x); + else if (h1 < 4) + col = QColor::fromRgbF(0, x, chroma); + else if (h1 < 5) + col = QColor::fromRgbF(x, 0, chroma); + else if (h1 < 6) + col = QColor::fromRgbF(chroma, 0, x); - qreal m = lig-chroma/2; + qreal m = lig - chroma / 2; - return QColor::fromRgbF( - qBound(0.0,col.redF()+m,1.0), - qBound(0.0,col.greenF()+m,1.0), - qBound(0.0,col.blueF()+m,1.0), - alpha); + return QColor::fromRgbF(qBound(0.0, col.redF() + m, 1.0), + qBound(0.0, col.greenF() + m, 1.0), + qBound(0.0, col.blueF() + m, 1.0), + alpha); } } // namespace detail diff --git a/external/Qt-Color-Widgets/src/color_wheel.cpp b/external/Qt-Color-Widgets/src/color_wheel.cpp index 6219a64f..e188e28e 100644 --- a/external/Qt-Color-Widgets/src/color_wheel.cpp +++ b/external/Qt-Color-Widgets/src/color_wheel.cpp @@ -21,560 +21,544 @@ */ #include "color_wheel.hpp" -#include -#include -#include -#include -#include -#include -#include #include "color_utils.hpp" +#include +#include +#include +#include +#include +#include +#include namespace color_widgets { enum MouseStatus { - Nothing, - DragCircle, - DragSquare + Nothing, + DragCircle, + DragSquare }; -static const ColorWheel::DisplayFlags hard_default_flags = ColorWheel::SHAPE_TRIANGLE|ColorWheel::ANGLE_ROTATING|ColorWheel::COLOR_HSV; +static const ColorWheel::DisplayFlags hard_default_flags = + ColorWheel::SHAPE_TRIANGLE | ColorWheel::ANGLE_ROTATING | + ColorWheel::COLOR_HSV; static ColorWheel::DisplayFlags default_flags = hard_default_flags; static const double selector_radius = 6; class ColorWheel::Private { private: - ColorWheel * const w; + ColorWheel* const w; public: - qreal hue, sat, val; - qreal bgBrightness; - unsigned int wheel_width; - MouseStatus mouse_status; - QPixmap hue_ring; - QImage inner_selector; - DisplayFlags display_flags; - QColor (*color_from)(qreal,qreal,qreal,qreal); - QColor (*rainbow_from_hue)(qreal); - int max_size = 128; + qreal hue, sat, val; + qreal bgBrightness; + unsigned int wheel_width; + MouseStatus mouse_status; + QPixmap hue_ring; + QImage inner_selector; + DisplayFlags display_flags; + QColor (*color_from)(qreal, qreal, qreal, qreal); + QColor (*rainbow_from_hue)(qreal); + int max_size = 128; - explicit Private(ColorWheel *widget) - : w(widget), hue(0), sat(0), val(0), - wheel_width(20), mouse_status(Nothing), - display_flags(FLAGS_DEFAULT), - color_from(&QColor::fromHsvF), rainbow_from_hue(&detail::rainbow_hsv) - { - QColor bgColor = widget->palette().window().color(); - bgBrightness = color_widgets::detail::color_lumaF(bgColor); + explicit Private(ColorWheel* widget) + : w(widget) + , hue(0) + , sat(0) + , val(0) + , wheel_width(20) + , mouse_status(Nothing) + , display_flags(FLAGS_DEFAULT) + , color_from(&QColor::fromHsvF) + , rainbow_from_hue(&detail::rainbow_hsv) + { + QColor bgColor = widget->palette().window().color(); + bgBrightness = color_widgets::detail::color_lumaF(bgColor); + } + + /// Calculate outer wheel radius from idget center + qreal outer_radius() const + { + return qMin(w->geometry().width(), w->geometry().height()) / 2; + } + + /// Calculate inner wheel radius from idget center + qreal inner_radius() const { return outer_radius() - wheel_width; } + + /// Calculate the edge length of the inner square + qreal square_size() const { return inner_radius() * qSqrt(2); } + + /// Calculate the height of the inner triangle + qreal triangle_height() const { return inner_radius() * 3 / 2; } + + /// Calculate the side of the inner triangle + qreal triangle_side() const { return inner_radius() * qSqrt(3); } + + /// return line from center to given point + QLineF line_to_point(const QPoint& p) const + { + return QLineF( + w->geometry().width() / 2, w->geometry().height() / 2, p.x(), p.y()); + } + + void render_square() + { + int width = qMin(square_size(), max_size); + QSize size(width, width); + inner_selector = QImage(size, QImage::Format_RGB32); + + for (int y = 0; y < width; ++y) { + for (int x = 0; x < width; ++x) { + inner_selector.setPixel( + x, y, color_from(hue, double(x) / width, double(y) / width, 1).rgb()); + } + } + } + + /** + * \brief renders the selector as a triangle + * \note It's the same as a square with the edge with value=0 collapsed to a + * single point + */ + void render_triangle() + { + QSizeF size = selector_size(); + if (size.height() > max_size) + size *= max_size / size.height(); + + qreal ycenter = size.height() / 2; + inner_selector = QImage(size.toSize(), QImage::Format_RGB32); + + for (int x = 0; x < inner_selector.width(); x++) { + qreal pval = x / size.height(); + qreal slice_h = size.height() * pval; + for (int y = 0; y < inner_selector.height(); y++) { + qreal ymin = ycenter - slice_h / 2; + qreal psat = qBound(0.0, (y - ymin) / slice_h, 1.0); + + inner_selector.setPixel(x, y, color_from(hue, psat, pval, 1).rgb()); + } + } + } + + /// Updates the inner image that displays the saturation-value selector + void render_inner_selector() + { + if (display_flags & ColorWheel::SHAPE_TRIANGLE) + render_triangle(); + else + render_square(); + } + + /// Offset of the selector image + QPointF selector_image_offset() + { + if (display_flags & SHAPE_TRIANGLE) + return QPointF(-inner_radius(), -triangle_side() / 2); + return QPointF(-square_size() / 2, -square_size() / 2); + } + + /** + * \brief Size of the selector when rendered to the screen + */ + QSizeF selector_size() + { + if (display_flags & SHAPE_TRIANGLE) + return QSizeF(triangle_height(), triangle_side()); + return QSizeF(square_size(), square_size()); + } + + /// Rotation of the selector image + qreal selector_image_angle() + { + if (display_flags & SHAPE_TRIANGLE) { + if (display_flags & ANGLE_ROTATING) + return -hue * 360 - 60; + return -150; + } else { + if (display_flags & ANGLE_ROTATING) + return -hue * 360 - 45; + else + return 180; + } + } + + /// Updates the outer ring that displays the hue selector + void render_ring() + { + hue_ring = QPixmap(outer_radius() * 2, outer_radius() * 2); + hue_ring.fill(Qt::transparent); + QPainter painter(&hue_ring); + painter.setRenderHint(QPainter::Antialiasing); + painter.setCompositionMode(QPainter::CompositionMode_Source); + + const int hue_stops = 24; + QConicalGradient gradient_hue(0, 0, 0); + if (gradient_hue.stops().size() < hue_stops) { + for (double a = 0; a < 1.0; a += 1.0 / (hue_stops - 1)) { + gradient_hue.setColorAt(a, rainbow_from_hue(a)); + } + gradient_hue.setColorAt(1, rainbow_from_hue(0)); } - /// Calculate outer wheel radius from idget center - qreal outer_radius() const - { - return qMin(w->geometry().width(), w->geometry().height())/2; - } - - /// Calculate inner wheel radius from idget center - qreal inner_radius() const - { - return outer_radius()-wheel_width; - } - - /// Calculate the edge length of the inner square - qreal square_size() const - { - return inner_radius()*qSqrt(2); - } - - /// Calculate the height of the inner triangle - qreal triangle_height() const - { - return inner_radius()*3/2; - } - - /// Calculate the side of the inner triangle - qreal triangle_side() const - { - return inner_radius()*qSqrt(3); - } - - /// return line from center to given point - QLineF line_to_point(const QPoint &p) const - { - return QLineF (w->geometry().width()/2, w->geometry().height()/2, p.x(), p.y()); - } - - void render_square() - { - int width = qMin(square_size(), max_size); - QSize size(width, width); - inner_selector = QImage(size, QImage::Format_RGB32); - - for ( int y = 0; y < width; ++y ) - { - for ( int x = 0; x < width; ++x ) - { - inner_selector.setPixel( x, y, - color_from(hue,double(x)/width,double(y)/width,1).rgb()); - } - } - } - - /** - * \brief renders the selector as a triangle - * \note It's the same as a square with the edge with value=0 collapsed to a single point - */ - void render_triangle() - { - QSizeF size = selector_size(); - if ( size.height() > max_size ) - size *= max_size / size.height(); - - qreal ycenter = size.height()/2; - inner_selector = QImage(size.toSize(), QImage::Format_RGB32); - - for (int x = 0; x < inner_selector.width(); x++ ) - { - qreal pval = x / size.height(); - qreal slice_h = size.height() * pval; - for (int y = 0; y < inner_selector.height(); y++ ) - { - qreal ymin = ycenter-slice_h/2; - qreal psat = qBound(0.0,(y-ymin)/slice_h,1.0); - - inner_selector.setPixel(x,y,color_from(hue,psat,pval,1).rgb()); - } - } - } - - /// Updates the inner image that displays the saturation-value selector - void render_inner_selector() - { - if ( display_flags & ColorWheel::SHAPE_TRIANGLE ) - render_triangle(); - else - render_square(); - } - - /// Offset of the selector image - QPointF selector_image_offset() - { - if ( display_flags & SHAPE_TRIANGLE ) - return QPointF(-inner_radius(),-triangle_side()/2); - return QPointF(-square_size()/2,-square_size()/2); - } - - /** - * \brief Size of the selector when rendered to the screen - */ - QSizeF selector_size() - { - if ( display_flags & SHAPE_TRIANGLE ) - return QSizeF(triangle_height(), triangle_side()); - return QSizeF(square_size(), square_size()); - } - - - /// Rotation of the selector image - qreal selector_image_angle() - { - if ( display_flags & SHAPE_TRIANGLE ) - { - if ( display_flags & ANGLE_ROTATING ) - return -hue*360-60; - return -150; - } - else - { - if ( display_flags & ANGLE_ROTATING ) - return -hue*360-45; - else - return 180; - } - } - - /// Updates the outer ring that displays the hue selector - void render_ring() - { - hue_ring = QPixmap(outer_radius()*2,outer_radius()*2); - hue_ring.fill(Qt::transparent); - QPainter painter(&hue_ring); - painter.setRenderHint(QPainter::Antialiasing); - painter.setCompositionMode(QPainter::CompositionMode_Source); - - - const int hue_stops = 24; - QConicalGradient gradient_hue(0, 0, 0); - if ( gradient_hue.stops().size() < hue_stops ) - { - for ( double a = 0; a < 1.0; a+=1.0/(hue_stops-1) ) - { - gradient_hue.setColorAt(a,rainbow_from_hue(a)); - } - gradient_hue.setColorAt(1,rainbow_from_hue(0)); - } - - painter.translate(outer_radius(),outer_radius()); - - painter.setPen(Qt::NoPen); - painter.setBrush(QBrush(gradient_hue)); - painter.drawEllipse(QPointF(0,0),outer_radius(),outer_radius()); - - painter.setBrush(Qt::transparent);//palette().background()); - painter.drawEllipse(QPointF(0,0),inner_radius(),inner_radius()); - } - - void set_color(const QColor& c) - { - if ( display_flags & ColorWheel::COLOR_HSV ) - { - hue = qMax(0.0, c.hsvHueF()); - sat = c.hsvSaturationF(); - val = c.valueF(); - } - else if ( display_flags & ColorWheel::COLOR_HSL ) - { - hue = qMax(0.0, c.hueF()); - sat = detail::color_HSL_saturationF(c); - val = detail::color_lightnessF(c); - } - else if ( display_flags & ColorWheel::COLOR_LCH ) - { - hue = qMax(0.0, c.hsvHueF()); - sat = detail::color_chromaF(c); - val = detail::color_lumaF(c); - } + painter.translate(outer_radius(), outer_radius()); + + painter.setPen(Qt::NoPen); + painter.setBrush(QBrush(gradient_hue)); + painter.drawEllipse(QPointF(0, 0), outer_radius(), outer_radius()); + + painter.setBrush(Qt::transparent); // palette().background()); + painter.drawEllipse(QPointF(0, 0), inner_radius(), inner_radius()); + } + + void set_color(const QColor& c) + { + if (display_flags & ColorWheel::COLOR_HSV) { + hue = qMax(0.0, c.hsvHueF()); + sat = c.hsvSaturationF(); + val = c.valueF(); + } else if (display_flags & ColorWheel::COLOR_HSL) { + hue = qMax(0.0, c.hueF()); + sat = detail::color_HSL_saturationF(c); + val = detail::color_lightnessF(c); + } else if (display_flags & ColorWheel::COLOR_LCH) { + hue = qMax(0.0, c.hsvHueF()); + sat = detail::color_chromaF(c); + val = detail::color_lumaF(c); } + } }; -ColorWheel::ColorWheel(QWidget *parent) : - QWidget(parent), p(new Private(this)) +ColorWheel::ColorWheel(QWidget* parent) + : QWidget(parent) + , p(new Private(this)) { - setDisplayFlags(FLAGS_DEFAULT); - setAcceptDrops(true); + setDisplayFlags(FLAGS_DEFAULT); + setAcceptDrops(true); } ColorWheel::~ColorWheel() { - delete p; + delete p; } -QColor ColorWheel::color() const +QColor +ColorWheel::color() const { - return p->color_from(p->hue, p->sat, p->val, 1); + return p->color_from(p->hue, p->sat, p->val, 1); } -QSize ColorWheel::sizeHint() const +QSize +ColorWheel::sizeHint() const { - return QSize(p->wheel_width*5, p->wheel_width*5); + return QSize(p->wheel_width * 5, p->wheel_width * 5); } -qreal ColorWheel::hue() const +qreal +ColorWheel::hue() const { - if ( (p->display_flags & COLOR_LCH) && p->sat > 0.01 ) - return color().hueF(); - return p->hue; + if ((p->display_flags & COLOR_LCH) && p->sat > 0.01) + return color().hueF(); + return p->hue; } -qreal ColorWheel::saturation() const +qreal +ColorWheel::saturation() const { - return color().hsvSaturationF(); + return color().hsvSaturationF(); } -qreal ColorWheel::value() const +qreal +ColorWheel::value() const { - return color().valueF(); + return color().valueF(); } -unsigned int ColorWheel::wheelWidth() const +unsigned int +ColorWheel::wheelWidth() const { - return p->wheel_width; + return p->wheel_width; } -void ColorWheel::setWheelWidth(unsigned int w) +void +ColorWheel::setWheelWidth(unsigned int w) { - p->wheel_width = w; - p->render_inner_selector(); - update(); + p->wheel_width = w; + p->render_inner_selector(); + update(); } -void ColorWheel::paintEvent(QPaintEvent * ) +void +ColorWheel::paintEvent(QPaintEvent*) { - QPainter painter(this); - painter.setRenderHint(QPainter::Antialiasing); - painter.translate(geometry().width()/2,geometry().height()/2); + QPainter painter(this); + painter.setRenderHint(QPainter::Antialiasing); + painter.translate(geometry().width() / 2, geometry().height() / 2); - // hue wheel - if(p->hue_ring.isNull()) - p->render_ring(); - - painter.drawPixmap(-p->outer_radius(), -p->outer_radius(), p->hue_ring); - - // hue selector - QColor penColor = p->bgBrightness < 0.6 ? Qt::white : Qt::black; - painter.setPen(QPen(penColor,3)); - painter.setBrush(Qt::NoBrush); - QLineF ray(0, 0, p->outer_radius(), 0); - ray.setAngle(p->hue*360); - QPointF h1 = ray.p2(); - ray.setLength(p->inner_radius()); - QPointF h2 = ray.p2(); - painter.drawLine(h1,h2); - - // lum-sat square - if(p->inner_selector.isNull()) - p->render_inner_selector(); - - painter.rotate(p->selector_image_angle()); - painter.translate(p->selector_image_offset()); - - QPointF selector_position; - if ( p->display_flags & SHAPE_SQUARE ) - { - qreal side = p->square_size(); - selector_position = QPointF(p->sat*side, p->val*side); - } - else if ( p->display_flags & SHAPE_TRIANGLE ) - { - qreal side = p->triangle_side(); - qreal height = p->triangle_height(); - qreal slice_h = side * p->val; - qreal ymin = side/2-slice_h/2; - - selector_position = QPointF(p->val*height, ymin + p->sat*slice_h); - QPolygonF triangle; - triangle.append(QPointF(0,side/2)); - triangle.append(QPointF(height,0)); - triangle.append(QPointF(height,side)); - QPainterPath clip; - clip.addPolygon(triangle); - painter.setClipPath(clip); - } - - painter.drawImage(QRectF(QPointF(0, 0), p->selector_size()), p->inner_selector); - painter.setClipping(false); - - // lum-sat selector - // we define the color of the selecto based on the background color of the widget - // in order to improve the contrast - qreal colorBrightness = color_widgets::detail::color_lumaF(color()); - if (p->bgBrightness < 0.6) // dark theme - { - bool isWhite = (colorBrightness < 0.7); - painter.setPen(QPen(isWhite ? Qt::white : Qt::black, 3)); - } - else // light theme - { - bool isWhite = (colorBrightness < 0.4 && p->val < 0.3); - painter.setPen(QPen(isWhite ? Qt::white : Qt::black, 3)); - } - painter.setBrush(Qt::NoBrush); - painter.drawEllipse(selector_position, selector_radius, selector_radius); - -} - -void ColorWheel::mouseMoveEvent(QMouseEvent *ev) -{ - if (p->mouse_status == DragCircle ) - { - p->hue = p->line_to_point(ev->pos()).angle()/360.0; - p->render_inner_selector(); - - emit colorSelected(color()); - emit colorChanged(color()); - update(); - } - else if(p->mouse_status == DragSquare) - { - QLineF glob_mouse_ln = p->line_to_point(ev->pos()); - QLineF center_mouse_ln ( QPointF(0,0), - glob_mouse_ln.p2() - glob_mouse_ln.p1() ); - - center_mouse_ln.setAngle(center_mouse_ln.angle()+p->selector_image_angle()); - center_mouse_ln.setP2(center_mouse_ln.p2()-p->selector_image_offset()); - - if ( p->display_flags & SHAPE_SQUARE ) - { - p->sat = qBound(0.0, center_mouse_ln.x2()/p->square_size(), 1.0); - p->val = qBound(0.0, center_mouse_ln.y2()/p->square_size(), 1.0); - } - else if ( p->display_flags & SHAPE_TRIANGLE ) - { - QPointF pt = center_mouse_ln.p2(); - - qreal side = p->triangle_side(); - p->val = qBound(0.0, pt.x() / p->triangle_height(), 1.0); - qreal slice_h = side * p->val; - - qreal ycenter = side/2; - qreal ymin = ycenter-slice_h/2; - - if ( slice_h > 0 ) - p->sat = qBound(0.0, (pt.y()-ymin)/slice_h, 1.0); - } - - emit colorSelected(color()); - emit colorChanged(color()); - update(); - } -} - -void ColorWheel::mousePressEvent(QMouseEvent *ev) -{ - if ( ev->buttons() & Qt::LeftButton ) - { - setFocus(); - QLineF ray = p->line_to_point(ev->pos()); - if ( ray.length() <= p->inner_radius() ) - p->mouse_status = DragSquare; - else if ( ray.length() <= p->outer_radius() ) - p->mouse_status = DragCircle; - - // Update the color - mouseMoveEvent(ev); - } -} - -void ColorWheel::mouseReleaseEvent(QMouseEvent *ev) -{ - mouseMoveEvent(ev); - p->mouse_status = Nothing; - emit mouseReleaseOnColor(color()); - -} - -void ColorWheel::resizeEvent(QResizeEvent *) -{ + // hue wheel + if (p->hue_ring.isNull()) p->render_ring(); + + painter.drawPixmap(-p->outer_radius(), -p->outer_radius(), p->hue_ring); + + // hue selector + QColor penColor = p->bgBrightness < 0.6 ? Qt::white : Qt::black; + painter.setPen(QPen(penColor, 3)); + painter.setBrush(Qt::NoBrush); + QLineF ray(0, 0, p->outer_radius(), 0); + ray.setAngle(p->hue * 360); + QPointF h1 = ray.p2(); + ray.setLength(p->inner_radius()); + QPointF h2 = ray.p2(); + painter.drawLine(h1, h2); + + // lum-sat square + if (p->inner_selector.isNull()) p->render_inner_selector(); + + painter.rotate(p->selector_image_angle()); + painter.translate(p->selector_image_offset()); + + QPointF selector_position; + if (p->display_flags & SHAPE_SQUARE) { + qreal side = p->square_size(); + selector_position = QPointF(p->sat * side, p->val * side); + } else if (p->display_flags & SHAPE_TRIANGLE) { + qreal side = p->triangle_side(); + qreal height = p->triangle_height(); + qreal slice_h = side * p->val; + qreal ymin = side / 2 - slice_h / 2; + + selector_position = QPointF(p->val * height, ymin + p->sat * slice_h); + QPolygonF triangle; + triangle.append(QPointF(0, side / 2)); + triangle.append(QPointF(height, 0)); + triangle.append(QPointF(height, side)); + QPainterPath clip; + clip.addPolygon(triangle); + painter.setClipPath(clip); + } + + painter.drawImage(QRectF(QPointF(0, 0), p->selector_size()), + p->inner_selector); + painter.setClipping(false); + + // lum-sat selector + // we define the color of the selecto based on the background color of the + // widget in order to improve the contrast + qreal colorBrightness = color_widgets::detail::color_lumaF(color()); + if (p->bgBrightness < 0.6) // dark theme + { + bool isWhite = (colorBrightness < 0.7); + painter.setPen(QPen(isWhite ? Qt::white : Qt::black, 3)); + } else // light theme + { + bool isWhite = (colorBrightness < 0.4 && p->val < 0.3); + painter.setPen(QPen(isWhite ? Qt::white : Qt::black, 3)); + } + painter.setBrush(Qt::NoBrush); + painter.drawEllipse(selector_position, selector_radius, selector_radius); } -void ColorWheel::setColor(QColor c) +void +ColorWheel::mouseMoveEvent(QMouseEvent* ev) { - qreal oldh = p->hue; - p->set_color(c); - if (!qFuzzyCompare(oldh+1, p->hue+1)) - p->render_inner_selector(); - update(); - emit colorChanged(c); -} - -void ColorWheel::setHue(qreal h) -{ - p->hue = qBound(0.0, h, 1.0); + if (p->mouse_status == DragCircle) { + p->hue = p->line_to_point(ev->pos()).angle() / 360.0; p->render_inner_selector(); + + emit colorSelected(color()); + emit colorChanged(color()); update(); -} + } else if (p->mouse_status == DragSquare) { + QLineF glob_mouse_ln = p->line_to_point(ev->pos()); + QLineF center_mouse_ln(QPointF(0, 0), + glob_mouse_ln.p2() - glob_mouse_ln.p1()); -void ColorWheel::setSaturation(qreal s) -{ - p->sat = qBound(0.0, s, 1.0); - update(); -} + center_mouse_ln.setAngle(center_mouse_ln.angle() + + p->selector_image_angle()); + center_mouse_ln.setP2(center_mouse_ln.p2() - p->selector_image_offset()); -void ColorWheel::setValue(qreal v) -{ - p->val = qBound(0.0, v, 1.0); - update(); -} + if (p->display_flags & SHAPE_SQUARE) { + p->sat = qBound(0.0, center_mouse_ln.x2() / p->square_size(), 1.0); + p->val = qBound(0.0, center_mouse_ln.y2() / p->square_size(), 1.0); + } else if (p->display_flags & SHAPE_TRIANGLE) { + QPointF pt = center_mouse_ln.p2(); + qreal side = p->triangle_side(); + p->val = qBound(0.0, pt.x() / p->triangle_height(), 1.0); + qreal slice_h = side * p->val; -void ColorWheel::setDisplayFlags(DisplayFlags flags) -{ - if ( ! (flags & COLOR_FLAGS) ) - flags |= default_flags & COLOR_FLAGS; - if ( ! (flags & ANGLE_FLAGS) ) - flags |= default_flags & ANGLE_FLAGS; - if ( ! (flags & SHAPE_FLAGS) ) - flags |= default_flags & SHAPE_FLAGS; + qreal ycenter = side / 2; + qreal ymin = ycenter - slice_h / 2; - if ( (flags & COLOR_FLAGS) != (p->display_flags & COLOR_FLAGS) ) - { - QColor old_col = color(); - if ( flags & ColorWheel::COLOR_HSL ) - { - p->hue = old_col.hueF(); - p->sat = detail::color_HSL_saturationF(old_col); - p->val = detail::color_lightnessF(old_col); - p->color_from = &detail::color_from_hsl; - p->rainbow_from_hue = &detail::rainbow_hsv; - } - else if ( flags & ColorWheel::COLOR_LCH ) - { - p->hue = old_col.hueF(); - p->sat = detail::color_chromaF(old_col); - p->val = detail::color_lumaF(old_col); - p->color_from = &detail::color_from_lch; - p->rainbow_from_hue = &detail::rainbow_lch; - } - else - { - p->hue = old_col.hsvHueF(); - p->sat = old_col.hsvSaturationF(); - p->val = old_col.valueF(); - p->color_from = &QColor::fromHsvF; - p->rainbow_from_hue = &detail::rainbow_hsv; - } - p->render_ring(); + if (slice_h > 0) + p->sat = qBound(0.0, (pt.y() - ymin) / slice_h, 1.0); } - p->display_flags = flags; - p->render_inner_selector(); + emit colorSelected(color()); + emit colorChanged(color()); update(); - emit displayFlagsChanged(flags); + } } -ColorWheel::DisplayFlags ColorWheel::displayFlags(DisplayFlags mask) const +void +ColorWheel::mousePressEvent(QMouseEvent* ev) { - return p->display_flags & mask; + if (ev->buttons() & Qt::LeftButton) { + setFocus(); + QLineF ray = p->line_to_point(ev->pos()); + if (ray.length() <= p->inner_radius()) + p->mouse_status = DragSquare; + else if (ray.length() <= p->outer_radius()) + p->mouse_status = DragCircle; + + // Update the color + mouseMoveEvent(ev); + } } -void ColorWheel::setDefaultDisplayFlags(DisplayFlags flags) +void +ColorWheel::mouseReleaseEvent(QMouseEvent* ev) { - if ( !(flags & COLOR_FLAGS) ) - flags |= hard_default_flags & COLOR_FLAGS; - if ( !(flags & ANGLE_FLAGS) ) - flags |= hard_default_flags & ANGLE_FLAGS; - if ( !(flags & SHAPE_FLAGS) ) - flags |= hard_default_flags & SHAPE_FLAGS; - default_flags = flags; + mouseMoveEvent(ev); + p->mouse_status = Nothing; + emit mouseReleaseOnColor(color()); } -ColorWheel::DisplayFlags ColorWheel::defaultDisplayFlags(DisplayFlags mask) +void +ColorWheel::resizeEvent(QResizeEvent*) { - return default_flags & mask; + p->render_ring(); + p->render_inner_selector(); } -void ColorWheel::setDisplayFlag(DisplayFlags flag, DisplayFlags mask) +void +ColorWheel::setColor(QColor c) { - setDisplayFlags((p->display_flags&~mask)|flag); + qreal oldh = p->hue; + p->set_color(c); + if (!qFuzzyCompare(oldh + 1, p->hue + 1)) + p->render_inner_selector(); + update(); + emit colorChanged(c); } -void ColorWheel::dragEnterEvent(QDragEnterEvent* event) +void +ColorWheel::setHue(qreal h) { - if ( event->mimeData()->hasColor() || - ( event->mimeData()->hasText() && QColor(event->mimeData()->text()).isValid() ) ) - event->acceptProposedAction(); + p->hue = qBound(0.0, h, 1.0); + p->render_inner_selector(); + update(); } -void ColorWheel::dropEvent(QDropEvent* event) +void +ColorWheel::setSaturation(qreal s) { - if ( event->mimeData()->hasColor() ) - { - setColor(event->mimeData()->colorData().value()); - event->accept(); + p->sat = qBound(0.0, s, 1.0); + update(); +} + +void +ColorWheel::setValue(qreal v) +{ + p->val = qBound(0.0, v, 1.0); + update(); +} + +void +ColorWheel::setDisplayFlags(DisplayFlags flags) +{ + if (!(flags & COLOR_FLAGS)) + flags |= default_flags & COLOR_FLAGS; + if (!(flags & ANGLE_FLAGS)) + flags |= default_flags & ANGLE_FLAGS; + if (!(flags & SHAPE_FLAGS)) + flags |= default_flags & SHAPE_FLAGS; + + if ((flags & COLOR_FLAGS) != (p->display_flags & COLOR_FLAGS)) { + QColor old_col = color(); + if (flags & ColorWheel::COLOR_HSL) { + p->hue = old_col.hueF(); + p->sat = detail::color_HSL_saturationF(old_col); + p->val = detail::color_lightnessF(old_col); + p->color_from = &detail::color_from_hsl; + p->rainbow_from_hue = &detail::rainbow_hsv; + } else if (flags & ColorWheel::COLOR_LCH) { + p->hue = old_col.hueF(); + p->sat = detail::color_chromaF(old_col); + p->val = detail::color_lumaF(old_col); + p->color_from = &detail::color_from_lch; + p->rainbow_from_hue = &detail::rainbow_lch; + } else { + p->hue = old_col.hsvHueF(); + p->sat = old_col.hsvSaturationF(); + p->val = old_col.valueF(); + p->color_from = &QColor::fromHsvF; + p->rainbow_from_hue = &detail::rainbow_hsv; } - else if ( event->mimeData()->hasText() ) - { - QColor col(event->mimeData()->text()); - if ( col.isValid() ) - { - setColor(col); - event->accept(); - } + p->render_ring(); + } + + p->display_flags = flags; + p->render_inner_selector(); + update(); + emit displayFlagsChanged(flags); +} + +ColorWheel::DisplayFlags +ColorWheel::displayFlags(DisplayFlags mask) const +{ + return p->display_flags & mask; +} + +void +ColorWheel::setDefaultDisplayFlags(DisplayFlags flags) +{ + if (!(flags & COLOR_FLAGS)) + flags |= hard_default_flags & COLOR_FLAGS; + if (!(flags & ANGLE_FLAGS)) + flags |= hard_default_flags & ANGLE_FLAGS; + if (!(flags & SHAPE_FLAGS)) + flags |= hard_default_flags & SHAPE_FLAGS; + default_flags = flags; +} + +ColorWheel::DisplayFlags +ColorWheel::defaultDisplayFlags(DisplayFlags mask) +{ + return default_flags & mask; +} + +void +ColorWheel::setDisplayFlag(DisplayFlags flag, DisplayFlags mask) +{ + setDisplayFlags((p->display_flags & ~mask) | flag); +} + +void +ColorWheel::dragEnterEvent(QDragEnterEvent* event) +{ + if (event->mimeData()->hasColor() || + (event->mimeData()->hasText() && + QColor(event->mimeData()->text()).isValid())) + event->acceptProposedAction(); +} + +void +ColorWheel::dropEvent(QDropEvent* event) +{ + if (event->mimeData()->hasColor()) { + setColor(event->mimeData()->colorData().value()); + event->accept(); + } else if (event->mimeData()->hasText()) { + QColor col(event->mimeData()->text()); + if (col.isValid()) { + setColor(col); + event->accept(); } + } } } // namespace color_widgets diff --git a/external/singleapplication/singleapplication.cpp b/external/singleapplication/singleapplication.cpp index 1f5a5b8c..f929701b 100644 --- a/external/singleapplication/singleapplication.cpp +++ b/external/singleapplication/singleapplication.cpp @@ -22,335 +22,351 @@ #include +#include +#include +#include #include #include -#include #include #include #include -#include -#include #include #include #ifdef Q_OS_UNIX - #include - #include +#include +#include #endif #ifdef Q_OS_WIN - #include - #include +#include +#include #endif #include "singleapplication.h" #include "singleapplication_p.h" - -SingleApplicationPrivate::SingleApplicationPrivate( SingleApplication *q_ptr ) : q_ptr( q_ptr ) { - server = nullptr; - socket = nullptr; +SingleApplicationPrivate::SingleApplicationPrivate(SingleApplication* q_ptr) + : q_ptr(q_ptr) +{ + server = nullptr; + socket = nullptr; } SingleApplicationPrivate::~SingleApplicationPrivate() { - if( socket != nullptr ) { - socket->close(); - delete socket; - } + if (socket != nullptr) { + socket->close(); + delete socket; + } - memory->lock(); - InstancesInfo* inst = static_cast(memory->data()); - if( server != nullptr ) { - server->close(); - delete server; - inst->primary = false; - inst->primaryPid = -1; - } - memory->unlock(); + memory->lock(); + InstancesInfo* inst = static_cast(memory->data()); + if (server != nullptr) { + server->close(); + delete server; + inst->primary = false; + inst->primaryPid = -1; + } + memory->unlock(); - delete memory; + delete memory; } -void SingleApplicationPrivate::genBlockServerName( int timeout ) +void +SingleApplicationPrivate::genBlockServerName(int timeout) { - QCryptographicHash appData( QCryptographicHash::Sha256 ); - appData.addData( "SingleApplication", 17 ); - appData.addData( SingleApplication::app_t::applicationName().toUtf8() ); - appData.addData( SingleApplication::app_t::organizationName().toUtf8() ); - appData.addData( SingleApplication::app_t::organizationDomain().toUtf8() ); + QCryptographicHash appData(QCryptographicHash::Sha256); + appData.addData("SingleApplication", 17); + appData.addData(SingleApplication::app_t::applicationName().toUtf8()); + appData.addData(SingleApplication::app_t::organizationName().toUtf8()); + appData.addData(SingleApplication::app_t::organizationDomain().toUtf8()); - if( ! (options & SingleApplication::Mode::ExcludeAppVersion) ) { - appData.addData( SingleApplication::app_t::applicationVersion().toUtf8() ); - } + if (!(options & SingleApplication::Mode::ExcludeAppVersion)) { + appData.addData(SingleApplication::app_t::applicationVersion().toUtf8()); + } - if( ! (options & SingleApplication::Mode::ExcludeAppPath) ) { + if (!(options & SingleApplication::Mode::ExcludeAppPath)) { #ifdef Q_OS_WIN - appData.addData( SingleApplication::app_t::applicationFilePath().toLower().toUtf8() ); + appData.addData( + SingleApplication::app_t::applicationFilePath().toLower().toUtf8()); #else - appData.addData( SingleApplication::app_t::applicationFilePath().toUtf8() ); + appData.addData(SingleApplication::app_t::applicationFilePath().toUtf8()); #endif - } + } - // User level block requires a user specific data in the hash - if( options & SingleApplication::Mode::User ) { + // User level block requires a user specific data in the hash + if (options & SingleApplication::Mode::User) { #ifdef Q_OS_WIN - Q_UNUSED(timeout); - wchar_t username [ UNLEN + 1 ]; - // Specifies size of the buffer on input - DWORD usernameLength = UNLEN + 1; - if( GetUserNameW( username, &usernameLength ) ) { - appData.addData( QString::fromWCharArray(username).toUtf8() ); - } else { - appData.addData( QStandardPaths::standardLocations( QStandardPaths::HomeLocation ).join("").toUtf8() ); - } -#endif -#ifdef Q_OS_UNIX - QProcess process; - process.start( QStringLiteral("whoami"),QStringList{} ); - - if( process.waitForFinished( timeout ) && - process.exitCode() == QProcess::NormalExit) { - appData.addData( process.readLine() ); - } else { - appData.addData( - QDir( - QStandardPaths::standardLocations( QStandardPaths::HomeLocation ).first() - ).absolutePath().toUtf8() - ); - } -#endif - } - - // Replace the backslash in RFC 2045 Base64 [a-zA-Z0-9+/=] to comply with - // server naming requirements. - blockServerName = appData.result().toBase64().replace("/", "_"); -} - -void SingleApplicationPrivate::startPrimary( bool resetMemory ) -{ - Q_Q(SingleApplication); - -#ifdef Q_OS_UNIX - // Handle any further termination signals to ensure the - // QSharedMemory block is deleted even if the process crashes - crashHandler(); -#endif - // Successful creation means that no main process exists - // So we start a QLocalServer to listen for connections - QLocalServer::removeServer( blockServerName ); - server = new QLocalServer(); - - // Restrict access to the socket according to the - // SingleApplication::Mode::User flag on User level or no restrictions - if( options & SingleApplication::Mode::User ) { - server->setSocketOptions( QLocalServer::UserAccessOption ); + Q_UNUSED(timeout); + wchar_t username[UNLEN + 1]; + // Specifies size of the buffer on input + DWORD usernameLength = UNLEN + 1; + if (GetUserNameW(username, &usernameLength)) { + appData.addData(QString::fromWCharArray(username).toUtf8()); } else { - server->setSocketOptions( QLocalServer::WorldAccessOption ); + appData.addData( + QStandardPaths::standardLocations(QStandardPaths::HomeLocation) + .join("") + .toUtf8()); } +#endif +#ifdef Q_OS_UNIX + QProcess process; + process.start(QStringLiteral("whoami"), QStringList{}); - server->listen( blockServerName ); - QObject::connect( - server, - &QLocalServer::newConnection, - this, - &SingleApplicationPrivate::slotConnectionEstablished - ); - - // Reset the number of connections - memory->lock(); - InstancesInfo* inst = static_cast(memory->data()); - - if( resetMemory ) { - inst->secondary = 0; + if (process.waitForFinished(timeout) && + process.exitCode() == QProcess::NormalExit) { + appData.addData(process.readLine()); + } else { + appData.addData( + QDir(QStandardPaths::standardLocations(QStandardPaths::HomeLocation) + .first()) + .absolutePath() + .toUtf8()); } +#endif + } - inst->primary = true; - inst->primaryPid = q->applicationPid(); - - memory->unlock(); - - instanceNumber = 0; + // Replace the backslash in RFC 2045 Base64 [a-zA-Z0-9+/=] to comply with + // server naming requirements. + blockServerName = appData.result().toBase64().replace("/", "_"); } -void SingleApplicationPrivate::startSecondary() +void +SingleApplicationPrivate::startPrimary(bool resetMemory) +{ + Q_Q(SingleApplication); + +#ifdef Q_OS_UNIX + // Handle any further termination signals to ensure the + // QSharedMemory block is deleted even if the process crashes + crashHandler(); +#endif + // Successful creation means that no main process exists + // So we start a QLocalServer to listen for connections + QLocalServer::removeServer(blockServerName); + server = new QLocalServer(); + + // Restrict access to the socket according to the + // SingleApplication::Mode::User flag on User level or no restrictions + if (options & SingleApplication::Mode::User) { + server->setSocketOptions(QLocalServer::UserAccessOption); + } else { + server->setSocketOptions(QLocalServer::WorldAccessOption); + } + + server->listen(blockServerName); + QObject::connect(server, + &QLocalServer::newConnection, + this, + &SingleApplicationPrivate::slotConnectionEstablished); + + // Reset the number of connections + memory->lock(); + InstancesInfo* inst = static_cast(memory->data()); + + if (resetMemory) { + inst->secondary = 0; + } + + inst->primary = true; + inst->primaryPid = q->applicationPid(); + + memory->unlock(); + + instanceNumber = 0; +} + +void +SingleApplicationPrivate::startSecondary() { #ifdef Q_OS_UNIX - // Handle any further termination signals to ensure the - // QSharedMemory block is deleted even if the process crashes - crashHandler(); + // Handle any further termination signals to ensure the + // QSharedMemory block is deleted even if the process crashes + crashHandler(); #endif } -void SingleApplicationPrivate::connectToPrimary( int msecs, ConnectionType connectionType ) +void +SingleApplicationPrivate::connectToPrimary(int msecs, + ConnectionType connectionType) { - // Connect to the Local Server of the Primary Instance if not already - // connected. - if( socket == nullptr ) { - socket = new QLocalSocket(); - } + // Connect to the Local Server of the Primary Instance if not already + // connected. + if (socket == nullptr) { + socket = new QLocalSocket(); + } - // If already connected - we are done; - if( socket->state() == QLocalSocket::ConnectedState ) - return; + // If already connected - we are done; + if (socket->state() == QLocalSocket::ConnectedState) + return; - // If not connect - if( socket->state() == QLocalSocket::UnconnectedState || - socket->state() == QLocalSocket::ClosingState ) { - socket->connectToServer( blockServerName ); - } + // If not connect + if (socket->state() == QLocalSocket::UnconnectedState || + socket->state() == QLocalSocket::ClosingState) { + socket->connectToServer(blockServerName); + } - // Wait for being connected - if( socket->state() == QLocalSocket::ConnectingState ) { - socket->waitForConnected( msecs ); - } + // Wait for being connected + if (socket->state() == QLocalSocket::ConnectingState) { + socket->waitForConnected(msecs); + } - // Initialisation message according to the SingleApplication protocol - if( socket->state() == QLocalSocket::ConnectedState ) { - // Notify the parent that a new instance had been started; - QByteArray initMsg; - QDataStream writeStream(&initMsg, QIODevice::WriteOnly); - writeStream.setVersion(QDataStream::Qt_5_2); - writeStream << blockServerName.toLatin1(); - writeStream << static_cast(connectionType); - writeStream << instanceNumber; - quint16 checksum = qChecksum(initMsg.constData(), static_cast(initMsg.length())); - writeStream << checksum; + // Initialisation message according to the SingleApplication protocol + if (socket->state() == QLocalSocket::ConnectedState) { + // Notify the parent that a new instance had been started; + QByteArray initMsg; + QDataStream writeStream(&initMsg, QIODevice::WriteOnly); + writeStream.setVersion(QDataStream::Qt_5_2); + writeStream << blockServerName.toLatin1(); + writeStream << static_cast(connectionType); + writeStream << instanceNumber; + quint16 checksum = + qChecksum(initMsg.constData(), static_cast(initMsg.length())); + writeStream << checksum; - socket->write( initMsg ); - socket->flush(); - socket->waitForBytesWritten( msecs ); - } + socket->write(initMsg); + socket->flush(); + socket->waitForBytesWritten(msecs); + } } -qint64 SingleApplicationPrivate::primaryPid() +qint64 +SingleApplicationPrivate::primaryPid() { - qint64 pid; + qint64 pid; - memory->lock(); - InstancesInfo* inst = static_cast(memory->data()); - pid = inst->primaryPid; - memory->unlock(); + memory->lock(); + InstancesInfo* inst = static_cast(memory->data()); + pid = inst->primaryPid; + memory->unlock(); - return pid; + return pid; } #ifdef Q_OS_UNIX - void SingleApplicationPrivate::crashHandler() - { - // Handle any further termination signals to ensure the - // QSharedMemory block is deleted even if the process crashes - signal( SIGHUP, SingleApplicationPrivate::terminate ); // 1 - signal( SIGINT, SingleApplicationPrivate::terminate ); // 2 - signal( SIGQUIT, SingleApplicationPrivate::terminate ); // 3 - signal( SIGILL, SingleApplicationPrivate::terminate ); // 4 - signal( SIGABRT, SingleApplicationPrivate::terminate ); // 6 - signal( SIGFPE, SingleApplicationPrivate::terminate ); // 8 - signal( SIGBUS, SingleApplicationPrivate::terminate ); // 10 - signal( SIGSEGV, SingleApplicationPrivate::terminate ); // 11 - signal( SIGSYS, SingleApplicationPrivate::terminate ); // 12 - signal( SIGPIPE, SingleApplicationPrivate::terminate ); // 13 - signal( SIGALRM, SingleApplicationPrivate::terminate ); // 14 - signal( SIGTERM, SingleApplicationPrivate::terminate ); // 15 - signal( SIGXCPU, SingleApplicationPrivate::terminate ); // 24 - signal( SIGXFSZ, SingleApplicationPrivate::terminate ); // 25 - } +void +SingleApplicationPrivate::crashHandler() +{ + // Handle any further termination signals to ensure the + // QSharedMemory block is deleted even if the process crashes + signal(SIGHUP, SingleApplicationPrivate::terminate); // 1 + signal(SIGINT, SingleApplicationPrivate::terminate); // 2 + signal(SIGQUIT, SingleApplicationPrivate::terminate); // 3 + signal(SIGILL, SingleApplicationPrivate::terminate); // 4 + signal(SIGABRT, SingleApplicationPrivate::terminate); // 6 + signal(SIGFPE, SingleApplicationPrivate::terminate); // 8 + signal(SIGBUS, SingleApplicationPrivate::terminate); // 10 + signal(SIGSEGV, SingleApplicationPrivate::terminate); // 11 + signal(SIGSYS, SingleApplicationPrivate::terminate); // 12 + signal(SIGPIPE, SingleApplicationPrivate::terminate); // 13 + signal(SIGALRM, SingleApplicationPrivate::terminate); // 14 + signal(SIGTERM, SingleApplicationPrivate::terminate); // 15 + signal(SIGXCPU, SingleApplicationPrivate::terminate); // 24 + signal(SIGXFSZ, SingleApplicationPrivate::terminate); // 25 +} - void SingleApplicationPrivate::terminate( int signum ) - { - delete ((SingleApplication*)QCoreApplication::instance())->d_ptr; - ::exit( 128 + signum ); - } +void +SingleApplicationPrivate::terminate(int signum) +{ + delete ((SingleApplication*)QCoreApplication::instance())->d_ptr; + ::exit(128 + signum); +} #endif /** * @brief Executed when a connection has been made to the LocalServer */ -void SingleApplicationPrivate::slotConnectionEstablished() +void +SingleApplicationPrivate::slotConnectionEstablished() { - Q_Q(SingleApplication); + Q_Q(SingleApplication); - QLocalSocket *nextConnSocket = server->nextPendingConnection(); + QLocalSocket* nextConnSocket = server->nextPendingConnection(); - quint32 instanceId = 0; - ConnectionType connectionType = InvalidConnection; - if( nextConnSocket->waitForReadyRead( 100 ) ) { - // read all data from message in same order/format as written - QByteArray msgBytes = nextConnSocket->read(nextConnSocket->bytesAvailable() - static_cast(sizeof(quint16))); - QByteArray checksumBytes = nextConnSocket->read(sizeof(quint16)); - QDataStream readStream(msgBytes); - readStream.setVersion(QDataStream::Qt_5_2); + quint32 instanceId = 0; + ConnectionType connectionType = InvalidConnection; + if (nextConnSocket->waitForReadyRead(100)) { + // read all data from message in same order/format as written + QByteArray msgBytes = nextConnSocket->read( + nextConnSocket->bytesAvailable() - static_cast(sizeof(quint16))); + QByteArray checksumBytes = nextConnSocket->read(sizeof(quint16)); + QDataStream readStream(msgBytes); + readStream.setVersion(QDataStream::Qt_5_2); - // server name - QByteArray latin1Name; - readStream >> latin1Name; - // connectioon type - quint8 connType = InvalidConnection; - readStream >> connType; - connectionType = static_cast(connType); - // instance id - readStream >> instanceId; - // checksum - quint16 msgChecksum = 0; - QDataStream checksumStream(checksumBytes); - checksumStream.setVersion(QDataStream::Qt_5_2); - checksumStream >> msgChecksum; + // server name + QByteArray latin1Name; + readStream >> latin1Name; + // connectioon type + quint8 connType = InvalidConnection; + readStream >> connType; + connectionType = static_cast(connType); + // instance id + readStream >> instanceId; + // checksum + quint16 msgChecksum = 0; + QDataStream checksumStream(checksumBytes); + checksumStream.setVersion(QDataStream::Qt_5_2); + checksumStream >> msgChecksum; - const quint16 actualChecksum = qChecksum(msgBytes.constData(), static_cast(msgBytes.length())); + const quint16 actualChecksum = + qChecksum(msgBytes.constData(), static_cast(msgBytes.length())); - if (readStream.status() != QDataStream::Ok || QLatin1String(latin1Name) != blockServerName || msgChecksum != actualChecksum) { - connectionType = InvalidConnection; - } + if (readStream.status() != QDataStream::Ok || + QLatin1String(latin1Name) != blockServerName || + msgChecksum != actualChecksum) { + connectionType = InvalidConnection; } + } - if( connectionType == InvalidConnection ) { - nextConnSocket->close(); - delete nextConnSocket; - return; - } + if (connectionType == InvalidConnection) { + nextConnSocket->close(); + delete nextConnSocket; + return; + } - QObject::connect( - nextConnSocket, - &QLocalSocket::aboutToClose, - this, - [nextConnSocket, instanceId, this]() { - emit this->slotClientConnectionClosed( nextConnSocket, instanceId ); - } - ); + QObject::connect(nextConnSocket, + &QLocalSocket::aboutToClose, + this, + [nextConnSocket, instanceId, this]() { + emit this->slotClientConnectionClosed(nextConnSocket, + instanceId); + }); - QObject::connect( - nextConnSocket, - &QLocalSocket::readyRead, - this, - [nextConnSocket, instanceId, this]() { - emit this->slotDataAvailable( nextConnSocket, instanceId ); - } - ); + QObject::connect(nextConnSocket, + &QLocalSocket::readyRead, + this, + [nextConnSocket, instanceId, this]() { + emit this->slotDataAvailable(nextConnSocket, instanceId); + }); - if( connectionType == NewInstance || ( - connectionType == SecondaryInstance && - options & SingleApplication::Mode::SecondaryNotification - ) - ) { - emit q->instanceStarted(); - } + if (connectionType == NewInstance || + (connectionType == SecondaryInstance && + options & SingleApplication::Mode::SecondaryNotification)) { + emit q->instanceStarted(); + } - if( nextConnSocket->bytesAvailable() > 0 ) { - emit this->slotDataAvailable( nextConnSocket, instanceId ); - } + if (nextConnSocket->bytesAvailable() > 0) { + emit this->slotDataAvailable(nextConnSocket, instanceId); + } } -void SingleApplicationPrivate::slotDataAvailable( QLocalSocket *dataSocket, quint32 instanceId ) +void +SingleApplicationPrivate::slotDataAvailable(QLocalSocket* dataSocket, + quint32 instanceId) { - Q_Q(SingleApplication); - emit q->receivedMessage( instanceId, dataSocket->readAll() ); + Q_Q(SingleApplication); + emit q->receivedMessage(instanceId, dataSocket->readAll()); } -void SingleApplicationPrivate::slotClientConnectionClosed( QLocalSocket *closedSocket, quint32 instanceId ) +void +SingleApplicationPrivate::slotClientConnectionClosed(QLocalSocket* closedSocket, + quint32 instanceId) { - if( closedSocket->bytesAvailable() > 0 ) - emit slotDataAvailable( closedSocket, instanceId ); - closedSocket->deleteLater(); + if (closedSocket->bytesAvailable() > 0) + emit slotDataAvailable(closedSocket, instanceId); + closedSocket->deleteLater(); } /** @@ -360,63 +376,69 @@ void SingleApplicationPrivate::slotClientConnectionClosed( QLocalSocket *closedS * @param argv * @param {bool} allowSecondaryInstances */ -SingleApplication::SingleApplication( int &argc, char *argv[], bool allowSecondary, Options options, int timeout ) - : app_t( argc, argv ), d_ptr( new SingleApplicationPrivate( this ) ) +SingleApplication::SingleApplication(int& argc, + char* argv[], + bool allowSecondary, + Options options, + int timeout) + : app_t(argc, argv) + , d_ptr(new SingleApplicationPrivate(this)) { - Q_D(SingleApplication); + Q_D(SingleApplication); - // Store the current mode of the program - d->options = options; + // Store the current mode of the program + d->options = options; - // Generating an application ID used for identifying the shared memory - // block and QLocalServer - d->genBlockServerName( timeout ); + // Generating an application ID used for identifying the shared memory + // block and QLocalServer + d->genBlockServerName(timeout); - // Guarantee thread safe behaviour with a shared memory block. Also by - // explicitly attaching it and then deleting it we make sure that the - // memory is deleted even if the process had crashed on Unix. + // Guarantee thread safe behaviour with a shared memory block. Also by + // explicitly attaching it and then deleting it we make sure that the + // memory is deleted even if the process had crashed on Unix. #ifdef Q_OS_UNIX - d->memory = new QSharedMemory( d->blockServerName ); - d->memory->attach(); - delete d->memory; + d->memory = new QSharedMemory(d->blockServerName); + d->memory->attach(); + delete d->memory; #endif - d->memory = new QSharedMemory( d->blockServerName ); + d->memory = new QSharedMemory(d->blockServerName); - // Create a shared memory block - if( d->memory->create( sizeof( InstancesInfo ) ) ) { - d->startPrimary( true ); + // Create a shared memory block + if (d->memory->create(sizeof(InstancesInfo))) { + d->startPrimary(true); + return; + } else { + // Attempt to attach to the memory segment + if (d->memory->attach()) { + d->memory->lock(); + InstancesInfo* inst = static_cast(d->memory->data()); + + if (!inst->primary) { + d->startPrimary(false); + d->memory->unlock(); return; - } else { - // Attempt to attach to the memory segment - if( d->memory->attach() ) { - d->memory->lock(); - InstancesInfo* inst = static_cast(d->memory->data()); + } - if( ! inst->primary ) { - d->startPrimary( false ); - d->memory->unlock(); - return; - } - - // Check if another instance can be started - if( allowSecondary ) { - inst->secondary += 1; - d->instanceNumber = inst->secondary; - d->startSecondary(); - if( d->options & Mode::SecondaryNotification ) { - d->connectToPrimary( timeout, SingleApplicationPrivate::SecondaryInstance ); - } - d->memory->unlock(); - return; - } - - d->memory->unlock(); + // Check if another instance can be started + if (allowSecondary) { + inst->secondary += 1; + d->instanceNumber = inst->secondary; + d->startSecondary(); + if (d->options & Mode::SecondaryNotification) { + d->connectToPrimary(timeout, + SingleApplicationPrivate::SecondaryInstance); } - } + d->memory->unlock(); + return; + } - d->connectToPrimary( timeout, SingleApplicationPrivate::NewInstance ); - delete d; - ::exit( EXIT_SUCCESS ); + d->memory->unlock(); + } + } + + d->connectToPrimary(timeout, SingleApplicationPrivate::NewInstance); + delete d; + ::exit(EXIT_SUCCESS); } /** @@ -424,46 +446,52 @@ SingleApplication::SingleApplication( int &argc, char *argv[], bool allowSeconda */ SingleApplication::~SingleApplication() { - Q_D(SingleApplication); - delete d; + Q_D(SingleApplication); + delete d; } -bool SingleApplication::isPrimary() +bool +SingleApplication::isPrimary() { - Q_D(SingleApplication); - return d->server != nullptr; + Q_D(SingleApplication); + return d->server != nullptr; } -bool SingleApplication::isSecondary() +bool +SingleApplication::isSecondary() { - Q_D(SingleApplication); - return d->server == nullptr; + Q_D(SingleApplication); + return d->server == nullptr; } -quint32 SingleApplication::instanceId() +quint32 +SingleApplication::instanceId() { - Q_D(SingleApplication); - return d->instanceNumber; + Q_D(SingleApplication); + return d->instanceNumber; } -qint64 SingleApplication::primaryPid() +qint64 +SingleApplication::primaryPid() { - Q_D(SingleApplication); - return d->primaryPid(); + Q_D(SingleApplication); + return d->primaryPid(); } -bool SingleApplication::sendMessage( QByteArray message, int timeout ) +bool +SingleApplication::sendMessage(QByteArray message, int timeout) { - Q_D(SingleApplication); + Q_D(SingleApplication); - // Nobody to connect to - if( isPrimary() ) return false; + // Nobody to connect to + if (isPrimary()) + return false; - // Make sure the socket is connected - d->connectToPrimary( timeout, SingleApplicationPrivate::Reconnect ); + // Make sure the socket is connected + d->connectToPrimary(timeout, SingleApplicationPrivate::Reconnect); - d->socket->write( message ); - bool dataWritten = d->socket->flush(); - d->socket->waitForBytesWritten( timeout ); - return dataWritten; + d->socket->write(message); + bool dataWritten = d->socket->flush(); + d->socket->waitForBytesWritten(timeout); + return dataWritten; } diff --git a/external/singleapplication/singleapplication.h b/external/singleapplication/singleapplication.h index 33a9898a..23872809 100644 --- a/external/singleapplication/singleapplication.h +++ b/external/singleapplication/singleapplication.h @@ -27,7 +27,7 @@ #include #ifndef QAPPLICATION_CLASS - #define QAPPLICATION_CLASS QCoreApplication +#define QAPPLICATION_CLASS QCoreApplication #endif #include QT_STRINGIFY(QAPPLICATION_CLASS) @@ -41,93 +41,98 @@ class SingleApplicationPrivate; */ class SingleApplication : public QAPPLICATION_CLASS { - Q_OBJECT + Q_OBJECT - typedef QAPPLICATION_CLASS app_t; + typedef QAPPLICATION_CLASS app_t; public: - /** - * @brief Mode of operation of SingleApplication. - * Whether the block should be user-wide or system-wide and whether the - * primary instance should be notified when a secondary instance had been - * started. - * @note Operating system can restrict the shared memory blocks to the same - * user, in which case the User/System modes will have no effect and the - * block will be user wide. - * @enum - */ - enum Mode { - User = 1 << 0, - System = 1 << 1, - SecondaryNotification = 1 << 2, - ExcludeAppVersion = 1 << 3, - ExcludeAppPath = 1 << 4 - }; - Q_DECLARE_FLAGS(Options, Mode) + /** + * @brief Mode of operation of SingleApplication. + * Whether the block should be user-wide or system-wide and whether the + * primary instance should be notified when a secondary instance had been + * started. + * @note Operating system can restrict the shared memory blocks to the same + * user, in which case the User/System modes will have no effect and the + * block will be user wide. + * @enum + */ + enum Mode + { + User = 1 << 0, + System = 1 << 1, + SecondaryNotification = 1 << 2, + ExcludeAppVersion = 1 << 3, + ExcludeAppPath = 1 << 4 + }; + Q_DECLARE_FLAGS(Options, Mode) - /** - * @brief Intitializes a SingleApplication instance with argc command line - * arguments in argv - * @arg {int &} argc - Number of arguments in argv - * @arg {const char *[]} argv - Supplied command line arguments - * @arg {bool} allowSecondary - Whether to start the instance as secondary - * if there is already a primary instance. - * @arg {Mode} mode - Whether for the SingleApplication block to be applied - * User wide or System wide. - * @arg {int} timeout - Timeout to wait in miliseconds. - * @note argc and argv may be changed as Qt removes arguments that it - * recognizes - * @note Mode::SecondaryNotification only works if set on both the primary - * instance and the secondary instance. - * @note The timeout is just a hint for the maximum time of blocking - * operations. It does not guarantee that the SingleApplication - * initialisation will be completed in given time, though is a good hint. - * Usually 4*timeout would be the worst case (fail) scenario. - * @see See the corresponding QAPPLICATION_CLASS constructor for reference - */ - explicit SingleApplication( int &argc, char *argv[], bool allowSecondary = false, Options options = Mode::User, int timeout = 100 ); - ~SingleApplication(); + /** + * @brief Intitializes a SingleApplication instance with argc command line + * arguments in argv + * @arg {int &} argc - Number of arguments in argv + * @arg {const char *[]} argv - Supplied command line arguments + * @arg {bool} allowSecondary - Whether to start the instance as secondary + * if there is already a primary instance. + * @arg {Mode} mode - Whether for the SingleApplication block to be applied + * User wide or System wide. + * @arg {int} timeout - Timeout to wait in miliseconds. + * @note argc and argv may be changed as Qt removes arguments that it + * recognizes + * @note Mode::SecondaryNotification only works if set on both the primary + * instance and the secondary instance. + * @note The timeout is just a hint for the maximum time of blocking + * operations. It does not guarantee that the SingleApplication + * initialisation will be completed in given time, though is a good hint. + * Usually 4*timeout would be the worst case (fail) scenario. + * @see See the corresponding QAPPLICATION_CLASS constructor for reference + */ + explicit SingleApplication(int& argc, + char* argv[], + bool allowSecondary = false, + Options options = Mode::User, + int timeout = 100); + ~SingleApplication(); - /** - * @brief Returns if the instance is the primary instance - * @returns {bool} - */ - bool isPrimary(); + /** + * @brief Returns if the instance is the primary instance + * @returns {bool} + */ + bool isPrimary(); - /** - * @brief Returns if the instance is a secondary instance - * @returns {bool} - */ - bool isSecondary(); + /** + * @brief Returns if the instance is a secondary instance + * @returns {bool} + */ + bool isSecondary(); - /** - * @brief Returns a unique identifier for the current instance - * @returns {qint32} - */ - quint32 instanceId(); + /** + * @brief Returns a unique identifier for the current instance + * @returns {qint32} + */ + quint32 instanceId(); - /** - * @brief Returns the process ID (PID) of the primary instance - * @returns {qint64} - */ - qint64 primaryPid(); + /** + * @brief Returns the process ID (PID) of the primary instance + * @returns {qint64} + */ + qint64 primaryPid(); - /** - * @brief Sends a message to the primary instance. Returns true on success. - * @param {int} timeout - Timeout for connecting - * @returns {bool} - * @note sendMessage() will return false if invoked from the primary - * instance. - */ - bool sendMessage( QByteArray message, int timeout = 100 ); + /** + * @brief Sends a message to the primary instance. Returns true on success. + * @param {int} timeout - Timeout for connecting + * @returns {bool} + * @note sendMessage() will return false if invoked from the primary + * instance. + */ + bool sendMessage(QByteArray message, int timeout = 100); Q_SIGNALS: - void instanceStarted(); - void receivedMessage( quint32 instanceId, QByteArray message ); + void instanceStarted(); + void receivedMessage(quint32 instanceId, QByteArray message); private: - SingleApplicationPrivate *d_ptr; - Q_DECLARE_PRIVATE(SingleApplication) + SingleApplicationPrivate* d_ptr; + Q_DECLARE_PRIVATE(SingleApplication) }; Q_DECLARE_OPERATORS_FOR_FLAGS(SingleApplication::Options) diff --git a/external/singleapplication/singleapplication_p.h b/external/singleapplication/singleapplication_p.h index a990a53c..90885ed9 100644 --- a/external/singleapplication/singleapplication_p.h +++ b/external/singleapplication/singleapplication_p.h @@ -32,54 +32,57 @@ #ifndef SINGLEAPPLICATION_P_H #define SINGLEAPPLICATION_P_H +#include "singleapplication.h" #include #include #include -#include "singleapplication.h" -struct InstancesInfo { - bool primary; - quint32 secondary; - qint64 primaryPid; +struct InstancesInfo +{ + bool primary; + quint32 secondary; + qint64 primaryPid; }; -class SingleApplicationPrivate : public QObject { -Q_OBJECT +class SingleApplicationPrivate : public QObject +{ + Q_OBJECT public: - enum ConnectionType : quint8 { - InvalidConnection = 0, - NewInstance = 1, - SecondaryInstance = 2, - Reconnect = 3 - }; - Q_DECLARE_PUBLIC(SingleApplication) + enum ConnectionType : quint8 + { + InvalidConnection = 0, + NewInstance = 1, + SecondaryInstance = 2, + Reconnect = 3 + }; + Q_DECLARE_PUBLIC(SingleApplication) - SingleApplicationPrivate( SingleApplication *q_ptr ); - ~SingleApplicationPrivate(); + SingleApplicationPrivate(SingleApplication* q_ptr); + ~SingleApplicationPrivate(); - void genBlockServerName( int msecs ); - void startPrimary( bool resetMemory ); - void startSecondary(); - void connectToPrimary(int msecs, ConnectionType connectionType ); - qint64 primaryPid(); + void genBlockServerName(int msecs); + void startPrimary(bool resetMemory); + void startSecondary(); + void connectToPrimary(int msecs, ConnectionType connectionType); + qint64 primaryPid(); #ifdef Q_OS_UNIX - void crashHandler(); - static void terminate( int signum ); + void crashHandler(); + static void terminate(int signum); #endif - QSharedMemory *memory; - SingleApplication *q_ptr; - QLocalSocket *socket; - QLocalServer *server; - quint32 instanceNumber; - QString blockServerName; - SingleApplication::Options options; + QSharedMemory* memory; + SingleApplication* q_ptr; + QLocalSocket* socket; + QLocalServer* server; + quint32 instanceNumber; + QString blockServerName; + SingleApplication::Options options; public Q_SLOTS: - void slotConnectionEstablished(); - void slotDataAvailable( QLocalSocket*, quint32 ); - void slotClientConnectionClosed( QLocalSocket*, quint32 ); + void slotConnectionEstablished(); + void slotDataAvailable(QLocalSocket*, quint32); + void slotClientConnectionClosed(QLocalSocket*, quint32); }; #endif // SINGLEAPPLICATION_P_H diff --git a/src/cli/commandargument.cpp b/src/cli/commandargument.cpp index b516ee90..ef7da845 100644 --- a/src/cli/commandargument.cpp +++ b/src/cli/commandargument.cpp @@ -17,38 +17,46 @@ #include "commandargument.h" -CommandArgument::CommandArgument() { +CommandArgument::CommandArgument() {} -} +CommandArgument::CommandArgument(const QString& name, + const QString& description) + : m_name(name) + , m_description(description) +{} -CommandArgument::CommandArgument(const QString &name, - const QString &description) : - m_name(name), m_description(description) +void +CommandArgument::setName(const QString& name) { - + m_name = name; } -void CommandArgument::setName(const QString &name) { - m_name = name; +QString +CommandArgument::name() const +{ + return m_name; } -QString CommandArgument::name() const { - return m_name; +void +CommandArgument::setDescription(const QString& description) +{ + m_description = description; } -void CommandArgument::setDescription(const QString &description) { - m_description = description; +QString +CommandArgument::description() const +{ + return m_description; } -QString CommandArgument::description() const { - return m_description; +bool +CommandArgument::isRoot() const +{ + return m_name.isEmpty() && m_description.isEmpty(); } -bool CommandArgument::isRoot() const { - return m_name.isEmpty() && m_description.isEmpty(); -} - -bool CommandArgument::operator ==(const CommandArgument &arg) const { - return m_description == arg.m_description - && m_name == arg.m_name; +bool +CommandArgument::operator==(const CommandArgument& arg) const +{ + return m_description == arg.m_description && m_name == arg.m_name; } diff --git a/src/cli/commandargument.h b/src/cli/commandargument.h index b8394218..e37f0e24 100644 --- a/src/cli/commandargument.h +++ b/src/cli/commandargument.h @@ -19,22 +19,23 @@ #include -class CommandArgument { +class CommandArgument +{ public: - CommandArgument(); - explicit CommandArgument(const QString &name, const QString &description); + CommandArgument(); + explicit CommandArgument(const QString& name, const QString& description); - void setName(const QString &name); - QString name() const; + void setName(const QString& name); + QString name() const; - void setDescription(const QString &description); - QString description() const; + void setDescription(const QString& description); + QString description() const; - bool isRoot() const; + bool isRoot() const; - bool operator ==(const CommandArgument &arg) const; + bool operator==(const CommandArgument& arg) const; private: - QString m_name; - QString m_description; + QString m_name; + QString m_description; }; diff --git a/src/cli/commandlineparser.cpp b/src/cli/commandlineparser.cpp index 9a0daaf2..7b896aa5 100644 --- a/src/cli/commandlineparser.cpp +++ b/src/cli/commandlineparser.cpp @@ -19,384 +19,405 @@ #include #include -CommandLineParser::CommandLineParser() : - m_description(qApp->applicationName()) -{ - -} +CommandLineParser::CommandLineParser() + : m_description(qApp->applicationName()) +{} namespace { QTextStream out(stdout); QTextStream err(stderr); -auto versionOption = CommandOption({"v", "version"}, - QStringLiteral("Displays version information")); -auto helpOption = CommandOption({"h", "help"}, - QStringLiteral("Displays this help")); +auto versionOption = + CommandOption({ "v", "version" }, + QStringLiteral("Displays version information")); +auto helpOption = + CommandOption({ "h", "help" }, QStringLiteral("Displays this help")); -QString optionsToString(const QList &options, - const QList &arguments) { - int size = 0; // track the largest size - QStringList dashedOptionList; - // save the dashed options and its size in order to print the description - // of every option at the same horizontal character position. - for (auto const &option: options) { - QStringList dashedOptions = option.dashedNames(); - QString joinedDashedOptions = dashedOptions.join(QStringLiteral(", ")); - if (!option.valueName().isEmpty()) { - joinedDashedOptions += QStringLiteral(" <%1>") - .arg(option.valueName()); - } - if (joinedDashedOptions.length() > size) { - size = joinedDashedOptions.length(); - } - dashedOptionList << joinedDashedOptions; +QString +optionsToString(const QList& options, + const QList& arguments) +{ + int size = 0; // track the largest size + QStringList dashedOptionList; + // save the dashed options and its size in order to print the description + // of every option at the same horizontal character position. + for (auto const& option : options) { + QStringList dashedOptions = option.dashedNames(); + QString joinedDashedOptions = dashedOptions.join(QStringLiteral(", ")); + if (!option.valueName().isEmpty()) { + joinedDashedOptions += QStringLiteral(" <%1>").arg(option.valueName()); } - // check the length of the arguments - for (auto const &arg: arguments) { - if(arg.name().length() > size) - size = arg.name().length(); + if (joinedDashedOptions.length() > size) { + size = joinedDashedOptions.length(); } - // generate the text - QString result; - if(!dashedOptionList.isEmpty()) { - result += QLatin1String("Options:\n"); - QString linePadding = QStringLiteral(" ").repeated(size + 4).prepend("\n"); - for (int i = 0; i < options.length(); ++i) { - result += QStringLiteral(" %1 %2\n") - .arg(dashedOptionList.at(i).leftJustified(size, ' ')) - .arg(options.at(i).description() - .replace(QLatin1String("\n"), linePadding)); - } - if (!arguments.isEmpty()) { - result += QLatin1String("\n"); - } + dashedOptionList << joinedDashedOptions; + } + // check the length of the arguments + for (auto const& arg : arguments) { + if (arg.name().length() > size) + size = arg.name().length(); + } + // generate the text + QString result; + if (!dashedOptionList.isEmpty()) { + result += QLatin1String("Options:\n"); + QString linePadding = QStringLiteral(" ").repeated(size + 4).prepend("\n"); + for (int i = 0; i < options.length(); ++i) { + result += QStringLiteral(" %1 %2\n") + .arg(dashedOptionList.at(i).leftJustified(size, ' ')) + .arg(options.at(i).description().replace(QLatin1String("\n"), + linePadding)); } if (!arguments.isEmpty()) { - result += QLatin1String("Arguments:\n"); + result += QLatin1String("\n"); } - for (int i = 0; i < arguments.length(); ++i) { - result += QStringLiteral(" %1 %2\n") + } + if (!arguments.isEmpty()) { + result += QLatin1String("Arguments:\n"); + } + for (int i = 0; i < arguments.length(); ++i) { + result += QStringLiteral(" %1 %2\n") .arg(arguments.at(i).name().leftJustified(size, ' ')) .arg(arguments.at(i).description()); - } - return result; + } + return result; } } // unnamed namespace -bool CommandLineParser::processArgs(const QStringList &args, - QStringList::const_iterator &actualIt, - Node * &actualNode) +bool +CommandLineParser::processArgs(const QStringList& args, + QStringList::const_iterator& actualIt, + Node*& actualNode) { - QString argument = *actualIt; - bool ok = true; - bool isValidArg = false; - for (Node &n: actualNode->subNodes) { - if (n.argument.name() == argument) { - actualNode = &n; - isValidArg = true; - break; - } - } - if (isValidArg) { - auto nextArg = actualNode->argument; - m_foundArgs.append(nextArg); - // check next is help - ++actualIt; - ok = processIfOptionIsHelp(args, actualIt, actualNode); - --actualIt; - } else { - ok = false; - out << QStringLiteral("'%1' is not a valid argument.").arg(argument); + QString argument = *actualIt; + bool ok = true; + bool isValidArg = false; + for (Node& n : actualNode->subNodes) { + if (n.argument.name() == argument) { + actualNode = &n; + isValidArg = true; + break; } + } + if (isValidArg) { + auto nextArg = actualNode->argument; + m_foundArgs.append(nextArg); + // check next is help + ++actualIt; + ok = processIfOptionIsHelp(args, actualIt, actualNode); + --actualIt; + } else { + ok = false; + out << QStringLiteral("'%1' is not a valid argument.").arg(argument); + } + return ok; +} + +bool +CommandLineParser::processOptions(const QStringList& args, + QStringList::const_iterator& actualIt, + Node* const actualNode) +{ + QString arg = *actualIt; + bool ok = true; + // track values + int equalsPos = arg.indexOf(QLatin1String("=")); + QString valueStr; + if (equalsPos != -1) { + valueStr = arg.mid(equalsPos + 1); // right + arg = arg.mid(0, equalsPos); // left + } + // check format -x --xx... + bool isDoubleDashed = arg.startsWith(QLatin1String("--")); + ok = isDoubleDashed ? arg.length() > 3 : arg.length() == 2; + if (!ok) { + out << QStringLiteral("the option %1 has a wrong format.").arg(arg); return ok; -} - -bool CommandLineParser::processOptions(const QStringList &args, - QStringList::const_iterator &actualIt, - Node *const actualNode) -{ - QString arg = *actualIt; - bool ok = true; - // track values - int equalsPos = arg.indexOf(QLatin1String("=")); - QString valueStr; - if (equalsPos != -1) { - valueStr = arg.mid(equalsPos +1); // right - arg = arg.mid(0, equalsPos); // left + } + arg = isDoubleDashed ? arg.remove(0, 2) : arg.remove(0, 1); + // get option + auto endIt = actualNode->options.cend(); + auto optionIt = endIt; + for (auto i = actualNode->options.cbegin(); i != endIt; ++i) { + if ((*i).names().contains(arg)) { + optionIt = i; + break; } - // check format -x --xx... - bool isDoubleDashed = arg.startsWith(QLatin1String("--")); - ok = isDoubleDashed ? arg.length() > 3 : - arg.length() == 2; - if (!ok) { - out << QStringLiteral("the option %1 has a wrong format.").arg(arg); - return ok; - } - arg = isDoubleDashed ? - arg.remove(0, 2) : - arg.remove(0, 1); - // get option - auto endIt = actualNode->options.cend(); - auto optionIt = endIt; - for (auto i = actualNode->options.cbegin(); i != endIt; ++i) { - if ((*i).names().contains(arg)) { - optionIt = i; - break; - } - } - if (optionIt == endIt) { - QString argName = actualNode->argument.name(); - if (argName.isEmpty()) { - argName = qApp->applicationName(); - } - out << QStringLiteral("the option '%1' is not a valid option " - "for the argument '%2'.").arg(arg) - .arg(argName); - ok = false; - return ok; - } - // check presence of values - CommandOption option = *optionIt; - bool requiresValue = !(option.valueName().isEmpty()); - if (!requiresValue && equalsPos != -1) { - out << QStringLiteral("the option '%1' contains a '=' and it doesn't " - "require a value.").arg(arg); - ok = false; - return ok; - } else if (requiresValue && valueStr.isEmpty()) { - // find in the next - if (actualIt+1 != args.cend()) { - ++actualIt; - } else { - out << QStringLiteral("Expected value after the option '%1'.").arg(arg); - ok = false; - return ok; - } - valueStr = *actualIt; - } - // check the value correctness - if (requiresValue) { - ok = option.checkValue(valueStr); - if (!ok) { - QString err = option.errorMsg(); - if (!err.endsWith(QLatin1String("."))) - err += QLatin1String("."); - out << err; - return ok; - } - option.setValue(valueStr); - } - m_foundOptions.append(option); - return ok; -} - -bool CommandLineParser::parse(const QStringList &args) { - m_foundArgs.clear(); - m_foundOptions.clear(); - bool ok = true; - Node *actualNode = &m_parseTree; - auto it = ++args.cbegin(); - // check version option - QStringList dashedVersion = versionOption.dashedNames(); - if (m_withVersion && args.length() > 1 && - dashedVersion.contains(args.at(1))) - { - if (args.length() == 2) { - printVersion(); - m_foundOptions << versionOption; - } else { - out << "Invalid arguments after the version option."; - ok = false; - } - return ok; - - } - // check help option - ok = processIfOptionIsHelp(args, it, actualNode); - // process the other args - for (; it != args.cend() && ok; ++it) { - const QString &value = *it; - if (value.startsWith(QLatin1String("-"))) { - ok = processOptions(args, it, actualNode); - - } else { - ok = processArgs(args, it, actualNode); - } - } - if (!ok && !m_generalErrorMessage.isEmpty()) { - out << QStringLiteral(" %1\n").arg(m_generalErrorMessage); - } - return ok; -} - -CommandOption CommandLineParser::addVersionOption() { - m_withVersion = true; - return versionOption; -} - -CommandOption CommandLineParser::addHelpOption() { - m_withHelp = true; - return helpOption; -} - -bool CommandLineParser::AddArgument(const CommandArgument &arg, - const CommandArgument &parent) -{ - bool res = true; - Node *n = findParent(parent); - if (n == nullptr) { - res = false; - } else { - Node child; - child.argument = arg; - n->subNodes.append(child); - } - return res; -} - -bool CommandLineParser::AddOption(const CommandOption &option, - const CommandArgument &parent) -{ - bool res = true; - Node *n = findParent(parent); - if (n == nullptr) { - res = false; - } else { - n->options.append(option); - } - return res; -} - -bool CommandLineParser::AddOptions(const QList &options, - const CommandArgument &parent) -{ - bool res = true; - for (auto const &option: options) { - if (!AddOption(option, parent)) { - res = false; - break; - } - } - return res; -} - -void CommandLineParser::setGeneralErrorMessage(const QString &msg) { - m_generalErrorMessage = msg; -} - -void CommandLineParser::setDescription(const QString &description) { - m_description = description; -} - -bool CommandLineParser::isSet(const CommandArgument &arg) const { - return m_foundArgs.contains(arg); -} - - -bool CommandLineParser::isSet(const CommandOption &option) const { - return m_foundOptions.contains(option); -} - -QString CommandLineParser::value(const CommandOption &option) const { - QString value = option.value(); - for (const CommandOption &fOption: m_foundOptions) { - if (option == fOption) { - value = fOption.value(); - break; - } - } - return value; -} - -void CommandLineParser::printVersion() { - out << "Flameshot " << qApp->applicationVersion() << "\nCompiled with Qt " - << static_cast(QT_VERSION_STR) << "\n"; -} - -void CommandLineParser::printHelp(QStringList args, const Node *node) { - args.removeLast(); // remove the help, it's always the last - QString helpText; - // add usage info - QString argName = node->argument.name(); + } + if (optionIt == endIt) { + QString argName = actualNode->argument.name(); if (argName.isEmpty()) { - argName = qApp->applicationName(); + argName = qApp->applicationName(); } - QString argText = node->subNodes.isEmpty() ? "" : "[arguments]"; - helpText += QStringLiteral("Usage: %1 [%2-options] %3\n\n") - .arg(args.join(QStringLiteral(" "))) - .arg(argName).arg(argText); - // add command options and subarguments - QList subArgs; - for (const Node &n: node->subNodes) - subArgs.append(n.argument); - auto modifiedOptions = node->options; - if (m_withHelp) - modifiedOptions << helpOption; - if (m_withVersion && node == &m_parseTree) { - modifiedOptions << versionOption; - } - helpText += optionsToString(modifiedOptions, subArgs); - // print it - out << helpText; -} - -CommandLineParser::Node* CommandLineParser::findParent( - const CommandArgument &parent) -{ - if (parent == CommandArgument()) { - return &m_parseTree; - } - //find the parent in the subNodes recursively - Node *res = nullptr; - for (auto i = m_parseTree.subNodes.begin(); - i != m_parseTree.subNodes.end(); ++i) - { - res = recursiveParentSearch(parent, *i); - if (res != nullptr) { - break; - } - } - return res; -} - -CommandLineParser::Node* CommandLineParser::recursiveParentSearch( - const CommandArgument &parent, Node &node) const -{ - Node * res = nullptr; - if (node.argument == parent) { - res = &node; + out << QStringLiteral("the option '%1' is not a valid option " + "for the argument '%2'.") + .arg(arg) + .arg(argName); + ok = false; + return ok; + } + // check presence of values + CommandOption option = *optionIt; + bool requiresValue = !(option.valueName().isEmpty()); + if (!requiresValue && equalsPos != -1) { + out << QStringLiteral("the option '%1' contains a '=' and it doesn't " + "require a value.") + .arg(arg); + ok = false; + return ok; + } else if (requiresValue && valueStr.isEmpty()) { + // find in the next + if (actualIt + 1 != args.cend()) { + ++actualIt; } else { - for (auto i = node.subNodes.begin(); i != node.subNodes.end(); ++i){ - res = recursiveParentSearch(parent, *i); - if (res != nullptr) { - break; - } - } + out << QStringLiteral("Expected value after the option '%1'.").arg(arg); + ok = false; + return ok; } - return res; + valueStr = *actualIt; + } + // check the value correctness + if (requiresValue) { + ok = option.checkValue(valueStr); + if (!ok) { + QString err = option.errorMsg(); + if (!err.endsWith(QLatin1String("."))) + err += QLatin1String("."); + out << err; + return ok; + } + option.setValue(valueStr); + } + m_foundOptions.append(option); + return ok; } -bool CommandLineParser::processIfOptionIsHelp( - const QStringList &args, - QStringList::const_iterator &actualIt, - Node * &actualNode) +bool +CommandLineParser::parse(const QStringList& args) { - bool ok = true; - auto dashedHelpNames = helpOption.dashedNames(); - if (m_withHelp && actualIt != args.cend() && - dashedHelpNames.contains(*actualIt)) - { - if (actualIt+1 == args.cend()) { - m_foundOptions << helpOption; - printHelp(args, actualNode); - actualIt++; - } else { - out << "Invalid arguments after the help option."; - ok = false; - } + m_foundArgs.clear(); + m_foundOptions.clear(); + bool ok = true; + Node* actualNode = &m_parseTree; + auto it = ++args.cbegin(); + // check version option + QStringList dashedVersion = versionOption.dashedNames(); + if (m_withVersion && args.length() > 1 && + dashedVersion.contains(args.at(1))) { + if (args.length() == 2) { + printVersion(); + m_foundOptions << versionOption; + } else { + out << "Invalid arguments after the version option."; + ok = false; } return ok; + } + // check help option + ok = processIfOptionIsHelp(args, it, actualNode); + // process the other args + for (; it != args.cend() && ok; ++it) { + const QString& value = *it; + if (value.startsWith(QLatin1String("-"))) { + ok = processOptions(args, it, actualNode); + + } else { + ok = processArgs(args, it, actualNode); + } + } + if (!ok && !m_generalErrorMessage.isEmpty()) { + out << QStringLiteral(" %1\n").arg(m_generalErrorMessage); + } + return ok; +} + +CommandOption +CommandLineParser::addVersionOption() +{ + m_withVersion = true; + return versionOption; +} + +CommandOption +CommandLineParser::addHelpOption() +{ + m_withHelp = true; + return helpOption; +} + +bool +CommandLineParser::AddArgument(const CommandArgument& arg, + const CommandArgument& parent) +{ + bool res = true; + Node* n = findParent(parent); + if (n == nullptr) { + res = false; + } else { + Node child; + child.argument = arg; + n->subNodes.append(child); + } + return res; +} + +bool +CommandLineParser::AddOption(const CommandOption& option, + const CommandArgument& parent) +{ + bool res = true; + Node* n = findParent(parent); + if (n == nullptr) { + res = false; + } else { + n->options.append(option); + } + return res; +} + +bool +CommandLineParser::AddOptions(const QList& options, + const CommandArgument& parent) +{ + bool res = true; + for (auto const& option : options) { + if (!AddOption(option, parent)) { + res = false; + break; + } + } + return res; +} + +void +CommandLineParser::setGeneralErrorMessage(const QString& msg) +{ + m_generalErrorMessage = msg; +} + +void +CommandLineParser::setDescription(const QString& description) +{ + m_description = description; +} + +bool +CommandLineParser::isSet(const CommandArgument& arg) const +{ + return m_foundArgs.contains(arg); +} + +bool +CommandLineParser::isSet(const CommandOption& option) const +{ + return m_foundOptions.contains(option); +} + +QString +CommandLineParser::value(const CommandOption& option) const +{ + QString value = option.value(); + for (const CommandOption& fOption : m_foundOptions) { + if (option == fOption) { + value = fOption.value(); + break; + } + } + return value; +} + +void +CommandLineParser::printVersion() +{ + out << "Flameshot " << qApp->applicationVersion() << "\nCompiled with Qt " + << static_cast(QT_VERSION_STR) << "\n"; +} + +void +CommandLineParser::printHelp(QStringList args, const Node* node) +{ + args.removeLast(); // remove the help, it's always the last + QString helpText; + // add usage info + QString argName = node->argument.name(); + if (argName.isEmpty()) { + argName = qApp->applicationName(); + } + QString argText = node->subNodes.isEmpty() ? "" : "[arguments]"; + helpText += QStringLiteral("Usage: %1 [%2-options] %3\n\n") + .arg(args.join(QStringLiteral(" "))) + .arg(argName) + .arg(argText); + // add command options and subarguments + QList subArgs; + for (const Node& n : node->subNodes) + subArgs.append(n.argument); + auto modifiedOptions = node->options; + if (m_withHelp) + modifiedOptions << helpOption; + if (m_withVersion && node == &m_parseTree) { + modifiedOptions << versionOption; + } + helpText += optionsToString(modifiedOptions, subArgs); + // print it + out << helpText; +} + +CommandLineParser::Node* +CommandLineParser::findParent(const CommandArgument& parent) +{ + if (parent == CommandArgument()) { + return &m_parseTree; + } + // find the parent in the subNodes recursively + Node* res = nullptr; + for (auto i = m_parseTree.subNodes.begin(); i != m_parseTree.subNodes.end(); + ++i) { + res = recursiveParentSearch(parent, *i); + if (res != nullptr) { + break; + } + } + return res; +} + +CommandLineParser::Node* +CommandLineParser::recursiveParentSearch(const CommandArgument& parent, + Node& node) const +{ + Node* res = nullptr; + if (node.argument == parent) { + res = &node; + } else { + for (auto i = node.subNodes.begin(); i != node.subNodes.end(); ++i) { + res = recursiveParentSearch(parent, *i); + if (res != nullptr) { + break; + } + } + } + return res; +} + +bool +CommandLineParser::processIfOptionIsHelp(const QStringList& args, + QStringList::const_iterator& actualIt, + Node*& actualNode) +{ + bool ok = true; + auto dashedHelpNames = helpOption.dashedNames(); + if (m_withHelp && actualIt != args.cend() && + dashedHelpNames.contains(*actualIt)) { + if (actualIt + 1 == args.cend()) { + m_foundOptions << helpOption; + printHelp(args, actualNode); + actualIt++; + } else { + out << "Invalid arguments after the help option."; + ok = false; + } + } + return ok; } diff --git a/src/cli/commandlineparser.h b/src/cli/commandlineparser.h index dc2306ce..1635edbe 100644 --- a/src/cli/commandlineparser.h +++ b/src/cli/commandlineparser.h @@ -21,69 +21,72 @@ #include "src/cli/commandoption.h" #include -class CommandLineParser { +class CommandLineParser +{ public: - CommandLineParser(); + CommandLineParser(); - bool parse(const QStringList &args); + bool parse(const QStringList& args); - CommandArgument rootArgument() const { return CommandArgument(); } + CommandArgument rootArgument() const { return CommandArgument(); } - CommandOption addVersionOption(); - CommandOption addHelpOption(); + CommandOption addVersionOption(); + CommandOption addHelpOption(); - bool AddArgument(const CommandArgument &arg, - const CommandArgument &parent = CommandArgument()); + bool AddArgument(const CommandArgument& arg, + const CommandArgument& parent = CommandArgument()); - bool AddOption(const CommandOption &option, - const CommandArgument &parent = CommandArgument()); + bool AddOption(const CommandOption& option, + const CommandArgument& parent = CommandArgument()); - bool AddOptions(const QList &options, - const CommandArgument &parent = CommandArgument()); + bool AddOptions(const QList& options, + const CommandArgument& parent = CommandArgument()); - void setGeneralErrorMessage(const QString &msg); - void setDescription(const QString &description); + void setGeneralErrorMessage(const QString& msg); + void setDescription(const QString& description); - bool isSet(const CommandArgument &arg) const; - bool isSet(const CommandOption &option) const; - QString value(const CommandOption &option) const; + bool isSet(const CommandArgument& arg) const; + bool isSet(const CommandOption& option) const; + QString value(const CommandOption& option) const; private: - bool m_withHelp = false; - bool m_withVersion = false; - QString m_description; - QString m_generalErrorMessage; + bool m_withHelp = false; + bool m_withVersion = false; + QString m_description; + QString m_generalErrorMessage; - struct Node { - explicit Node(const CommandArgument &arg) : argument(arg) {} - Node() {} - bool operator==(const Node &n) const { - return argument == n.argument && - options == n.options && - subNodes == n.subNodes; - } - CommandArgument argument; - QList options; - QList subNodes; - }; + struct Node + { + explicit Node(const CommandArgument& arg) + : argument(arg) + {} + Node() {} + bool operator==(const Node& n) const + { + return argument == n.argument && options == n.options && + subNodes == n.subNodes; + } + CommandArgument argument; + QList options; + QList subNodes; + }; - Node m_parseTree; - QList m_foundOptions; - QList m_foundArgs; + Node m_parseTree; + QList m_foundOptions; + QList m_foundArgs; - // helper functions - void printVersion(); - void printHelp(QStringList args, const Node *node); - Node* findParent(const CommandArgument &parent); - Node* recursiveParentSearch(const CommandArgument &parent, - Node &node) const; - bool processIfOptionIsHelp(const QStringList &args, - QStringList::const_iterator &actualIt, - Node * &actualNode); - bool processArgs(const QStringList &args, - QStringList::const_iterator &actualIt, - Node * &actualNode); - bool processOptions(const QStringList &args, - QStringList::const_iterator &actualIt, - Node *const actualNode); + // helper functions + void printVersion(); + void printHelp(QStringList args, const Node* node); + Node* findParent(const CommandArgument& parent); + Node* recursiveParentSearch(const CommandArgument& parent, Node& node) const; + bool processIfOptionIsHelp(const QStringList& args, + QStringList::const_iterator& actualIt, + Node*& actualNode); + bool processArgs(const QStringList& args, + QStringList::const_iterator& actualIt, + Node*& actualNode); + bool processOptions(const QStringList& args, + QStringList::const_iterator& actualIt, + Node* const actualNode); }; diff --git a/src/cli/commandoption.cpp b/src/cli/commandoption.cpp index a0877fad..ba7d9339 100644 --- a/src/cli/commandoption.cpp +++ b/src/cli/commandoption.cpp @@ -17,96 +17,124 @@ #include "commandoption.h" -CommandOption::CommandOption(const QString &name, const QString &description, - const QString &valueName, - const QString &defaultValue) : - m_names(name), m_description(description), m_valueName(valueName), - m_value(defaultValue) +CommandOption::CommandOption(const QString& name, + const QString& description, + const QString& valueName, + const QString& defaultValue) + : m_names(name) + , m_description(description) + , m_valueName(valueName) + , m_value(defaultValue) { - m_checker = [](QString const&){ return true; }; + m_checker = [](QString const&) { return true; }; } -CommandOption::CommandOption(const QStringList &names, - const QString &description, - const QString &valueName, - const QString &defaultValue) : - m_names(names), m_description(description), m_valueName(valueName), - m_value(defaultValue) +CommandOption::CommandOption(const QStringList& names, + const QString& description, + const QString& valueName, + const QString& defaultValue) + : m_names(names) + , m_description(description) + , m_valueName(valueName) + , m_value(defaultValue) { - m_checker = [](QString const&) -> bool { return true; }; + m_checker = [](QString const&) -> bool { return true; }; } -void CommandOption::setName(const QString &name) { - m_names = QStringList() << name; -} - -void CommandOption::setNames(const QStringList &names) { - m_names = names; -} - -QStringList CommandOption::names() const { - return m_names; -} - -QStringList CommandOption::dashedNames() const { - QStringList dashedNames; - for (const QString &name: m_names) { - // prepend "-" to single character options, and "--" to the others - QString dashedName = (name.length() == 1) ? - QStringLiteral("-%1").arg(name) : - QStringLiteral("--%1").arg(name); - dashedNames << dashedName; - } - return dashedNames; -} - -void CommandOption::setValueName(const QString &name) { - m_valueName = name; -} - -QString CommandOption::valueName() const { - return m_valueName; -} - -void CommandOption::setValue(const QString &value) { - if (m_valueName.isEmpty()) { - m_valueName = QLatin1String("value"); - } - m_value = value; -} - -QString CommandOption::value() const { - return m_value; -} - -void CommandOption::addChecker(const function checker, - const QString &errMsg) +void +CommandOption::setName(const QString& name) { - m_checker = checker; - m_errorMsg = errMsg; + m_names = QStringList() << name; } -bool CommandOption::checkValue(const QString &value) const { - return m_checker(value); -} - -QString CommandOption::description() const +void +CommandOption::setNames(const QStringList& names) { - return m_description; + m_names = names; } -void CommandOption::setDescription(const QString &description) +QStringList +CommandOption::names() const { - m_description = description; + return m_names; } -QString CommandOption::errorMsg() const { - return m_errorMsg; -} - -bool CommandOption::operator ==(const CommandOption &option) const +QStringList +CommandOption::dashedNames() const { - return m_description == option.m_description - && m_names == option.m_names - && m_valueName == option.m_valueName; + QStringList dashedNames; + for (const QString& name : m_names) { + // prepend "-" to single character options, and "--" to the others + QString dashedName = (name.length() == 1) + ? QStringLiteral("-%1").arg(name) + : QStringLiteral("--%1").arg(name); + dashedNames << dashedName; + } + return dashedNames; +} + +void +CommandOption::setValueName(const QString& name) +{ + m_valueName = name; +} + +QString +CommandOption::valueName() const +{ + return m_valueName; +} + +void +CommandOption::setValue(const QString& value) +{ + if (m_valueName.isEmpty()) { + m_valueName = QLatin1String("value"); + } + m_value = value; +} + +QString +CommandOption::value() const +{ + return m_value; +} + +void +CommandOption::addChecker(const function checker, + const QString& errMsg) +{ + m_checker = checker; + m_errorMsg = errMsg; +} + +bool +CommandOption::checkValue(const QString& value) const +{ + return m_checker(value); +} + +QString +CommandOption::description() const +{ + return m_description; +} + +void +CommandOption::setDescription(const QString& description) +{ + m_description = description; +} + +QString +CommandOption::errorMsg() const +{ + return m_errorMsg; +} + +bool +CommandOption::operator==(const CommandOption& option) const +{ + return m_description == option.m_description && m_names == option.m_names && + m_valueName == option.m_valueName; } diff --git a/src/cli/commandoption.h b/src/cli/commandoption.h index d73e5ec5..efcc388a 100644 --- a/src/cli/commandoption.h +++ b/src/cli/commandoption.h @@ -22,43 +22,47 @@ using std::function; -class CommandOption { +class CommandOption +{ public: - CommandOption(const QString &name, const QString &description, - const QString &valueName = QString(), - const QString &defaultValue = QString()); + CommandOption(const QString& name, + const QString& description, + const QString& valueName = QString(), + const QString& defaultValue = QString()); - CommandOption(const QStringList &names, const QString &description, - const QString &valueName = QString(), - const QString &defaultValue = QString()); + CommandOption(const QStringList& names, + const QString& description, + const QString& valueName = QString(), + const QString& defaultValue = QString()); - void setName(const QString &name); - void setNames(const QStringList &names); - QStringList names() const; - QStringList dashedNames() const; + void setName(const QString& name); + void setNames(const QStringList& names); + QStringList names() const; + QStringList dashedNames() const; - void setValueName(const QString &name); - QString valueName() const; + void setValueName(const QString& name); + QString valueName() const; - void setValue(const QString &value); - QString value() const; + void setValue(const QString& value); + QString value() const; - void addChecker(const function checker, const QString &errMsg); - bool checkValue(const QString &value) const; + void addChecker(const function checker, + const QString& errMsg); + bool checkValue(const QString& value) const; - QString description() const; - void setDescription(const QString &description); + QString description() const; + void setDescription(const QString& description); - QString errorMsg() const; + QString errorMsg() const; - bool operator==(const CommandOption &option) const; + bool operator==(const CommandOption& option) const; private: - QStringList m_names; - QString m_description; - QString m_valueName; - QString m_value; + QStringList m_names; + QString m_description; + QString m_valueName; + QString m_value; - function m_checker; - QString m_errorMsg; + function m_checker; + QString m_errorMsg; }; diff --git a/src/config/buttonlistview.cpp b/src/config/buttonlistview.cpp index 277c176b..11b6ca94 100644 --- a/src/config/buttonlistview.cpp +++ b/src/config/buttonlistview.cpp @@ -21,85 +21,97 @@ #include #include -ButtonListView::ButtonListView(QWidget *parent) : QListWidget(parent) { - setMouseTracking(true); - setFlow(QListWidget::TopToBottom); - initButtonList(); - updateComponents(); - connect(this, &QListWidget::itemClicked, this, - &ButtonListView::reverseItemCheck); +ButtonListView::ButtonListView(QWidget* parent) + : QListWidget(parent) +{ + setMouseTracking(true); + setFlow(QListWidget::TopToBottom); + initButtonList(); + updateComponents(); + connect( + this, &QListWidget::itemClicked, this, &ButtonListView::reverseItemCheck); } -void ButtonListView::initButtonList() { - ToolFactory factory; - auto listTypes = CaptureButton::getIterableButtonTypes(); +void +ButtonListView::initButtonList() +{ + ToolFactory factory; + auto listTypes = CaptureButton::getIterableButtonTypes(); - for (const CaptureButton::ButtonType t: listTypes) { - CaptureTool *tool = factory.CreateTool(t); + for (const CaptureButton::ButtonType t : listTypes) { + CaptureTool* tool = factory.CreateTool(t); - // add element to the local map - m_buttonTypeByName.insert(tool->name(), t); + // add element to the local map + m_buttonTypeByName.insert(tool->name(), t); - // init the menu option - QListWidgetItem *m_buttonItem = new QListWidgetItem(this); + // init the menu option + QListWidgetItem* m_buttonItem = new QListWidgetItem(this); - // when the background is lighter than gray, it uses the white icons - QColor bgColor = this->palette().color(QWidget::backgroundRole()); - m_buttonItem->setIcon(tool->icon(bgColor, false)); + // when the background is lighter than gray, it uses the white icons + QColor bgColor = this->palette().color(QWidget::backgroundRole()); + m_buttonItem->setIcon(tool->icon(bgColor, false)); - m_buttonItem->setFlags(Qt::ItemIsUserCheckable); - QColor foregroundColor = this->palette().color(QWidget::foregroundRole()); - m_buttonItem->setForeground(foregroundColor); + m_buttonItem->setFlags(Qt::ItemIsUserCheckable); + QColor foregroundColor = this->palette().color(QWidget::foregroundRole()); + m_buttonItem->setForeground(foregroundColor); - m_buttonItem->setText(tool->name()); - m_buttonItem->setToolTip(tool->description()); - tool->deleteLater(); - } + m_buttonItem->setText(tool->name()); + m_buttonItem->setToolTip(tool->description()); + tool->deleteLater(); + } } -void ButtonListView::updateActiveButtons(QListWidgetItem *item) { - CaptureButton::ButtonType bType = m_buttonTypeByName[item->text()]; - if (item->checkState() == Qt::Checked) { - m_listButtons.append(bType); - // TODO refactor so we don't need external sorts - using bt = CaptureButton::ButtonType; - std::sort(m_listButtons.begin(), m_listButtons.end(), [](bt a, bt b){ - return CaptureButton::getPriorityByButton(a) < - CaptureButton::getPriorityByButton(b); - }); +void +ButtonListView::updateActiveButtons(QListWidgetItem* item) +{ + CaptureButton::ButtonType bType = m_buttonTypeByName[item->text()]; + if (item->checkState() == Qt::Checked) { + m_listButtons.append(bType); + // TODO refactor so we don't need external sorts + using bt = CaptureButton::ButtonType; + std::sort(m_listButtons.begin(), m_listButtons.end(), [](bt a, bt b) { + return CaptureButton::getPriorityByButton(a) < + CaptureButton::getPriorityByButton(b); + }); + } else { + m_listButtons.remove(m_listButtons.indexOf(bType)); + } + ConfigHandler().setButtons(m_listButtons); +} + +void +ButtonListView::reverseItemCheck(QListWidgetItem* item) +{ + if (item->checkState() == Qt::Checked) { + item->setCheckState(Qt::Unchecked); + } else { + item->setCheckState(Qt::Checked); + } + updateActiveButtons(item); +} + +void +ButtonListView::selectAll() +{ + ConfigHandler().setAllTheButtons(); + for (int i = 0; i < this->count(); ++i) { + QListWidgetItem* item = this->item(i); + item->setCheckState(Qt::Checked); + } +} + +void +ButtonListView::updateComponents() +{ + m_listButtons = ConfigHandler().getButtons(); + auto listTypes = CaptureButton::getIterableButtonTypes(); + for (int i = 0; i < this->count(); ++i) { + QListWidgetItem* item = this->item(i); + auto elem = static_cast(listTypes.at(i)); + if (m_listButtons.contains(elem)) { + item->setCheckState(Qt::Checked); } else { - m_listButtons.remove(m_listButtons.indexOf(bType)); - } - ConfigHandler().setButtons(m_listButtons); -} - -void ButtonListView::reverseItemCheck(QListWidgetItem *item){ - if (item->checkState() == Qt::Checked) { - item->setCheckState(Qt::Unchecked); - } else { - item->setCheckState(Qt::Checked); - } - updateActiveButtons(item); -} - -void ButtonListView::selectAll() { - ConfigHandler().setAllTheButtons(); - for(int i = 0; i < this->count(); ++i) { - QListWidgetItem* item = this->item(i); - item->setCheckState(Qt::Checked); - } -} - -void ButtonListView::updateComponents() { - m_listButtons = ConfigHandler().getButtons(); - auto listTypes = CaptureButton::getIterableButtonTypes(); - for(int i = 0; i < this->count(); ++i) { - QListWidgetItem* item = this->item(i); - auto elem = static_cast(listTypes.at(i)); - if (m_listButtons.contains(elem)) { - item->setCheckState(Qt::Checked); - } else { - item->setCheckState(Qt::Unchecked); - } + item->setCheckState(Qt::Unchecked); } + } } diff --git a/src/config/buttonlistview.h b/src/config/buttonlistview.h index 8449d85f..a80944df 100644 --- a/src/config/buttonlistview.h +++ b/src/config/buttonlistview.h @@ -20,23 +20,24 @@ #include "src/widgets/capture/capturebutton.h" #include -class ButtonListView : public QListWidget { +class ButtonListView : public QListWidget +{ public: - explicit ButtonListView(QWidget *parent= nullptr); + explicit ButtonListView(QWidget* parent = nullptr); public slots: - void selectAll(); - void updateComponents(); + void selectAll(); + void updateComponents(); private slots: - void reverseItemCheck(QListWidgetItem *); + void reverseItemCheck(QListWidgetItem*); protected: - void initButtonList(); + void initButtonList(); private: - QVector m_listButtons; - QMap m_buttonTypeByName; + QVector m_listButtons; + QMap m_buttonTypeByName; - void updateActiveButtons(QListWidgetItem *); + void updateActiveButtons(QListWidgetItem*); }; diff --git a/src/config/clickablelabel.cpp b/src/config/clickablelabel.cpp index 75bd146c..5702a702 100644 --- a/src/config/clickablelabel.cpp +++ b/src/config/clickablelabel.cpp @@ -17,14 +17,18 @@ #include "clickablelabel.h" -ClickableLabel::ClickableLabel(QWidget *parent) : QLabel(parent) { +ClickableLabel::ClickableLabel(QWidget* parent) + : QLabel(parent) +{} +ClickableLabel::ClickableLabel(QString s, QWidget* parent) + : QLabel(parent) +{ + setText(s); } -ClickableLabel::ClickableLabel(QString s, QWidget *parent) : QLabel(parent) { - setText(s); -} - -void ClickableLabel::mousePressEvent(QMouseEvent *) { - emit clicked(); +void +ClickableLabel::mousePressEvent(QMouseEvent*) +{ + emit clicked(); } diff --git a/src/config/clickablelabel.h b/src/config/clickablelabel.h index 3431ee5a..5042e0f3 100644 --- a/src/config/clickablelabel.h +++ b/src/config/clickablelabel.h @@ -19,15 +19,16 @@ #include -class ClickableLabel : public QLabel { - Q_OBJECT +class ClickableLabel : public QLabel +{ + Q_OBJECT public: - explicit ClickableLabel(QWidget *parent = nullptr); - ClickableLabel(QString s, QWidget *parent = nullptr); + explicit ClickableLabel(QWidget* parent = nullptr); + ClickableLabel(QString s, QWidget* parent = nullptr); signals: - void clicked(); + void clicked(); private: - void mousePressEvent (QMouseEvent *); + void mousePressEvent(QMouseEvent*); }; diff --git a/src/config/configwindow.cpp b/src/config/configwindow.cpp index 665bef8a..a5ee86ad 100644 --- a/src/config/configwindow.cpp +++ b/src/config/configwindow.cpp @@ -16,73 +16,81 @@ // along with Flameshot. If not, see . #include "configwindow.h" -#include "src/utils/colorutils.h" -#include "src/utils/confighandler.h" -#include "src/utils/pathinfo.h" -#include "src/widgets/capture/capturebutton.h" -#include "src/config/geneneralconf.h" #include "src/config/filenameeditor.h" +#include "src/config/geneneralconf.h" #include "src/config/strftimechooserwidget.h" #include "src/config/visualseditor.h" +#include "src/utils/colorutils.h" +#include "src/utils/confighandler.h" #include "src/utils/globalvalues.h" -#include -#include -#include -#include +#include "src/utils/pathinfo.h" +#include "src/widgets/capture/capturebutton.h" #include +#include +#include +#include +#include // ConfigWindow contains the menus where you can configure the application -ConfigWindow::ConfigWindow(QWidget *parent) : QTabWidget(parent) { - setAttribute(Qt::WA_DeleteOnClose); - const int size = GlobalValues::buttonBaseSize() * 12; - setMinimumSize(size, size); - setWindowIcon(QIcon(":img/app/flameshot.svg")); - setWindowTitle(tr("Configuration")); +ConfigWindow::ConfigWindow(QWidget* parent) + : QTabWidget(parent) +{ + setAttribute(Qt::WA_DeleteOnClose); + const int size = GlobalValues::buttonBaseSize() * 12; + setMinimumSize(size, size); + setWindowIcon(QIcon(":img/app/flameshot.svg")); + setWindowTitle(tr("Configuration")); - auto changedSlot = [this](QString s){ - QStringList files = m_configWatcher->files(); - if (!files.contains(s)) { - this->m_configWatcher->addPath(s); - } - emit updateChildren(); - }; - m_configWatcher = new QFileSystemWatcher(this); - m_configWatcher->addPath(ConfigHandler().configFilePath()); - connect(m_configWatcher, &QFileSystemWatcher::fileChanged, - this, changedSlot); - - QColor background = this->palette().window().color(); - bool isDark = ColorUtils::colorIsDark(background); - QString modifier = isDark ? PathInfo::whiteIconPath() : - PathInfo::blackIconPath(); - - // visuals - m_visuals = new VisualsEditor(); - addTab(m_visuals, QIcon(modifier + "graphics.svg"), - tr("Interface")); - - // filename - m_filenameEditor = new FileNameEditor(); - addTab(m_filenameEditor, QIcon(modifier + "name_edition.svg"), - tr("Filename Editor")); - - // general - m_generalConfig = new GeneneralConf(); - addTab(m_generalConfig, QIcon(modifier + "config.svg"), - tr("General")); - - // connect update sigslots - connect(this, &ConfigWindow::updateChildren, - m_filenameEditor, &FileNameEditor::updateComponents); - connect(this, &ConfigWindow::updateChildren, - m_visuals, &VisualsEditor::updateComponents); - connect(this, &ConfigWindow::updateChildren, - m_generalConfig, &GeneneralConf::updateComponents); -} - -void ConfigWindow::keyPressEvent(QKeyEvent *e) { - if (e->key() == Qt::Key_Escape) { - close(); + auto changedSlot = [this](QString s) { + QStringList files = m_configWatcher->files(); + if (!files.contains(s)) { + this->m_configWatcher->addPath(s); } + emit updateChildren(); + }; + m_configWatcher = new QFileSystemWatcher(this); + m_configWatcher->addPath(ConfigHandler().configFilePath()); + connect(m_configWatcher, &QFileSystemWatcher::fileChanged, this, changedSlot); + + QColor background = this->palette().window().color(); + bool isDark = ColorUtils::colorIsDark(background); + QString modifier = + isDark ? PathInfo::whiteIconPath() : PathInfo::blackIconPath(); + + // visuals + m_visuals = new VisualsEditor(); + addTab(m_visuals, QIcon(modifier + "graphics.svg"), tr("Interface")); + + // filename + m_filenameEditor = new FileNameEditor(); + addTab(m_filenameEditor, + QIcon(modifier + "name_edition.svg"), + tr("Filename Editor")); + + // general + m_generalConfig = new GeneneralConf(); + addTab(m_generalConfig, QIcon(modifier + "config.svg"), tr("General")); + + // connect update sigslots + connect(this, + &ConfigWindow::updateChildren, + m_filenameEditor, + &FileNameEditor::updateComponents); + connect(this, + &ConfigWindow::updateChildren, + m_visuals, + &VisualsEditor::updateComponents); + connect(this, + &ConfigWindow::updateChildren, + m_generalConfig, + &GeneneralConf::updateComponents); +} + +void +ConfigWindow::keyPressEvent(QKeyEvent* e) +{ + if (e->key() == Qt::Key_Escape) { + close(); + } } diff --git a/src/config/configwindow.h b/src/config/configwindow.h index f7671fb0..979e1a72 100644 --- a/src/config/configwindow.h +++ b/src/config/configwindow.h @@ -24,20 +24,21 @@ class GeneneralConf; class QFileSystemWatcher; class VisualsEditor; -class ConfigWindow : public QTabWidget { - Q_OBJECT +class ConfigWindow : public QTabWidget +{ + Q_OBJECT public: - explicit ConfigWindow(QWidget *parent = nullptr); + explicit ConfigWindow(QWidget* parent = nullptr); signals: - void updateChildren(); + void updateChildren(); protected: - void keyPressEvent(QKeyEvent *); + void keyPressEvent(QKeyEvent*); private: - FileNameEditor *m_filenameEditor; - GeneneralConf *m_generalConfig; - VisualsEditor *m_visuals; - QFileSystemWatcher *m_configWatcher; + FileNameEditor* m_filenameEditor; + GeneneralConf* m_generalConfig; + VisualsEditor* m_visuals; + QFileSystemWatcher* m_configWatcher; }; diff --git a/src/config/extendedslider.cpp b/src/config/extendedslider.cpp index b7e7ac05..124d1bf3 100644 --- a/src/config/extendedslider.cpp +++ b/src/config/extendedslider.cpp @@ -17,34 +17,41 @@ #include "extendedslider.h" -ExtendedSlider::ExtendedSlider(QWidget *parent) - : QSlider(parent) +ExtendedSlider::ExtendedSlider(QWidget* parent) + : QSlider(parent) { - connect(this, &ExtendedSlider::valueChanged, - this, &ExtendedSlider::updateTooltip); - connect(this, &ExtendedSlider::sliderMoved, - this, &ExtendedSlider::fireTimer); - m_timer.setSingleShot(true); - connect(&m_timer, &QTimer::timeout, - this, &ExtendedSlider::modificationsEnded); + connect( + this, &ExtendedSlider::valueChanged, this, &ExtendedSlider::updateTooltip); + connect(this, &ExtendedSlider::sliderMoved, this, &ExtendedSlider::fireTimer); + m_timer.setSingleShot(true); + connect( + &m_timer, &QTimer::timeout, this, &ExtendedSlider::modificationsEnded); } -int ExtendedSlider::mappedValue(int min, int max) { - qreal progress = - ((value() - minimum())) / static_cast(maximum() - minimum()); - return min + (max - min) * progress; +int +ExtendedSlider::mappedValue(int min, int max) +{ + qreal progress = + ((value() - minimum())) / static_cast(maximum() - minimum()); + return min + (max - min) * progress; } -void ExtendedSlider::setMapedValue(int min, int val, int max) { - qreal progress = ((val - min) + 1) / static_cast(max - min); - int value = minimum() + (maximum() - minimum()) * progress; - setValue(value); +void +ExtendedSlider::setMapedValue(int min, int val, int max) +{ + qreal progress = ((val - min) + 1) / static_cast(max - min); + int value = minimum() + (maximum() - minimum()) * progress; + setValue(value); } -void ExtendedSlider::updateTooltip() { - setToolTip(QString::number(value())+"%"); +void +ExtendedSlider::updateTooltip() +{ + setToolTip(QString::number(value()) + "%"); } -void ExtendedSlider::fireTimer() { - m_timer.start(500); +void +ExtendedSlider::fireTimer() +{ + m_timer.start(500); } diff --git a/src/config/extendedslider.h b/src/config/extendedslider.h index 9b0f5627..7ef22f13 100644 --- a/src/config/extendedslider.h +++ b/src/config/extendedslider.h @@ -20,21 +20,22 @@ #include #include -class ExtendedSlider : public QSlider { - Q_OBJECT +class ExtendedSlider : public QSlider +{ + Q_OBJECT public: - explicit ExtendedSlider(QWidget *parent = nullptr); + explicit ExtendedSlider(QWidget* parent = nullptr); - int mappedValue(int min, int max); - void setMapedValue(int min, int val, int max); + int mappedValue(int min, int max); + void setMapedValue(int min, int val, int max); signals: - void modificationsEnded(); + void modificationsEnded(); private slots: - void updateTooltip(); - void fireTimer(); + void updateTooltip(); + void fireTimer(); private: - QTimer m_timer; + QTimer m_timer; }; diff --git a/src/config/filenameeditor.cpp b/src/config/filenameeditor.cpp index a6c0aa11..d3bae1a6 100644 --- a/src/config/filenameeditor.cpp +++ b/src/config/filenameeditor.cpp @@ -16,100 +16,122 @@ // along with Flameshot. If not, see . #include "filenameeditor.h" -#include "src/utils/filenamehandler.h" -#include "src/utils/confighandler.h" #include "src/config/strftimechooserwidget.h" -#include +#include "src/utils/confighandler.h" +#include "src/utils/filenamehandler.h" #include -#include #include +#include #include +#include -FileNameEditor::FileNameEditor(QWidget *parent) : QWidget(parent) { - initWidgets(); - initLayout(); +FileNameEditor::FileNameEditor(QWidget* parent) + : QWidget(parent) +{ + initWidgets(); + initLayout(); } -void FileNameEditor::initLayout() { - m_layout = new QVBoxLayout(this); - auto infoLabel = new QLabel(tr("Edit the name of your captures:"), this); - infoLabel->setFixedHeight(20); - m_layout->addWidget(infoLabel); - m_layout->addWidget(m_helperButtons); - m_layout->addWidget(new QLabel(tr("Edit:"))); - m_layout->addWidget(m_nameEditor); - m_layout->addWidget(new QLabel(tr("Preview:"))); - m_layout->addWidget(m_outputLabel); +void +FileNameEditor::initLayout() +{ + m_layout = new QVBoxLayout(this); + auto infoLabel = new QLabel(tr("Edit the name of your captures:"), this); + infoLabel->setFixedHeight(20); + m_layout->addWidget(infoLabel); + m_layout->addWidget(m_helperButtons); + m_layout->addWidget(new QLabel(tr("Edit:"))); + m_layout->addWidget(m_nameEditor); + m_layout->addWidget(new QLabel(tr("Preview:"))); + m_layout->addWidget(m_outputLabel); - QHBoxLayout *horizLayout = new QHBoxLayout(); - horizLayout->addWidget(m_saveButton); - horizLayout->addWidget(m_resetButton); - horizLayout->addWidget(m_clearButton); - m_layout->addLayout(horizLayout); + QHBoxLayout* horizLayout = new QHBoxLayout(); + horizLayout->addWidget(m_saveButton); + horizLayout->addWidget(m_resetButton); + horizLayout->addWidget(m_clearButton); + m_layout->addLayout(horizLayout); } -void FileNameEditor::initWidgets() { - m_nameHandler = new FileNameHandler(this); +void +FileNameEditor::initWidgets() +{ + m_nameHandler = new FileNameHandler(this); - // editor - m_nameEditor = new QLineEdit(this); - m_nameEditor->setMaxLength(FileNameHandler::MAX_CHARACTERS); + // editor + m_nameEditor = new QLineEdit(this); + m_nameEditor->setMaxLength(FileNameHandler::MAX_CHARACTERS); - // preview - m_outputLabel = new QLineEdit(this); - m_outputLabel->setDisabled(true); - QString foreground = this->palette().windowText().color().name(); - m_outputLabel->setStyleSheet(QStringLiteral("color: %1").arg(foreground)); - QPalette pal = m_outputLabel->palette(); - QColor color = pal.color(QPalette::Disabled, m_outputLabel->backgroundRole()); - pal.setColor(QPalette::Active, m_outputLabel->backgroundRole(), color); - m_outputLabel->setPalette(pal); + // preview + m_outputLabel = new QLineEdit(this); + m_outputLabel->setDisabled(true); + QString foreground = this->palette().windowText().color().name(); + m_outputLabel->setStyleSheet(QStringLiteral("color: %1").arg(foreground)); + QPalette pal = m_outputLabel->palette(); + QColor color = pal.color(QPalette::Disabled, m_outputLabel->backgroundRole()); + pal.setColor(QPalette::Active, m_outputLabel->backgroundRole(), color); + m_outputLabel->setPalette(pal); - connect(m_nameEditor, &QLineEdit::textChanged, this, - &FileNameEditor::showParsedPattern); - updateComponents(); + connect(m_nameEditor, + &QLineEdit::textChanged, + this, + &FileNameEditor::showParsedPattern); + updateComponents(); - // helper buttons - m_helperButtons = new StrftimeChooserWidget(this); - connect(m_helperButtons, &StrftimeChooserWidget::variableEmitted, - this, &FileNameEditor::addToNameEditor); + // helper buttons + m_helperButtons = new StrftimeChooserWidget(this); + connect(m_helperButtons, + &StrftimeChooserWidget::variableEmitted, + this, + &FileNameEditor::addToNameEditor); - // save - m_saveButton = new QPushButton(tr("Save"), this); - connect(m_saveButton, &QPushButton::clicked, this, &FileNameEditor::savePattern); - m_saveButton->setToolTip(tr("Saves the pattern")); - // reset - m_resetButton = new QPushButton(tr("Reset"), this); - connect(m_resetButton, &QPushButton::clicked, - this, &FileNameEditor::resetName); - m_resetButton->setToolTip(tr("Restores the saved pattern")); - // clear - m_clearButton = new QPushButton(tr("Clear"), this); - connect(m_clearButton, &QPushButton::clicked, this, - [this](){ m_nameEditor->setText(QString()); - }); - m_clearButton->setToolTip(tr("Deletes the name"));} - -void FileNameEditor::savePattern() { - QString pattern = m_nameEditor->text(); - m_nameHandler->setPattern(pattern); + // save + m_saveButton = new QPushButton(tr("Save"), this); + connect( + m_saveButton, &QPushButton::clicked, this, &FileNameEditor::savePattern); + m_saveButton->setToolTip(tr("Saves the pattern")); + // reset + m_resetButton = new QPushButton(tr("Reset"), this); + connect( + m_resetButton, &QPushButton::clicked, this, &FileNameEditor::resetName); + m_resetButton->setToolTip(tr("Restores the saved pattern")); + // clear + m_clearButton = new QPushButton(tr("Clear"), this); + connect(m_clearButton, &QPushButton::clicked, this, [this]() { + m_nameEditor->setText(QString()); + }); + m_clearButton->setToolTip(tr("Deletes the name")); } -void FileNameEditor::showParsedPattern(const QString &p) { - QString output = m_nameHandler->parseFilename(p); - m_outputLabel->setText(output); +void +FileNameEditor::savePattern() +{ + QString pattern = m_nameEditor->text(); + m_nameHandler->setPattern(pattern); } -void FileNameEditor::resetName() { - m_nameEditor->setText(ConfigHandler().filenamePatternValue()); +void +FileNameEditor::showParsedPattern(const QString& p) +{ + QString output = m_nameHandler->parseFilename(p); + m_outputLabel->setText(output); } -void FileNameEditor::addToNameEditor(QString s) { - m_nameEditor->setText(m_nameEditor->text() + s); - m_nameEditor->setFocus(); +void +FileNameEditor::resetName() +{ + m_nameEditor->setText(ConfigHandler().filenamePatternValue()); } -void FileNameEditor::updateComponents() { - m_nameEditor->setText(ConfigHandler().filenamePatternValue()); - m_outputLabel->setText(m_nameHandler->parsedPattern()); +void +FileNameEditor::addToNameEditor(QString s) +{ + m_nameEditor->setText(m_nameEditor->text() + s); + m_nameEditor->setFocus(); +} + +void +FileNameEditor::updateComponents() +{ + m_nameEditor->setText(ConfigHandler().filenamePatternValue()); + m_outputLabel->setText(m_nameHandler->parsedPattern()); } diff --git a/src/config/filenameeditor.h b/src/config/filenameeditor.h index d5668c07..6d77ef55 100644 --- a/src/config/filenameeditor.h +++ b/src/config/filenameeditor.h @@ -17,8 +17,8 @@ #pragma once -#include #include +#include class QVBoxLayout; class QLineEdit; @@ -26,30 +26,31 @@ class FileNameHandler; class QPushButton; class StrftimeChooserWidget; -class FileNameEditor : public QWidget { - Q_OBJECT +class FileNameEditor : public QWidget +{ + Q_OBJECT public: - explicit FileNameEditor(QWidget *parent = nullptr); + explicit FileNameEditor(QWidget* parent = nullptr); private: - QVBoxLayout *m_layout; - QLineEdit *m_outputLabel; - QLineEdit *m_nameEditor; - FileNameHandler *m_nameHandler; - StrftimeChooserWidget *m_helperButtons; - QPushButton *m_saveButton; - QPushButton *m_resetButton; - QPushButton *m_clearButton; + QVBoxLayout* m_layout; + QLineEdit* m_outputLabel; + QLineEdit* m_nameEditor; + FileNameHandler* m_nameHandler; + StrftimeChooserWidget* m_helperButtons; + QPushButton* m_saveButton; + QPushButton* m_resetButton; + QPushButton* m_clearButton; - void initLayout(); - void initWidgets(); + void initLayout(); + void initWidgets(); public slots: - void addToNameEditor(QString s); - void updateComponents(); + void addToNameEditor(QString s); + void updateComponents(); private slots: - void savePattern(); - void showParsedPattern(const QString &); - void resetName(); + void savePattern(); + void showParsedPattern(const QString&); + void resetName(); }; diff --git a/src/config/geneneralconf.cpp b/src/config/geneneralconf.cpp index 5ed73ea5..92bcb0eb 100644 --- a/src/config/geneneralconf.cpp +++ b/src/config/geneneralconf.cpp @@ -16,224 +16,269 @@ // along with Flameshot. If not, see . #include "geneneralconf.h" -#include "src/utils/confighandler.h" -#include "src/utils/confighandler.h" #include "src/core/controller.h" -#include -#include +#include "src/utils/confighandler.h" #include -#include -#include -#include #include -#include +#include #include +#include +#include +#include +#include +#include -GeneneralConf::GeneneralConf(QWidget *parent) : QWidget(parent) { - m_layout = new QVBoxLayout(this); - m_layout->setAlignment(Qt::AlignTop); - initShowHelp(); - initShowDesktopNotification(); - initShowTrayIcon(); - initAutostart(); - initCloseAfterCapture(); - initCopyAndCloseAfterUpload(); - - // this has to be at the end - initConfingButtons(); - updateComponents(); -} - -void GeneneralConf::updateComponents() { - ConfigHandler config; - m_helpMessage->setChecked(config.showHelpValue()); - m_sysNotifications->setChecked(config.desktopNotificationValue()); - m_autostart->setChecked(config.startupLaunchValue()); - m_closeAfterCapture->setChecked(config.closeAfterScreenshotValue()); - m_copyAndCloseAfterUpload->setChecked(config.copyAndCloseAfterUploadEnabled()); - -#if defined(Q_OS_LINUX) || defined(Q_OS_UNIX) - m_showTray->setChecked(!config.disabledTrayIconValue()); -#endif -} - -void GeneneralConf::showHelpChanged(bool checked) { - ConfigHandler().setShowHelp(checked); -} - -void GeneneralConf::showDesktopNotificationChanged(bool checked) { - ConfigHandler().setDesktopNotification(checked); -} - -void GeneneralConf::showTrayIconChanged(bool checked) { - auto controller = Controller::getInstance(); - if (checked) { - controller->enableTrayIcon(); - } else { - controller->disableTrayIcon(); - } -} - -void GeneneralConf::autostartChanged(bool checked) { - ConfigHandler().setStartupLaunch(checked); -} - -void GeneneralConf::closeAfterCaptureChanged(bool checked) { - ConfigHandler().setCloseAfterScreenshot(checked); -} - -void GeneneralConf::importConfiguration() { - QString fileName = QFileDialog::getOpenFileName(this, tr("Import")); - if (fileName.isEmpty()) { - return; - } - QFile file(fileName); - QTextCodec *codec = QTextCodec::codecForLocale(); - if (!file.open(QFile::ReadOnly)) { - QMessageBox::about(this, tr("Error"), tr("Unable to read file.")); - return; - } - QString text = codec->toUnicode(file.readAll()); - file.close(); - - QFile config(ConfigHandler().configFilePath()); - if (!config.open(QFile::WriteOnly)) { - QMessageBox::about(this, tr("Error"), tr("Unable to write file.")); - return; - } - config.write(codec->fromUnicode(text)); - config.close(); -} - -void GeneneralConf::exportFileConfiguration() { - QString fileName = QFileDialog::getSaveFileName(this, tr("Save File"), - QStringLiteral("flameshot.conf")); - - // Cancel button - if (fileName.isNull()) { - return; - } - - QFile targetFile(fileName); - if (targetFile.exists()) { - targetFile.remove(); - } - bool ok = QFile::copy(ConfigHandler().configFilePath(), fileName); - if (!ok) { - QMessageBox::about(this, tr("Error"), tr("Unable to write file.")); - } -} - -void GeneneralConf::resetConfiguration() { - QMessageBox::StandardButton reply; - reply = QMessageBox::question( - this, tr("Confirm Reset"), - tr("Are you sure you want to reset the configuration?"), - QMessageBox::Yes | QMessageBox::No); - if (reply == QMessageBox::Yes) { - ConfigHandler().setDefaults(); - } -} - - -void GeneneralConf::initShowHelp() { - m_helpMessage = new QCheckBox(tr("Show help message"), this); - ConfigHandler config; - bool checked = config.showHelpValue(); - m_helpMessage->setChecked(checked); - m_helpMessage->setToolTip(tr("Show the help message at the beginning " - "in the capture mode.")); - m_layout->addWidget(m_helpMessage); - - connect(m_helpMessage, &QCheckBox::clicked, this, - &GeneneralConf::showHelpChanged); -} - -void GeneneralConf::initShowDesktopNotification() { - m_sysNotifications = - new QCheckBox(tr("Show desktop notifications"), this); - ConfigHandler config; - bool checked = config.desktopNotificationValue(); - m_sysNotifications->setChecked(checked); - m_sysNotifications->setToolTip(tr("Show desktop notifications")); - m_layout->addWidget(m_sysNotifications); - - connect(m_sysNotifications, &QCheckBox::clicked, this, - &GeneneralConf::showDesktopNotificationChanged); -} - -void GeneneralConf::initShowTrayIcon() { -#if defined(Q_OS_LINUX) || defined(Q_OS_UNIX) - m_showTray = new QCheckBox(tr("Show tray icon"), this); - ConfigHandler config; - bool checked = !config.disabledTrayIconValue(); - m_showTray->setChecked(checked); - m_showTray->setToolTip(tr("Show the systemtray icon")); - m_layout->addWidget(m_showTray); - - connect(m_showTray, &QCheckBox::stateChanged, this, - &GeneneralConf::showTrayIconChanged); -#endif -} - -void GeneneralConf::initConfingButtons() { - QHBoxLayout *buttonLayout = new QHBoxLayout(); - m_layout->addStretch(); - QGroupBox *box = new QGroupBox(tr("Configuration File")); - box->setFlat(true); - box->setLayout(buttonLayout); - m_layout->addWidget(box); - - m_exportButton = new QPushButton(tr("Export")); - buttonLayout->addWidget(m_exportButton); - connect(m_exportButton, &QPushButton::clicked, this, - &GeneneralConf::exportFileConfiguration); - - m_importButton = new QPushButton(tr("Import")); - buttonLayout->addWidget(m_importButton); - connect(m_importButton, &QPushButton::clicked, this, - &GeneneralConf::importConfiguration); - - m_resetButton = new QPushButton(tr("Reset")); - buttonLayout->addWidget(m_resetButton); - connect(m_resetButton, &QPushButton::clicked, this, - &GeneneralConf::resetConfiguration); -} - -void GeneneralConf::initAutostart() { - m_autostart = - new QCheckBox(tr("Launch at startup"), this); - ConfigHandler config; - bool checked = config.startupLaunchValue(); - m_autostart->setChecked(checked); - m_autostart->setToolTip(tr("Launch Flameshot")); - m_layout->addWidget(m_autostart); - - connect(m_autostart, &QCheckBox::clicked, this, - &GeneneralConf::autostartChanged); -} - -void GeneneralConf::initCloseAfterCapture() { - m_closeAfterCapture = new QCheckBox(tr("Close after capture"), this); - ConfigHandler config; - bool checked = config.closeAfterScreenshotValue(); - m_closeAfterCapture->setChecked(checked); - m_closeAfterCapture->setToolTip(tr("Close after taking a screenshot")); - m_layout->addWidget(m_closeAfterCapture); - - connect(m_closeAfterCapture, &QCheckBox::clicked, this, - &GeneneralConf::closeAfterCaptureChanged); -} - -void GeneneralConf::initCopyAndCloseAfterUpload() +GeneneralConf::GeneneralConf(QWidget* parent) + : QWidget(parent) { - m_copyAndCloseAfterUpload = new QCheckBox(tr("Copy URL after upload"), this); - ConfigHandler config; - m_copyAndCloseAfterUpload->setChecked(config.copyAndCloseAfterUploadEnabled()); - m_copyAndCloseAfterUpload->setToolTip(tr("Copy URL and close window after upload")); - m_layout->addWidget(m_copyAndCloseAfterUpload); + m_layout = new QVBoxLayout(this); + m_layout->setAlignment(Qt::AlignTop); + initShowHelp(); + initShowDesktopNotification(); + initShowTrayIcon(); + initAutostart(); + initCloseAfterCapture(); + initCopyAndCloseAfterUpload(); - connect(m_copyAndCloseAfterUpload, &QCheckBox::clicked, [](bool checked) { - ConfigHandler().setCopyAndCloseAfterUploadEnabled(checked); - }); + // this has to be at the end + initConfingButtons(); + updateComponents(); +} + +void +GeneneralConf::updateComponents() +{ + ConfigHandler config; + m_helpMessage->setChecked(config.showHelpValue()); + m_sysNotifications->setChecked(config.desktopNotificationValue()); + m_autostart->setChecked(config.startupLaunchValue()); + m_closeAfterCapture->setChecked(config.closeAfterScreenshotValue()); + m_copyAndCloseAfterUpload->setChecked( + config.copyAndCloseAfterUploadEnabled()); + +#if defined(Q_OS_LINUX) || defined(Q_OS_UNIX) + m_showTray->setChecked(!config.disabledTrayIconValue()); +#endif +} + +void +GeneneralConf::showHelpChanged(bool checked) +{ + ConfigHandler().setShowHelp(checked); +} + +void +GeneneralConf::showDesktopNotificationChanged(bool checked) +{ + ConfigHandler().setDesktopNotification(checked); +} + +void +GeneneralConf::showTrayIconChanged(bool checked) +{ + auto controller = Controller::getInstance(); + if (checked) { + controller->enableTrayIcon(); + } else { + controller->disableTrayIcon(); + } +} + +void +GeneneralConf::autostartChanged(bool checked) +{ + ConfigHandler().setStartupLaunch(checked); +} + +void +GeneneralConf::closeAfterCaptureChanged(bool checked) +{ + ConfigHandler().setCloseAfterScreenshot(checked); +} + +void +GeneneralConf::importConfiguration() +{ + QString fileName = QFileDialog::getOpenFileName(this, tr("Import")); + if (fileName.isEmpty()) { + return; + } + QFile file(fileName); + QTextCodec* codec = QTextCodec::codecForLocale(); + if (!file.open(QFile::ReadOnly)) { + QMessageBox::about(this, tr("Error"), tr("Unable to read file.")); + return; + } + QString text = codec->toUnicode(file.readAll()); + file.close(); + + QFile config(ConfigHandler().configFilePath()); + if (!config.open(QFile::WriteOnly)) { + QMessageBox::about(this, tr("Error"), tr("Unable to write file.")); + return; + } + config.write(codec->fromUnicode(text)); + config.close(); +} + +void +GeneneralConf::exportFileConfiguration() +{ + QString fileName = QFileDialog::getSaveFileName( + this, tr("Save File"), QStringLiteral("flameshot.conf")); + + // Cancel button + if (fileName.isNull()) { + return; + } + + QFile targetFile(fileName); + if (targetFile.exists()) { + targetFile.remove(); + } + bool ok = QFile::copy(ConfigHandler().configFilePath(), fileName); + if (!ok) { + QMessageBox::about(this, tr("Error"), tr("Unable to write file.")); + } +} + +void +GeneneralConf::resetConfiguration() +{ + QMessageBox::StandardButton reply; + reply = QMessageBox::question( + this, + tr("Confirm Reset"), + tr("Are you sure you want to reset the configuration?"), + QMessageBox::Yes | QMessageBox::No); + if (reply == QMessageBox::Yes) { + ConfigHandler().setDefaults(); + } +} + +void +GeneneralConf::initShowHelp() +{ + m_helpMessage = new QCheckBox(tr("Show help message"), this); + ConfigHandler config; + bool checked = config.showHelpValue(); + m_helpMessage->setChecked(checked); + m_helpMessage->setToolTip(tr("Show the help message at the beginning " + "in the capture mode.")); + m_layout->addWidget(m_helpMessage); + + connect( + m_helpMessage, &QCheckBox::clicked, this, &GeneneralConf::showHelpChanged); +} + +void +GeneneralConf::initShowDesktopNotification() +{ + m_sysNotifications = new QCheckBox(tr("Show desktop notifications"), this); + ConfigHandler config; + bool checked = config.desktopNotificationValue(); + m_sysNotifications->setChecked(checked); + m_sysNotifications->setToolTip(tr("Show desktop notifications")); + m_layout->addWidget(m_sysNotifications); + + connect(m_sysNotifications, + &QCheckBox::clicked, + this, + &GeneneralConf::showDesktopNotificationChanged); +} + +void +GeneneralConf::initShowTrayIcon() +{ +#if defined(Q_OS_LINUX) || defined(Q_OS_UNIX) + m_showTray = new QCheckBox(tr("Show tray icon"), this); + ConfigHandler config; + bool checked = !config.disabledTrayIconValue(); + m_showTray->setChecked(checked); + m_showTray->setToolTip(tr("Show the systemtray icon")); + m_layout->addWidget(m_showTray); + + connect(m_showTray, + &QCheckBox::stateChanged, + this, + &GeneneralConf::showTrayIconChanged); +#endif +} + +void +GeneneralConf::initConfingButtons() +{ + QHBoxLayout* buttonLayout = new QHBoxLayout(); + m_layout->addStretch(); + QGroupBox* box = new QGroupBox(tr("Configuration File")); + box->setFlat(true); + box->setLayout(buttonLayout); + m_layout->addWidget(box); + + m_exportButton = new QPushButton(tr("Export")); + buttonLayout->addWidget(m_exportButton); + connect(m_exportButton, + &QPushButton::clicked, + this, + &GeneneralConf::exportFileConfiguration); + + m_importButton = new QPushButton(tr("Import")); + buttonLayout->addWidget(m_importButton); + connect(m_importButton, + &QPushButton::clicked, + this, + &GeneneralConf::importConfiguration); + + m_resetButton = new QPushButton(tr("Reset")); + buttonLayout->addWidget(m_resetButton); + connect(m_resetButton, + &QPushButton::clicked, + this, + &GeneneralConf::resetConfiguration); +} + +void +GeneneralConf::initAutostart() +{ + m_autostart = new QCheckBox(tr("Launch at startup"), this); + ConfigHandler config; + bool checked = config.startupLaunchValue(); + m_autostart->setChecked(checked); + m_autostart->setToolTip(tr("Launch Flameshot")); + m_layout->addWidget(m_autostart); + + connect( + m_autostart, &QCheckBox::clicked, this, &GeneneralConf::autostartChanged); +} + +void +GeneneralConf::initCloseAfterCapture() +{ + m_closeAfterCapture = new QCheckBox(tr("Close after capture"), this); + ConfigHandler config; + bool checked = config.closeAfterScreenshotValue(); + m_closeAfterCapture->setChecked(checked); + m_closeAfterCapture->setToolTip(tr("Close after taking a screenshot")); + m_layout->addWidget(m_closeAfterCapture); + + connect(m_closeAfterCapture, + &QCheckBox::clicked, + this, + &GeneneralConf::closeAfterCaptureChanged); +} + +void +GeneneralConf::initCopyAndCloseAfterUpload() +{ + m_copyAndCloseAfterUpload = new QCheckBox(tr("Copy URL after upload"), this); + ConfigHandler config; + m_copyAndCloseAfterUpload->setChecked( + config.copyAndCloseAfterUploadEnabled()); + m_copyAndCloseAfterUpload->setToolTip( + tr("Copy URL and close window after upload")); + m_layout->addWidget(m_copyAndCloseAfterUpload); + + connect(m_copyAndCloseAfterUpload, &QCheckBox::clicked, [](bool checked) { + ConfigHandler().setCopyAndCloseAfterUploadEnabled(checked); + }); } \ No newline at end of file diff --git a/src/config/geneneralconf.h b/src/config/geneneralconf.h index ae40ef76..2bc6e436 100644 --- a/src/config/geneneralconf.h +++ b/src/config/geneneralconf.h @@ -23,41 +23,42 @@ class QVBoxLayout; class QCheckBox; class QPushButton; -class GeneneralConf : public QWidget { - Q_OBJECT +class GeneneralConf : public QWidget +{ + Q_OBJECT public: - explicit GeneneralConf(QWidget *parent = nullptr); + explicit GeneneralConf(QWidget* parent = nullptr); public slots: - void updateComponents(); + void updateComponents(); private slots: - void showHelpChanged(bool checked); - void showDesktopNotificationChanged(bool checked); - void showTrayIconChanged(bool checked); - void autostartChanged(bool checked); - void closeAfterCaptureChanged(bool checked); - void importConfiguration(); - void exportFileConfiguration(); - void resetConfiguration(); + void showHelpChanged(bool checked); + void showDesktopNotificationChanged(bool checked); + void showTrayIconChanged(bool checked); + void autostartChanged(bool checked); + void closeAfterCaptureChanged(bool checked); + void importConfiguration(); + void exportFileConfiguration(); + void resetConfiguration(); private: - QVBoxLayout *m_layout; - QCheckBox *m_sysNotifications; - QCheckBox *m_showTray; - QCheckBox *m_helpMessage; - QCheckBox *m_autostart; - QCheckBox *m_closeAfterCapture; - QCheckBox *m_copyAndCloseAfterUpload; - QPushButton *m_importButton; - QPushButton *m_exportButton; - QPushButton *m_resetButton; + QVBoxLayout* m_layout; + QCheckBox* m_sysNotifications; + QCheckBox* m_showTray; + QCheckBox* m_helpMessage; + QCheckBox* m_autostart; + QCheckBox* m_closeAfterCapture; + QCheckBox* m_copyAndCloseAfterUpload; + QPushButton* m_importButton; + QPushButton* m_exportButton; + QPushButton* m_resetButton; - void initShowHelp(); - void initShowDesktopNotification(); - void initShowTrayIcon(); - void initConfingButtons(); - void initAutostart(); - void initCloseAfterCapture(); - void initCopyAndCloseAfterUpload(); + void initShowHelp(); + void initShowDesktopNotification(); + void initShowTrayIcon(); + void initConfingButtons(); + void initAutostart(); + void initCloseAfterCapture(); + void initCopyAndCloseAfterUpload(); }; diff --git a/src/config/strftimechooserwidget.cpp b/src/config/strftimechooserwidget.cpp index 85507419..47dc9fe6 100644 --- a/src/config/strftimechooserwidget.cpp +++ b/src/config/strftimechooserwidget.cpp @@ -16,53 +16,56 @@ // along with Flameshot. If not, see . #include "strftimechooserwidget.h" -#include #include +#include #include -StrftimeChooserWidget::StrftimeChooserWidget(QWidget *parent) : QWidget(parent) { - QGridLayout *layout = new QGridLayout(this); - auto k = m_buttonData.keys(); - int middle = k.length()/2; - // add the buttons in 2 columns (they need to be even) - for (int i = 0; i < 2; i++) { - for (int j = 0; j < middle; j++) { - QString key = k.last(); - k.pop_back(); - QString variable = m_buttonData.value(key); - QPushButton *button = new QPushButton(this); - button->setText(tr(key.toStdString().data())); - button->setToolTip(variable); - button->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); - button->setMinimumHeight(25); - layout->addWidget(button, j, i); - connect(button, &QPushButton::clicked, - this, [variable, this](){emit variableEmitted(variable);}); - } +StrftimeChooserWidget::StrftimeChooserWidget(QWidget* parent) + : QWidget(parent) +{ + QGridLayout* layout = new QGridLayout(this); + auto k = m_buttonData.keys(); + int middle = k.length() / 2; + // add the buttons in 2 columns (they need to be even) + for (int i = 0; i < 2; i++) { + for (int j = 0; j < middle; j++) { + QString key = k.last(); + k.pop_back(); + QString variable = m_buttonData.value(key); + QPushButton* button = new QPushButton(this); + button->setText(tr(key.toStdString().data())); + button->setToolTip(variable); + button->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); + button->setMinimumHeight(25); + layout->addWidget(button, j, i); + connect(button, &QPushButton::clicked, this, [variable, this]() { + emit variableEmitted(variable); + }); } - setLayout(layout); + } + setLayout(layout); } -QMap StrftimeChooserWidget::m_buttonData { - { QT_TR_NOOP("Century (00-99)"), "%C"}, - { QT_TR_NOOP("Year (00-99)"), "%y"}, - { QT_TR_NOOP("Year (2000)"), "%Y"}, - { QT_TR_NOOP("Month Name (jan)"), "%b"}, - { QT_TR_NOOP("Month Name (january)"), "%B"}, - { QT_TR_NOOP("Month (01-12)"), "%m"}, - { QT_TR_NOOP("Week Day (1-7)"), "%u"}, - { QT_TR_NOOP("Week (01-53)"), "%V"}, - { QT_TR_NOOP("Day Name (mon)"), "%a"}, - { QT_TR_NOOP("Day Name (monday)"), "%A"}, - { QT_TR_NOOP("Day (01-31)"), "%d"}, - { QT_TR_NOOP("Day of Month (1-31)"), "%e"}, - { QT_TR_NOOP("Day (001-366)"), "%j"}, - { QT_TR_NOOP("Time (%H-%M-%S)"), "%T"}, - { QT_TR_NOOP("Time (%H-%M)"), "%R"}, - { QT_TR_NOOP("Hour (00-23)"), "%H"}, - { QT_TR_NOOP("Hour (01-12)"), "%I"}, - { QT_TR_NOOP("Minute (00-59)"), "%M"}, - { QT_TR_NOOP("Second (00-59)"), "%S"}, - { QT_TR_NOOP("Full Date (%m/%d/%y)"), "%D"}, - { QT_TR_NOOP("Full Date (%Y-%m-%d)"), "%F"}, +QMap StrftimeChooserWidget::m_buttonData{ + { QT_TR_NOOP("Century (00-99)"), "%C" }, + { QT_TR_NOOP("Year (00-99)"), "%y" }, + { QT_TR_NOOP("Year (2000)"), "%Y" }, + { QT_TR_NOOP("Month Name (jan)"), "%b" }, + { QT_TR_NOOP("Month Name (january)"), "%B" }, + { QT_TR_NOOP("Month (01-12)"), "%m" }, + { QT_TR_NOOP("Week Day (1-7)"), "%u" }, + { QT_TR_NOOP("Week (01-53)"), "%V" }, + { QT_TR_NOOP("Day Name (mon)"), "%a" }, + { QT_TR_NOOP("Day Name (monday)"), "%A" }, + { QT_TR_NOOP("Day (01-31)"), "%d" }, + { QT_TR_NOOP("Day of Month (1-31)"), "%e" }, + { QT_TR_NOOP("Day (001-366)"), "%j" }, + { QT_TR_NOOP("Time (%H-%M-%S)"), "%T" }, + { QT_TR_NOOP("Time (%H-%M)"), "%R" }, + { QT_TR_NOOP("Hour (00-23)"), "%H" }, + { QT_TR_NOOP("Hour (01-12)"), "%I" }, + { QT_TR_NOOP("Minute (00-59)"), "%M" }, + { QT_TR_NOOP("Second (00-59)"), "%S" }, + { QT_TR_NOOP("Full Date (%m/%d/%y)"), "%D" }, + { QT_TR_NOOP("Full Date (%Y-%m-%d)"), "%F" }, }; diff --git a/src/config/strftimechooserwidget.h b/src/config/strftimechooserwidget.h index 999df4c3..df014689 100644 --- a/src/config/strftimechooserwidget.h +++ b/src/config/strftimechooserwidget.h @@ -19,14 +19,15 @@ #include -class StrftimeChooserWidget : public QWidget { - Q_OBJECT +class StrftimeChooserWidget : public QWidget +{ + Q_OBJECT public: - explicit StrftimeChooserWidget(QWidget *parent = nullptr); + explicit StrftimeChooserWidget(QWidget* parent = nullptr); signals: - void variableEmitted(const QString &); + void variableEmitted(const QString&); private: - static QMap m_buttonData; + static QMap m_buttonData; }; diff --git a/src/config/uicoloreditor.cpp b/src/config/uicoloreditor.cpp index 1d580bd2..7c00863a 100644 --- a/src/config/uicoloreditor.cpp +++ b/src/config/uicoloreditor.cpp @@ -15,151 +15,176 @@ // You should have received a copy of the GNU General Public License // along with Flameshot. If not, see . -#include "src/utils/confighandler.h" #include "uicoloreditor.h" #include "clickablelabel.h" +#include "src/utils/confighandler.h" #include "src/utils/globalvalues.h" -#include #include -#include #include +#include #include #include +#include -UIcolorEditor::UIcolorEditor(QWidget *parent) : QGroupBox(parent) { - setTitle(tr("UI Color Editor")); - setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); - m_hLayout = new QHBoxLayout; - m_vLayout = new QVBoxLayout; +UIcolorEditor::UIcolorEditor(QWidget* parent) + : QGroupBox(parent) +{ + setTitle(tr("UI Color Editor")); + setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); + m_hLayout = new QHBoxLayout; + m_vLayout = new QVBoxLayout; - const int space = QApplication::fontMetrics().lineSpacing(); - m_hLayout->addItem(new QSpacerItem(space, space, QSizePolicy::Expanding)); - m_vLayout->setAlignment(Qt::AlignVCenter); + const int space = QApplication::fontMetrics().lineSpacing(); + m_hLayout->addItem(new QSpacerItem(space, space, QSizePolicy::Expanding)); + m_vLayout->setAlignment(Qt::AlignVCenter); - initButtons(); - initColorWheel(); + initButtons(); + initColorWheel(); - m_vLayout->addSpacing(space); - m_hLayout->addLayout(m_vLayout); - m_hLayout->addItem(new QSpacerItem(space, space, QSizePolicy::Expanding)); - setLayout(m_hLayout); - updateComponents(); + m_vLayout->addSpacing(space); + m_hLayout->addLayout(m_vLayout); + m_hLayout->addItem(new QSpacerItem(space, space, QSizePolicy::Expanding)); + setLayout(m_hLayout); + updateComponents(); } -void UIcolorEditor::updateComponents() { - ConfigHandler config; - m_uiColor = config.uiMainColorValue(); - m_contrastColor = config.uiContrastColorValue(); - m_buttonContrast->setColor(m_contrastColor); - m_buttonMainColor->setColor(m_uiColor); - if (m_lastButtonPressed == m_buttonMainColor) { - m_colorWheel->setColor(m_uiColor); - } else { - m_colorWheel->setColor(m_contrastColor); - } +void +UIcolorEditor::updateComponents() +{ + ConfigHandler config; + m_uiColor = config.uiMainColorValue(); + m_contrastColor = config.uiContrastColorValue(); + m_buttonContrast->setColor(m_contrastColor); + m_buttonMainColor->setColor(m_uiColor); + if (m_lastButtonPressed == m_buttonMainColor) { + m_colorWheel->setColor(m_uiColor); + } else { + m_colorWheel->setColor(m_contrastColor); + } } // updateUIcolor updates the appearance of the buttons -void UIcolorEditor::updateUIcolor() { - ConfigHandler config; - if (m_lastButtonPressed == m_buttonMainColor) { - config.setUIMainColor(m_uiColor); - } else { - config.setUIContrastColor(m_contrastColor); - } +void +UIcolorEditor::updateUIcolor() +{ + ConfigHandler config; + if (m_lastButtonPressed == m_buttonMainColor) { + config.setUIMainColor(m_uiColor); + } else { + config.setUIContrastColor(m_contrastColor); + } } // updateLocalColor updates the local button -void UIcolorEditor::updateLocalColor(const QColor c) { - if (m_lastButtonPressed == m_buttonMainColor) { - m_uiColor = c; - } else { - m_contrastColor = c; - } - m_lastButtonPressed->setColor(c); +void +UIcolorEditor::updateLocalColor(const QColor c) +{ + if (m_lastButtonPressed == m_buttonMainColor) { + m_uiColor = c; + } else { + m_contrastColor = c; + } + m_lastButtonPressed->setColor(c); } -void UIcolorEditor::initColorWheel() { - m_colorWheel = new color_widgets::ColorWheel(this); - connect(m_colorWheel, &color_widgets::ColorWheel::mouseReleaseOnColor, this, - &UIcolorEditor::updateUIcolor); - connect(m_colorWheel, &color_widgets::ColorWheel::colorChanged, this, - &UIcolorEditor::updateLocalColor); +void +UIcolorEditor::initColorWheel() +{ + m_colorWheel = new color_widgets::ColorWheel(this); + connect(m_colorWheel, + &color_widgets::ColorWheel::mouseReleaseOnColor, + this, + &UIcolorEditor::updateUIcolor); + connect(m_colorWheel, + &color_widgets::ColorWheel::colorChanged, + this, + &UIcolorEditor::updateLocalColor); - const int size = GlobalValues::buttonBaseSize() * 3; - m_colorWheel->setMinimumSize(size, size); - m_colorWheel->setMaximumSize(size*2, size*2); - m_colorWheel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); - m_colorWheel->setToolTip(tr("Change the color moving the selectors and see" - " the changes in the preview buttons.")); + const int size = GlobalValues::buttonBaseSize() * 3; + m_colorWheel->setMinimumSize(size, size); + m_colorWheel->setMaximumSize(size * 2, size * 2); + m_colorWheel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); + m_colorWheel->setToolTip(tr("Change the color moving the selectors and see" + " the changes in the preview buttons.")); - m_hLayout->addWidget(m_colorWheel); + m_hLayout->addWidget(m_colorWheel); } -void UIcolorEditor::initButtons() { - const int extraSize = GlobalValues::buttonBaseSize() / 3; - int frameSize = GlobalValues::buttonBaseSize() + extraSize; +void +UIcolorEditor::initButtons() +{ + const int extraSize = GlobalValues::buttonBaseSize() / 3; + int frameSize = GlobalValues::buttonBaseSize() + extraSize; - m_vLayout->addWidget(new QLabel(tr("Select a Button to modify it"), this)); + m_vLayout->addWidget(new QLabel(tr("Select a Button to modify it"), this)); - QGroupBox *frame = new QGroupBox(); - frame->setFixedSize(frameSize, frameSize); + QGroupBox* frame = new QGroupBox(); + frame->setFixedSize(frameSize, frameSize); - m_buttonMainColor = new CaptureButton(m_buttonIconType, frame); - m_buttonMainColor->move(m_buttonMainColor->x() + extraSize/2, m_buttonMainColor->y() + extraSize/2); - QHBoxLayout *h1 = new QHBoxLayout(); - h1->addWidget(frame); - m_labelMain = new ClickableLabel(tr("Main Color"), this); - h1->addWidget(m_labelMain); - m_vLayout->addLayout(h1); + m_buttonMainColor = new CaptureButton(m_buttonIconType, frame); + m_buttonMainColor->move(m_buttonMainColor->x() + extraSize / 2, + m_buttonMainColor->y() + extraSize / 2); + QHBoxLayout* h1 = new QHBoxLayout(); + h1->addWidget(frame); + m_labelMain = new ClickableLabel(tr("Main Color"), this); + h1->addWidget(m_labelMain); + m_vLayout->addLayout(h1); - m_buttonMainColor->setToolTip(tr("Click on this button to set the edition" - " mode of the main color.")); + m_buttonMainColor->setToolTip(tr("Click on this button to set the edition" + " mode of the main color.")); - QGroupBox *frame2 = new QGroupBox(); - m_buttonContrast = new CaptureButton(m_buttonIconType, frame2); - m_buttonContrast->move(m_buttonContrast->x() + extraSize/2, - m_buttonContrast->y() + extraSize/2); + QGroupBox* frame2 = new QGroupBox(); + m_buttonContrast = new CaptureButton(m_buttonIconType, frame2); + m_buttonContrast->move(m_buttonContrast->x() + extraSize / 2, + m_buttonContrast->y() + extraSize / 2); - QHBoxLayout *h2 = new QHBoxLayout(); - h2->addWidget(frame2); - frame2->setFixedSize(frameSize, frameSize); - m_labelContrast = new ClickableLabel(tr("Contrast Color"), this); - m_labelContrast->setStyleSheet(QStringLiteral("color : gray")); - h2->addWidget(m_labelContrast); - m_vLayout->addLayout(h2); + QHBoxLayout* h2 = new QHBoxLayout(); + h2->addWidget(frame2); + frame2->setFixedSize(frameSize, frameSize); + m_labelContrast = new ClickableLabel(tr("Contrast Color"), this); + m_labelContrast->setStyleSheet(QStringLiteral("color : gray")); + h2->addWidget(m_labelContrast); + m_vLayout->addLayout(h2); - m_buttonContrast->setToolTip(tr("Click on this button to set the edition" - " mode of the contrast color.")); + m_buttonContrast->setToolTip(tr("Click on this button to set the edition" + " mode of the contrast color.")); - connect(m_buttonMainColor, &CaptureButton::pressedButton, - this, &UIcolorEditor::changeLastButton); - connect(m_buttonContrast, &CaptureButton::pressedButton, - this, &UIcolorEditor::changeLastButton); - // clicking the labels changes the button too - connect(m_labelMain, &ClickableLabel::clicked, - this, [this]{ changeLastButton(m_buttonMainColor); }); - connect(m_labelContrast, &ClickableLabel::clicked, - this, [this]{ changeLastButton(m_buttonContrast); }); - m_lastButtonPressed = m_buttonMainColor; + connect(m_buttonMainColor, + &CaptureButton::pressedButton, + this, + &UIcolorEditor::changeLastButton); + connect(m_buttonContrast, + &CaptureButton::pressedButton, + this, + &UIcolorEditor::changeLastButton); + // clicking the labels changes the button too + connect(m_labelMain, &ClickableLabel::clicked, this, [this] { + changeLastButton(m_buttonMainColor); + }); + connect(m_labelContrast, &ClickableLabel::clicked, this, [this] { + changeLastButton(m_buttonContrast); + }); + m_lastButtonPressed = m_buttonMainColor; } // visual update for the selected button -void UIcolorEditor::changeLastButton(CaptureButton *b) { - if (m_lastButtonPressed != b) { - m_lastButtonPressed = b; +void +UIcolorEditor::changeLastButton(CaptureButton* b) +{ + if (m_lastButtonPressed != b) { + m_lastButtonPressed = b; - QString offStyle(QStringLiteral("QLabel { color : gray; }")); + QString offStyle(QStringLiteral("QLabel { color : gray; }")); - if (b == m_buttonMainColor) { - m_colorWheel->setColor(m_uiColor); - m_labelContrast->setStyleSheet(offStyle); - m_labelMain->setStyleSheet(styleSheet()); - } else { - m_colorWheel->setColor(m_contrastColor); - m_labelContrast->setStyleSheet(styleSheet()); - m_labelMain->setStyleSheet(offStyle); - } - b->setIcon(b->icon()); + if (b == m_buttonMainColor) { + m_colorWheel->setColor(m_uiColor); + m_labelContrast->setStyleSheet(offStyle); + m_labelMain->setStyleSheet(styleSheet()); + } else { + m_colorWheel->setColor(m_contrastColor); + m_labelContrast->setStyleSheet(styleSheet()); + m_labelMain->setStyleSheet(offStyle); } + b->setIcon(b->icon()); + } } diff --git a/src/config/uicoloreditor.h b/src/config/uicoloreditor.h index 3c5c555b..5b362142 100644 --- a/src/config/uicoloreditor.h +++ b/src/config/uicoloreditor.h @@ -26,33 +26,35 @@ class QHBoxLayout; class CaptureButton; class ClickableLabel; -class UIcolorEditor : public QGroupBox { - Q_OBJECT +class UIcolorEditor : public QGroupBox +{ + Q_OBJECT public: - explicit UIcolorEditor(QWidget *parent = nullptr); + explicit UIcolorEditor(QWidget* parent = nullptr); public slots: - void updateComponents(); + void updateComponents(); private slots: - void updateUIcolor(); - void updateLocalColor(const QColor); - void changeLastButton(CaptureButton *); + void updateUIcolor(); + void updateLocalColor(const QColor); + void changeLastButton(CaptureButton*); private: - QColor m_uiColor, m_contrastColor; - CaptureButton *m_buttonMainColor; - ClickableLabel *m_labelMain; - CaptureButton *m_buttonContrast; - ClickableLabel *m_labelContrast; - CaptureButton *m_lastButtonPressed; - color_widgets::ColorWheel *m_colorWheel; + QColor m_uiColor, m_contrastColor; + CaptureButton* m_buttonMainColor; + ClickableLabel* m_labelMain; + CaptureButton* m_buttonContrast; + ClickableLabel* m_labelContrast; + CaptureButton* m_lastButtonPressed; + color_widgets::ColorWheel* m_colorWheel; - static const CaptureButton::ButtonType m_buttonIconType = CaptureButton::TYPE_CIRCLE; + static const CaptureButton::ButtonType m_buttonIconType = + CaptureButton::TYPE_CIRCLE; - QHBoxLayout *m_hLayout; - QVBoxLayout *m_vLayout; + QHBoxLayout* m_hLayout; + QVBoxLayout* m_vLayout; - void initColorWheel(); - void initButtons(); + void initColorWheel(); + void initButtons(); }; diff --git a/src/config/visualseditor.cpp b/src/config/visualseditor.cpp index 8ca77c80..6e702955 100644 --- a/src/config/visualseditor.cpp +++ b/src/config/visualseditor.cpp @@ -17,71 +17,85 @@ #include "visualseditor.h" #include "src/config/buttonlistview.h" +#include "src/config/extendedslider.h" #include "src/config/uicoloreditor.h" #include "src/utils/confighandler.h" -#include "src/config/extendedslider.h" +#include #include #include -#include -VisualsEditor::VisualsEditor(QWidget *parent) : QWidget(parent) { - m_layout= new QVBoxLayout(); - setLayout(m_layout); - initWidgets(); +VisualsEditor::VisualsEditor(QWidget* parent) + : QWidget(parent) +{ + m_layout = new QVBoxLayout(); + setLayout(m_layout); + initWidgets(); } -void VisualsEditor::updateComponents() { - m_buttonList->updateComponents(); - m_colorEditor->updateComponents(); - int opacity = ConfigHandler().contrastOpacityValue(); - m_opacitySlider->setMapedValue(0, opacity, 255); +void +VisualsEditor::updateComponents() +{ + m_buttonList->updateComponents(); + m_colorEditor->updateComponents(); + int opacity = ConfigHandler().contrastOpacityValue(); + m_opacitySlider->setMapedValue(0, opacity, 255); } -void VisualsEditor::initOpacitySlider() { - m_opacitySlider = new ExtendedSlider(); - m_opacitySlider->setFocusPolicy(Qt::NoFocus); - m_opacitySlider->setOrientation(Qt::Horizontal); - m_opacitySlider->setRange(0, 100); - connect(m_opacitySlider, &ExtendedSlider::modificationsEnded, - this, &VisualsEditor::saveOpacity); - QHBoxLayout *localLayout = new QHBoxLayout(); - localLayout->addWidget(new QLabel(QStringLiteral("0%"))); - localLayout->addWidget(m_opacitySlider); - localLayout->addWidget(new QLabel(QStringLiteral("100%"))); +void +VisualsEditor::initOpacitySlider() +{ + m_opacitySlider = new ExtendedSlider(); + m_opacitySlider->setFocusPolicy(Qt::NoFocus); + m_opacitySlider->setOrientation(Qt::Horizontal); + m_opacitySlider->setRange(0, 100); + connect(m_opacitySlider, + &ExtendedSlider::modificationsEnded, + this, + &VisualsEditor::saveOpacity); + QHBoxLayout* localLayout = new QHBoxLayout(); + localLayout->addWidget(new QLabel(QStringLiteral("0%"))); + localLayout->addWidget(m_opacitySlider); + localLayout->addWidget(new QLabel(QStringLiteral("100%"))); - QLabel *label = new QLabel(); - QString labelMsg = tr("Opacity of area outside selection:") + " %1%"; - connect(m_opacitySlider, &ExtendedSlider::valueChanged, - this, [labelMsg, label](int val){ - label->setText(labelMsg.arg(val)); - }); - m_layout->addWidget(label); - m_layout->addLayout(localLayout); + QLabel* label = new QLabel(); + QString labelMsg = tr("Opacity of area outside selection:") + " %1%"; + connect(m_opacitySlider, + &ExtendedSlider::valueChanged, + this, + [labelMsg, label](int val) { label->setText(labelMsg.arg(val)); }); + m_layout->addWidget(label); + m_layout->addLayout(localLayout); - int opacity = ConfigHandler().contrastOpacityValue(); - m_opacitySlider->setMapedValue(0, opacity, 255); + int opacity = ConfigHandler().contrastOpacityValue(); + m_opacitySlider->setMapedValue(0, opacity, 255); } -void VisualsEditor::saveOpacity() { - int value = m_opacitySlider->mappedValue(0, 255); - ConfigHandler().setContrastOpacity(value); +void +VisualsEditor::saveOpacity() +{ + int value = m_opacitySlider->mappedValue(0, 255); + ConfigHandler().setContrastOpacity(value); } -void VisualsEditor::initWidgets() { - m_colorEditor = new UIcolorEditor(); - m_layout->addWidget(m_colorEditor); +void +VisualsEditor::initWidgets() +{ + m_colorEditor = new UIcolorEditor(); + m_layout->addWidget(m_colorEditor); - initOpacitySlider(); + initOpacitySlider(); - auto boxButtons = new QGroupBox(); - boxButtons->setTitle(tr("Button Selection")); - auto listLayout = new QVBoxLayout(boxButtons); - m_buttonList = new ButtonListView(); - m_layout->addWidget(boxButtons); - listLayout->addWidget(m_buttonList); + auto boxButtons = new QGroupBox(); + boxButtons->setTitle(tr("Button Selection")); + auto listLayout = new QVBoxLayout(boxButtons); + m_buttonList = new ButtonListView(); + m_layout->addWidget(boxButtons); + listLayout->addWidget(m_buttonList); - QPushButton* setAllButtons = new QPushButton(tr("Select All")); - connect(setAllButtons, &QPushButton::clicked, - m_buttonList, &ButtonListView::selectAll); - listLayout->addWidget(setAllButtons); + QPushButton* setAllButtons = new QPushButton(tr("Select All")); + connect(setAllButtons, + &QPushButton::clicked, + m_buttonList, + &ButtonListView::selectAll); + listLayout->addWidget(setAllButtons); } diff --git a/src/config/visualseditor.h b/src/config/visualseditor.h index 85da7856..9acbd119 100644 --- a/src/config/visualseditor.h +++ b/src/config/visualseditor.h @@ -24,23 +24,24 @@ class QVBoxLayout; class ButtonListView; class UIcolorEditor; -class VisualsEditor : public QWidget { - Q_OBJECT +class VisualsEditor : public QWidget +{ + Q_OBJECT public: - explicit VisualsEditor(QWidget *parent = nullptr); + explicit VisualsEditor(QWidget* parent = nullptr); public slots: - void updateComponents(); + void updateComponents(); private slots: - void saveOpacity(); + void saveOpacity(); private: - QVBoxLayout *m_layout; - ButtonListView *m_buttonList; - UIcolorEditor *m_colorEditor; - ExtendedSlider *m_opacitySlider; + QVBoxLayout* m_layout; + ButtonListView* m_buttonList; + UIcolorEditor* m_colorEditor; + ExtendedSlider* m_opacitySlider; - void initWidgets(); - void initOpacitySlider(); + void initWidgets(); + void initOpacitySlider(); }; diff --git a/src/core/capturerequest.cpp b/src/core/capturerequest.cpp index 3c174a6d..9aac9374 100644 --- a/src/core/capturerequest.cpp +++ b/src/core/capturerequest.cpp @@ -17,70 +17,89 @@ #include "capturerequest.h" #include "src/utils/screenshotsaver.h" -#include #include +#include CaptureRequest::CaptureRequest(CaptureRequest::CaptureMode mode, - const uint delay, const QString &path, - const QVariant &data, - CaptureRequest::ExportTask tasks) : - m_mode(mode), m_delay(delay), m_path(path), m_tasks(tasks), - m_data(data), m_forcedID(false), m_id(0) + const uint delay, + const QString& path, + const QVariant& data, + CaptureRequest::ExportTask tasks) + : m_mode(mode) + , m_delay(delay) + , m_path(path) + , m_tasks(tasks) + , m_data(data) + , m_forcedID(false) + , m_id(0) +{} + +void +CaptureRequest::setStaticID(uint id) { - + m_forcedID = true; + m_id = id; } -void CaptureRequest::setStaticID(uint id) { - m_forcedID = true; - m_id = id; +uint +CaptureRequest::id() const +{ + if (m_forcedID) { + return m_id; + } + + uint id = 0; + QVector v; + v << qHash(m_mode) << qHash(m_delay * QDateTime::currentMSecsSinceEpoch()) + << qHash(m_path) << qHash(m_tasks) << m_data.toInt(); + for (uint i : v) { + id ^= i + 0x9e3779b9 + (id << 6) + (id >> 2); + } + return id; } -uint CaptureRequest::id() const { - if (m_forcedID) { - return m_id; - } - - uint id = 0; - QVectorv; - v << qHash(m_mode) << qHash(m_delay * QDateTime::currentMSecsSinceEpoch()) - << qHash(m_path) << qHash(m_tasks) << m_data.toInt(); - for(uint i : v) { - id ^= i + 0x9e3779b9 + (id << 6) + (id >> 2); - } - return id; -} - -CaptureRequest::CaptureMode CaptureRequest::captureMode() const { - return m_mode; -} - -uint CaptureRequest::delay() const { - return m_delay; -} - -QString CaptureRequest::path() const { - return m_path; -} - -QVariant CaptureRequest::data() const { - return m_data; -} - -void CaptureRequest::addTask(CaptureRequest::ExportTask task) { - m_tasks |= task; -} - -void CaptureRequest::exportCapture(const QPixmap &p) { - if ((m_tasks & ExportTask::FILESYSTEM_SAVE_TASK) != ExportTask::NO_TASK) { - if (m_path.isEmpty()) { - ScreenshotSaver().saveToFilesystemGUI(p); - } else { - ScreenshotSaver().saveToFilesystem(p, m_path); - } - } - - if ((m_tasks & ExportTask::CLIPBOARD_SAVE_TASK) != ExportTask::NO_TASK) { - ScreenshotSaver().saveToClipboard(p); +CaptureRequest::CaptureMode +CaptureRequest::captureMode() const +{ + return m_mode; +} + +uint +CaptureRequest::delay() const +{ + return m_delay; +} + +QString +CaptureRequest::path() const +{ + return m_path; +} + +QVariant +CaptureRequest::data() const +{ + return m_data; +} + +void +CaptureRequest::addTask(CaptureRequest::ExportTask task) +{ + m_tasks |= task; +} + +void +CaptureRequest::exportCapture(const QPixmap& p) +{ + if ((m_tasks & ExportTask::FILESYSTEM_SAVE_TASK) != ExportTask::NO_TASK) { + if (m_path.isEmpty()) { + ScreenshotSaver().saveToFilesystemGUI(p); + } else { + ScreenshotSaver().saveToFilesystem(p, m_path); } + } + if ((m_tasks & ExportTask::CLIPBOARD_SAVE_TASK) != ExportTask::NO_TASK) { + ScreenshotSaver().saveToClipboard(p); + } } diff --git a/src/core/capturerequest.h b/src/core/capturerequest.h index f500fa60..4adf3c45 100644 --- a/src/core/capturerequest.h +++ b/src/core/capturerequest.h @@ -17,64 +17,72 @@ #pragma once -#include #include +#include #include -class CaptureRequest { +class CaptureRequest +{ public: - enum CaptureMode { - FULLSCREEN_MODE, - GRAPHICAL_MODE, - SCREEN_MODE, - }; + enum CaptureMode + { + FULLSCREEN_MODE, + GRAPHICAL_MODE, + SCREEN_MODE, + }; - enum ExportTask { - NO_TASK = 0, - CLIPBOARD_SAVE_TASK = 1, - FILESYSTEM_SAVE_TASK = 2, - }; + enum ExportTask + { + NO_TASK = 0, + CLIPBOARD_SAVE_TASK = 1, + FILESYSTEM_SAVE_TASK = 2, + }; - CaptureRequest(CaptureMode mode, - const uint delay = 0, - const QString &path = QLatin1String(""), - const QVariant &data = QVariant(), - ExportTask tasks = NO_TASK); + CaptureRequest(CaptureMode mode, + const uint delay = 0, + const QString& path = QLatin1String(""), + const QVariant& data = QVariant(), + ExportTask tasks = NO_TASK); - void setStaticID(uint id); + void setStaticID(uint id); - uint id() const; - uint delay() const; - QString path() const; - QVariant data() const; - CaptureMode captureMode() const; + uint id() const; + uint delay() const; + QString path() const; + QVariant data() const; + CaptureMode captureMode() const; - void addTask(ExportTask task); - void exportCapture(const QPixmap &p); + void addTask(ExportTask task); + void exportCapture(const QPixmap& p); private: - CaptureMode m_mode; - uint m_delay; - QString m_path; - ExportTask m_tasks; - QVariant m_data; + CaptureMode m_mode; + uint m_delay; + QString m_path; + ExportTask m_tasks; + QVariant m_data; - bool m_forcedID; - uint m_id; + bool m_forcedID; + uint m_id; }; using eTask = CaptureRequest::ExportTask; -inline eTask operator|(const eTask &a, const eTask &b) { - return static_cast(static_cast(a) | static_cast(b)); +inline eTask +operator|(const eTask& a, const eTask& b) +{ + return static_cast(static_cast(a) | static_cast(b)); } -inline eTask operator&(const eTask &a, const eTask &b) { - return static_cast(static_cast(a) & static_cast(b)); +inline eTask +operator&(const eTask& a, const eTask& b) +{ + return static_cast(static_cast(a) & static_cast(b)); } -inline eTask& operator|=(eTask &a, const eTask &b) { - a = static_cast(static_cast(a) | static_cast(b)); - return a; +inline eTask& +operator|=(eTask& a, const eTask& b) +{ + a = static_cast(static_cast(a) | static_cast(b)); + return a; } - diff --git a/src/core/controller.cpp b/src/core/controller.cpp index d7c6e32e..5d6438f4 100644 --- a/src/core/controller.cpp +++ b/src/core/controller.cpp @@ -16,20 +16,20 @@ // along with Flameshot. If not, see . #include "controller.h" -#include "src/widgets/capture/capturewidget.h" -#include "src/utils/confighandler.h" -#include "src/widgets/infowindow.h" #include "src/config/configwindow.h" -#include "src/widgets/capture/capturebutton.h" -#include "src/widgets/capturelauncher.h" -#include "src/utils/systemnotification.h" +#include "src/utils/confighandler.h" #include "src/utils/screengrabber.h" -#include -#include -#include +#include "src/utils/systemnotification.h" +#include "src/widgets/capture/capturebutton.h" +#include "src/widgets/capture/capturewidget.h" +#include "src/widgets/capturelauncher.h" +#include "src/widgets/infowindow.h" #include -#include +#include #include +#include +#include +#include #ifdef Q_OS_WIN #include "src/core/globalshortcutfilter.h" @@ -38,241 +38,280 @@ // Controller is the core component of Flameshot, creates the trayIcon and // launches the capture widget -Controller::Controller() : m_captureWindow(nullptr) { - qApp->setQuitOnLastWindowClosed(false); +Controller::Controller() + : m_captureWindow(nullptr) +{ + qApp->setQuitOnLastWindowClosed(false); - // init tray icon + // init tray icon #if defined(Q_OS_LINUX) || defined(Q_OS_UNIX) - if (!ConfigHandler().disabledTrayIconValue()) { - enableTrayIcon(); - } -#elif defined(Q_OS_WIN) + if (!ConfigHandler().disabledTrayIconValue()) { enableTrayIcon(); + } +#elif defined(Q_OS_WIN) + enableTrayIcon(); - GlobalShortcutFilter *nativeFilter = new GlobalShortcutFilter(this); - qApp->installNativeEventFilter(nativeFilter); - connect(nativeFilter, &GlobalShortcutFilter::printPressed, - this, [this](){ - this->requestCapture(CaptureRequest(CaptureRequest::GRAPHICAL_MODE)); - }); + GlobalShortcutFilter* nativeFilter = new GlobalShortcutFilter(this); + qApp->installNativeEventFilter(nativeFilter); + connect(nativeFilter, &GlobalShortcutFilter::printPressed, this, [this]() { + this->requestCapture(CaptureRequest(CaptureRequest::GRAPHICAL_MODE)); + }); #endif - QString StyleSheet = CaptureButton::globalStyleSheet(); - qApp->setStyleSheet(StyleSheet); + QString StyleSheet = CaptureButton::globalStyleSheet(); + qApp->setStyleSheet(StyleSheet); } -Controller *Controller::getInstance() { - static Controller c; - return &c; +Controller* +Controller::getInstance() +{ + static Controller c; + return &c; } -void Controller::enableExports() { - connect(this, &Controller::captureTaken, - this, &Controller::handleCaptureTaken); - connect(this, &Controller::captureFailed, - this, &Controller::handleCaptureFailed); +void +Controller::enableExports() +{ + connect( + this, &Controller::captureTaken, this, &Controller::handleCaptureTaken); + connect( + this, &Controller::captureFailed, this, &Controller::handleCaptureFailed); } -void Controller::requestCapture(const CaptureRequest &request) { - uint id = request.id(); - m_requestMap.insert(id, request); +void +Controller::requestCapture(const CaptureRequest& request) +{ + uint id = request.id(); + m_requestMap.insert(id, request); - switch (request.captureMode()) { + switch (request.captureMode()) { case CaptureRequest::FULLSCREEN_MODE: - doLater(request.delay(), this, [this, id](){ - this->startFullscreenCapture(id); - }); - break; - // TODO: Figure out the code path that gets here so the deprated warning can be fixed + doLater(request.delay(), this, [this, id]() { + this->startFullscreenCapture(id); + }); + break; + // TODO: Figure out the code path that gets here so the deprated warning can + // be fixed case CaptureRequest::SCREEN_MODE: { - int &&number = request.data().toInt(); - doLater(request.delay(), this, [this, id, number](){ - this->startScreenGrab(id, number); - }); - break; - } case CaptureRequest::GRAPHICAL_MODE: { - QString &&path = request.path(); - doLater(request.delay(), this, [this, id, path](){ - this->startVisualCapture(id, path); - }); - break; - } default: - emit captureFailed(id); - break; + int&& number = request.data().toInt(); + doLater(request.delay(), this, [this, id, number]() { + this->startScreenGrab(id, number); + }); + break; } + case CaptureRequest::GRAPHICAL_MODE: { + QString&& path = request.path(); + doLater(request.delay(), this, [this, id, path]() { + this->startVisualCapture(id, path); + }); + break; + } + default: + emit captureFailed(id); + break; + } } // creation of a new capture in GUI mode -void Controller::startVisualCapture(const uint id, const QString &forcedSavePath) { - if (!m_captureWindow) { - QWidget *modalWidget = nullptr; - do { - modalWidget = qApp->activeModalWidget(); - if (modalWidget) { - modalWidget->close(); - modalWidget->deleteLater(); - } - } while (modalWidget); +void +Controller::startVisualCapture(const uint id, const QString& forcedSavePath) +{ + if (!m_captureWindow) { + QWidget* modalWidget = nullptr; + do { + modalWidget = qApp->activeModalWidget(); + if (modalWidget) { + modalWidget->close(); + modalWidget->deleteLater(); + } + } while (modalWidget); - m_captureWindow = new CaptureWidget(id, forcedSavePath); - //m_captureWindow = new CaptureWidget(id, forcedSavePath, false); // debug - connect(m_captureWindow, &CaptureWidget::captureFailed, - this, &Controller::captureFailed); - connect(m_captureWindow, &CaptureWidget::captureTaken, - this, &Controller::captureTaken); + m_captureWindow = new CaptureWidget(id, forcedSavePath); + // m_captureWindow = new CaptureWidget(id, forcedSavePath, false); // debug + connect(m_captureWindow, + &CaptureWidget::captureFailed, + this, + &Controller::captureFailed); + connect(m_captureWindow, + &CaptureWidget::captureTaken, + this, + &Controller::captureTaken); #ifdef Q_OS_WIN - m_captureWindow->show(); + m_captureWindow->show(); #else - m_captureWindow->showFullScreen(); - //m_captureWindow->show(); // Debug + m_captureWindow->showFullScreen(); + // m_captureWindow->show(); // Debug #endif - } else { - emit captureFailed(id); - } + } else { + emit captureFailed(id); + } } -void Controller::startScreenGrab(const uint id, const int screenNumber) { - bool ok = true; - int n = screenNumber; +void +Controller::startScreenGrab(const uint id, const int screenNumber) +{ + bool ok = true; + int n = screenNumber; - if (n < 0) { - QPoint globalCursorPos = QCursor::pos(); - n = qApp->desktop()->screenNumber(globalCursorPos); - } - QPixmap p(ScreenGrabber().grabScreen(n, ok)); - if (ok) { - emit captureTaken(id, p); - } else { - emit captureFailed(id); - } + if (n < 0) { + QPoint globalCursorPos = QCursor::pos(); + n = qApp->desktop()->screenNumber(globalCursorPos); + } + QPixmap p(ScreenGrabber().grabScreen(n, ok)); + if (ok) { + emit captureTaken(id, p); + } else { + emit captureFailed(id); + } } // creation of the configuration window -void Controller::openConfigWindow() { - if (!m_configWindow) { - m_configWindow = new ConfigWindow(); - m_configWindow->show(); - } +void +Controller::openConfigWindow() +{ + if (!m_configWindow) { + m_configWindow = new ConfigWindow(); + m_configWindow->show(); + } } // creation of the window of information -void Controller::openInfoWindow() { - if (!m_infoWindow) { - m_infoWindow = new InfoWindow(); +void +Controller::openInfoWindow() +{ + if (!m_infoWindow) { + m_infoWindow = new InfoWindow(); + } +} + +void +Controller::openLauncherWindow() +{ + CaptureLauncher* w = new CaptureLauncher(); + w->show(); +} + +void +Controller::enableTrayIcon() +{ + if (m_trayIcon) { + return; + } + ConfigHandler().setDisabledTrayIcon(false); + QAction* captureAction = new QAction(tr("&Take Screenshot"), this); + connect(captureAction, &QAction::triggered, this, [this]() { + // Wait 400 ms to hide the QMenu + doLater(400, this, [this]() { this->startVisualCapture(); }); + }); + QAction* launcherAction = new QAction(tr("&Open Launcher"), this); + connect( + launcherAction, &QAction::triggered, this, &Controller::openLauncherWindow); + QAction* configAction = new QAction(tr("&Configuration"), this); + connect( + configAction, &QAction::triggered, this, &Controller::openConfigWindow); + QAction* infoAction = new QAction(tr("&Information"), this); + connect(infoAction, &QAction::triggered, this, &Controller::openInfoWindow); + QAction* quitAction = new QAction(tr("&Quit"), this); + connect(quitAction, &QAction::triggered, qApp, &QCoreApplication::quit); + + QMenu* trayIconMenu = new QMenu(); + trayIconMenu->addAction(captureAction); + trayIconMenu->addAction(launcherAction); + trayIconMenu->addSeparator(); + trayIconMenu->addAction(configAction); + trayIconMenu->addAction(infoAction); + trayIconMenu->addSeparator(); + trayIconMenu->addAction(quitAction); + + m_trayIcon = new QSystemTrayIcon(); + m_trayIcon->setToolTip(QStringLiteral("Flameshot")); + m_trayIcon->setContextMenu(trayIconMenu); + QIcon trayicon = + QIcon::fromTheme("flameshot-tray", QIcon(":img/app/flameshot.png")); + m_trayIcon->setIcon(trayicon); + + auto trayIconActivated = [this](QSystemTrayIcon::ActivationReason r) { + if (r == QSystemTrayIcon::Trigger) { + startVisualCapture(); } + }; + connect(m_trayIcon, &QSystemTrayIcon::activated, this, trayIconActivated); + m_trayIcon->show(); } -void Controller::openLauncherWindow() { - CaptureLauncher *w = new CaptureLauncher(); - w->show(); -} - -void Controller::enableTrayIcon() { - if (m_trayIcon) { - return; - } - ConfigHandler().setDisabledTrayIcon(false); - QAction *captureAction = new QAction(tr("&Take Screenshot"), this); - connect(captureAction, &QAction::triggered, this, [this](){ - // Wait 400 ms to hide the QMenu - doLater(400, this, [this](){ this->startVisualCapture(); }); - }); - QAction *launcherAction = new QAction(tr("&Open Launcher"), this); - connect(launcherAction, &QAction::triggered, this, - &Controller::openLauncherWindow); - QAction *configAction = new QAction(tr("&Configuration"), this); - connect(configAction, &QAction::triggered, this, - &Controller::openConfigWindow); - QAction *infoAction = new QAction(tr("&Information"), this); - connect(infoAction, &QAction::triggered, this, - &Controller::openInfoWindow); - QAction *quitAction = new QAction(tr("&Quit"), this); - connect(quitAction, &QAction::triggered, qApp, - &QCoreApplication::quit); - - QMenu *trayIconMenu = new QMenu(); - trayIconMenu->addAction(captureAction); - trayIconMenu->addAction(launcherAction); - trayIconMenu->addSeparator(); - trayIconMenu->addAction(configAction); - trayIconMenu->addAction(infoAction); - trayIconMenu->addSeparator(); - trayIconMenu->addAction(quitAction); - - m_trayIcon = new QSystemTrayIcon(); - m_trayIcon->setToolTip(QStringLiteral("Flameshot")); - m_trayIcon->setContextMenu(trayIconMenu); - QIcon trayicon = QIcon::fromTheme("flameshot-tray", QIcon(":img/app/flameshot.png")); - m_trayIcon->setIcon(trayicon); - - auto trayIconActivated = [this](QSystemTrayIcon::ActivationReason r){ - if (r == QSystemTrayIcon::Trigger) { - startVisualCapture(); - } - }; - connect(m_trayIcon, &QSystemTrayIcon::activated, this, trayIconActivated); - m_trayIcon->show(); -} - -void Controller::disableTrayIcon() { +void +Controller::disableTrayIcon() +{ #if defined(Q_OS_LINUX) || defined(Q_OS_UNIX) - if (m_trayIcon) { - m_trayIcon->deleteLater(); - } - ConfigHandler().setDisabledTrayIcon(true); + if (m_trayIcon) { + m_trayIcon->deleteLater(); + } + ConfigHandler().setDisabledTrayIcon(true); #endif } -void Controller::sendTrayNotification( - const QString &text, - const QString &title, - const int timeout) +void +Controller::sendTrayNotification(const QString& text, + const QString& title, + const int timeout) { - if (m_trayIcon) { - m_trayIcon->showMessage(title, text, QSystemTrayIcon::Information, timeout); - } + if (m_trayIcon) { + m_trayIcon->showMessage(title, text, QSystemTrayIcon::Information, timeout); + } } -void Controller::updateConfigComponents() { - if (m_configWindow) { - m_configWindow->updateChildren(); - } +void +Controller::updateConfigComponents() +{ + if (m_configWindow) { + m_configWindow->updateChildren(); + } } -void Controller::startFullscreenCapture(const uint id) { - bool ok = true; - QPixmap p(ScreenGrabber().grabEntireDesktop(ok)); - if (ok) { - emit captureTaken(id, p); - } else { - emit captureFailed(id); - } +void +Controller::startFullscreenCapture(const uint id) +{ + bool ok = true; + QPixmap p(ScreenGrabber().grabEntireDesktop(ok)); + if (ok) { + emit captureTaken(id, p); + } else { + emit captureFailed(id); + } } -void Controller::handleCaptureTaken(uint id, QPixmap p) { - auto it = m_requestMap.find(id); - if (it != m_requestMap.end()) { - it.value().exportCapture(p); - m_requestMap.erase(it); - } - if (ConfigHandler().closeAfterScreenshotValue()) { - QApplication::quit(); - } +void +Controller::handleCaptureTaken(uint id, QPixmap p) +{ + auto it = m_requestMap.find(id); + if (it != m_requestMap.end()) { + it.value().exportCapture(p); + m_requestMap.erase(it); + } + if (ConfigHandler().closeAfterScreenshotValue()) { + QApplication::quit(); + } } -void Controller::handleCaptureFailed(uint id) { - m_requestMap.remove(id); +void +Controller::handleCaptureFailed(uint id) +{ + m_requestMap.remove(id); - if (ConfigHandler().closeAfterScreenshotValue()) { - QApplication::quit(); - } + if (ConfigHandler().closeAfterScreenshotValue()) { + QApplication::quit(); + } } -void Controller::doLater(int msec, QObject *receiver, lambda func) { - QTimer *timer = new QTimer(receiver); - QObject::connect(timer, &QTimer::timeout, receiver, - [timer, func](){ func(); timer->deleteLater(); }); - timer->setInterval(msec); - timer->start(); +void +Controller::doLater(int msec, QObject* receiver, lambda func) +{ + QTimer* timer = new QTimer(receiver); + QObject::connect(timer, &QTimer::timeout, receiver, [timer, func]() { + func(); + timer->deleteLater(); + }); + timer->setInterval(msec); + timer->start(); } diff --git a/src/core/controller.h b/src/core/controller.h index bea0df12..ba9ac24d 100644 --- a/src/core/controller.h +++ b/src/core/controller.h @@ -18,10 +18,10 @@ #pragma once #include "src/core/capturerequest.h" -#include -#include -#include #include +#include +#include +#include #include #include @@ -32,54 +32,56 @@ class QSystemTrayIcon; using lambda = std::function; -class Controller : public QObject { - Q_OBJECT +class Controller : public QObject +{ + Q_OBJECT public: - static Controller* getInstance(); + static Controller* getInstance(); - Controller(const Controller&) = delete; - void operator =(const Controller&) = delete; + Controller(const Controller&) = delete; + void operator=(const Controller&) = delete; - void enableExports(); + void enableExports(); signals: - void captureTaken(uint id, QPixmap p); - void captureFailed(uint id); + void captureTaken(uint id, QPixmap p); + void captureFailed(uint id); public slots: - void requestCapture(const CaptureRequest &request); + void requestCapture(const CaptureRequest& request); - void openConfigWindow(); - void openInfoWindow(); - void openLauncherWindow(); - void enableTrayIcon(); - void disableTrayIcon(); - void sendTrayNotification(const QString &text, - const QString &title = QStringLiteral("Flameshot Info"), - const int timeout = 5000); + void openConfigWindow(); + void openInfoWindow(); + void openLauncherWindow(); + void enableTrayIcon(); + void disableTrayIcon(); + void sendTrayNotification( + const QString& text, + const QString& title = QStringLiteral("Flameshot Info"), + const int timeout = 5000); - void updateConfigComponents(); + void updateConfigComponents(); private slots: - void startFullscreenCapture(const uint id = 0); - void startVisualCapture(const uint id = 0, - const QString &forcedSavePath = QString()); - void startScreenGrab(const uint id = 0, const int screenNumber = -1); + void startFullscreenCapture(const uint id = 0); + void startVisualCapture(const uint id = 0, + const QString& forcedSavePath = QString()); + void startScreenGrab(const uint id = 0, const int screenNumber = -1); - void handleCaptureTaken(uint id, QPixmap p); - void handleCaptureFailed(uint id); + void handleCaptureTaken(uint id, QPixmap p); + void handleCaptureFailed(uint id); private: - Controller(); + Controller(); - // replace QTimer::singleShot introduced in Qt 5.4 - // the actual target Qt version is 5.3 - void doLater(int msec, QObject *receiver, lambda func); + // replace QTimer::singleShot introduced in Qt 5.4 + // the actual target Qt version is 5.3 + void doLater(int msec, QObject* receiver, lambda func); - QMap m_requestMap; - QPointer m_captureWindow; - QPointer m_infoWindow; - QPointer m_configWindow; - QPointer m_trayIcon; + QMap m_requestMap; + QPointer m_captureWindow; + QPointer m_infoWindow; + QPointer m_configWindow; + QPointer m_trayIcon; }; diff --git a/src/core/flameshotdbusadapter.cpp b/src/core/flameshotdbusadapter.cpp index 44b3fb20..b3ecb8b0 100644 --- a/src/core/flameshotdbusadapter.cpp +++ b/src/core/flameshotdbusadapter.cpp @@ -16,90 +16,111 @@ // along with Flameshot. If not, see . #include "flameshotdbusadapter.h" +#include "src/core/controller.h" #include "src/utils/confighandler.h" #include "src/utils/screengrabber.h" -#include "src/core/controller.h" #include "src/utils/screenshotsaver.h" #include "src/utils/systemnotification.h" #include -FlameshotDBusAdapter::FlameshotDBusAdapter(QObject *parent) - : QDBusAbstractAdaptor(parent) +FlameshotDBusAdapter::FlameshotDBusAdapter(QObject* parent) + : QDBusAbstractAdaptor(parent) { - auto controller = Controller::getInstance(); - connect(controller, &Controller::captureFailed, - this, &FlameshotDBusAdapter::captureFailed); - connect(controller, &Controller::captureTaken, - this, &FlameshotDBusAdapter::handleCaptureTaken); + auto controller = Controller::getInstance(); + connect(controller, + &Controller::captureFailed, + this, + &FlameshotDBusAdapter::captureFailed); + connect(controller, + &Controller::captureTaken, + this, + &FlameshotDBusAdapter::handleCaptureTaken); } -FlameshotDBusAdapter::~FlameshotDBusAdapter() { +FlameshotDBusAdapter::~FlameshotDBusAdapter() {} -} - -void FlameshotDBusAdapter::graphicCapture(QString path, int delay, uint id) { - CaptureRequest req(CaptureRequest::GRAPHICAL_MODE, delay, path); -// if (toClipboard) { -// req.addTask(CaptureRequest::CLIPBOARD_SAVE_TASK); -// } - req.setStaticID(id); - Controller::getInstance()->requestCapture(req); -} - -void FlameshotDBusAdapter::fullScreen( - QString path, bool toClipboard, int delay, uint id) +void +FlameshotDBusAdapter::graphicCapture(QString path, int delay, uint id) { - CaptureRequest req(CaptureRequest::FULLSCREEN_MODE, delay, path); - if (toClipboard) { - req.addTask(CaptureRequest::CLIPBOARD_SAVE_TASK); - } - if (!path.isEmpty()) { - req.addTask(CaptureRequest::FILESYSTEM_SAVE_TASK); - } - req.setStaticID(id); - Controller::getInstance()->requestCapture(req); + CaptureRequest req(CaptureRequest::GRAPHICAL_MODE, delay, path); + // if (toClipboard) { + // req.addTask(CaptureRequest::CLIPBOARD_SAVE_TASK); + // } + req.setStaticID(id); + Controller::getInstance()->requestCapture(req); } -void FlameshotDBusAdapter::openLauncher() { - Controller::getInstance()->openLauncherWindow(); -} - -void FlameshotDBusAdapter::captureScreen(int number, QString path, - bool toClipboard, int delay, uint id) +void +FlameshotDBusAdapter::fullScreen(QString path, + bool toClipboard, + int delay, + uint id) { - CaptureRequest req(CaptureRequest::SCREEN_MODE, delay, path, number); - if (toClipboard) { - req.addTask(CaptureRequest::CLIPBOARD_SAVE_TASK); - } - if (!path.isEmpty()) { - req.addTask(CaptureRequest::FILESYSTEM_SAVE_TASK); - } - req.setStaticID(id); - Controller::getInstance()->requestCapture(req); + CaptureRequest req(CaptureRequest::FULLSCREEN_MODE, delay, path); + if (toClipboard) { + req.addTask(CaptureRequest::CLIPBOARD_SAVE_TASK); + } + if (!path.isEmpty()) { + req.addTask(CaptureRequest::FILESYSTEM_SAVE_TASK); + } + req.setStaticID(id); + Controller::getInstance()->requestCapture(req); } -void FlameshotDBusAdapter::openConfig() { - Controller::getInstance()->openConfigWindow(); +void +FlameshotDBusAdapter::openLauncher() +{ + Controller::getInstance()->openLauncherWindow(); } -void FlameshotDBusAdapter::trayIconEnabled(bool enabled) { - auto controller = Controller::getInstance(); - if (enabled) { - controller->enableTrayIcon(); - } else { - controller->disableTrayIcon(); - } +void +FlameshotDBusAdapter::captureScreen(int number, + QString path, + bool toClipboard, + int delay, + uint id) +{ + CaptureRequest req(CaptureRequest::SCREEN_MODE, delay, path, number); + if (toClipboard) { + req.addTask(CaptureRequest::CLIPBOARD_SAVE_TASK); + } + if (!path.isEmpty()) { + req.addTask(CaptureRequest::FILESYSTEM_SAVE_TASK); + } + req.setStaticID(id); + Controller::getInstance()->requestCapture(req); } -void FlameshotDBusAdapter::autostartEnabled(bool enabled) { - ConfigHandler().setStartupLaunch(enabled); - auto controller = Controller::getInstance(); - // Autostart is not saved in a .ini file, requires manual update - controller->updateConfigComponents(); +void +FlameshotDBusAdapter::openConfig() +{ + Controller::getInstance()->openConfigWindow(); } -void FlameshotDBusAdapter::handleCaptureTaken(uint id, const QPixmap &p) { - QByteArray byteArray; - QBuffer buffer(&byteArray); - p.save(&buffer, "PNG"); - emit captureTaken(id, byteArray); +void +FlameshotDBusAdapter::trayIconEnabled(bool enabled) +{ + auto controller = Controller::getInstance(); + if (enabled) { + controller->enableTrayIcon(); + } else { + controller->disableTrayIcon(); + } +} + +void +FlameshotDBusAdapter::autostartEnabled(bool enabled) +{ + ConfigHandler().setStartupLaunch(enabled); + auto controller = Controller::getInstance(); + // Autostart is not saved in a .ini file, requires manual update + controller->updateConfigComponents(); +} + +void +FlameshotDBusAdapter::handleCaptureTaken(uint id, const QPixmap& p) +{ + QByteArray byteArray; + QBuffer buffer(&byteArray); + p.save(&buffer, "PNG"); + emit captureTaken(id, byteArray); } diff --git a/src/core/flameshotdbusadapter.h b/src/core/flameshotdbusadapter.h index 90063593..0fa336c1 100644 --- a/src/core/flameshotdbusadapter.h +++ b/src/core/flameshotdbusadapter.h @@ -17,30 +17,35 @@ #pragma once -#include #include "src/core/controller.h" +#include -class FlameshotDBusAdapter : public QDBusAbstractAdaptor { - Q_OBJECT - Q_CLASSINFO("D-Bus Interface", "org.dharkael.Flameshot") +class FlameshotDBusAdapter : public QDBusAbstractAdaptor +{ + Q_OBJECT + Q_CLASSINFO("D-Bus Interface", "org.dharkael.Flameshot") public: - explicit FlameshotDBusAdapter(QObject *parent = nullptr); - virtual ~FlameshotDBusAdapter(); + explicit FlameshotDBusAdapter(QObject* parent = nullptr); + virtual ~FlameshotDBusAdapter(); signals: - void captureTaken(uint id, QByteArray rawImage); - void captureFailed(uint id); + void captureTaken(uint id, QByteArray rawImage); + void captureFailed(uint id); public slots: - Q_NOREPLY void graphicCapture(QString path, int delay, uint id); - Q_NOREPLY void fullScreen(QString path, bool toClipboard, int delay, uint id); - Q_NOREPLY void captureScreen(int number, QString path, bool toClipboard, int delay, uint id); - Q_NOREPLY void openLauncher(); - Q_NOREPLY void openConfig(); - Q_NOREPLY void trayIconEnabled(bool enabled); - Q_NOREPLY void autostartEnabled(bool enabled); + Q_NOREPLY void graphicCapture(QString path, int delay, uint id); + Q_NOREPLY void fullScreen(QString path, bool toClipboard, int delay, uint id); + Q_NOREPLY void captureScreen(int number, + QString path, + bool toClipboard, + int delay, + uint id); + Q_NOREPLY void openLauncher(); + Q_NOREPLY void openConfig(); + Q_NOREPLY void trayIconEnabled(bool enabled); + Q_NOREPLY void autostartEnabled(bool enabled); private slots: - void handleCaptureTaken(uint id, const QPixmap &p); + void handleCaptureTaken(uint id, const QPixmap& p); }; diff --git a/src/core/globalshortcutfilter.cpp b/src/core/globalshortcutfilter.cpp index 313da9b4..c23a6316 100644 --- a/src/core/globalshortcutfilter.cpp +++ b/src/core/globalshortcutfilter.cpp @@ -19,33 +19,33 @@ #include "src/core/controller.h" #include -GlobalShortcutFilter::GlobalShortcutFilter(QObject *parent) : - QObject(parent) +GlobalShortcutFilter::GlobalShortcutFilter(QObject* parent) + : QObject(parent) { - // Forced Print Screen - if (RegisterHotKey(NULL, 1, 0, VK_SNAPSHOT)) { - // ok - } + // Forced Print Screen + if (RegisterHotKey(NULL, 1, 0, VK_SNAPSHOT)) { + // ok + } } -bool GlobalShortcutFilter::nativeEventFilter( - const QByteArray &eventType, - void *message, - long *result) +bool +GlobalShortcutFilter::nativeEventFilter(const QByteArray& eventType, + void* message, + long* result) { - Q_UNUSED(eventType); - Q_UNUSED(result); + Q_UNUSED(eventType); + Q_UNUSED(result); - MSG* msg = static_cast(message); - if (msg->message == WM_HOTKEY) { - //const quint32 keycode = HIWORD(msg->lParam); - //const quint32 modifiers = LOWORD(msg->lParam); + MSG* msg = static_cast(message); + if (msg->message == WM_HOTKEY) { + // const quint32 keycode = HIWORD(msg->lParam); + // const quint32 modifiers = LOWORD(msg->lParam); - // TODO: this is just a temporal workwrround, proper global - // support would need custom shortcuts defined by the user. - Controller::getInstance()->requestCapture( - CaptureRequest(CaptureRequest::GRAPHICAL_MODE)); - return true; - } - return false; + // TODO: this is just a temporal workwrround, proper global + // support would need custom shortcuts defined by the user. + Controller::getInstance()->requestCapture( + CaptureRequest(CaptureRequest::GRAPHICAL_MODE)); + return true; + } + return false; } diff --git a/src/core/globalshortcutfilter.h b/src/core/globalshortcutfilter.h index be1cc3c5..11d77213 100644 --- a/src/core/globalshortcutfilter.h +++ b/src/core/globalshortcutfilter.h @@ -17,22 +17,27 @@ #pragma once -#include #include +#include -class GlobalShortcutFilter : public QObject, public QAbstractNativeEventFilter { - Q_OBJECT +class GlobalShortcutFilter + : public QObject + , public QAbstractNativeEventFilter +{ + Q_OBJECT public: - explicit GlobalShortcutFilter(QObject *parent = nullptr); + explicit GlobalShortcutFilter(QObject* parent = nullptr); - bool nativeEventFilter(const QByteArray &eventType, void *message, long *result); + bool nativeEventFilter(const QByteArray& eventType, + void* message, + long* result); signals: - void printPressed(); + void printPressed(); private: - quint32 getNativeModifier(Qt::KeyboardModifiers modifiers); - quint32 nativeKeycode(Qt::Key key); - bool registerShortcut(quint32 nativeKey, quint32 nativeMods); - bool unregisterShortcut(quint32 nativeKey, quint32 nativeMods); + quint32 getNativeModifier(Qt::KeyboardModifiers modifiers); + quint32 nativeKeycode(Qt::Key key); + bool registerShortcut(quint32 nativeKey, quint32 nativeMods); + bool unregisterShortcut(quint32 nativeKey, quint32 nativeMods); }; diff --git a/src/main.cpp b/src/main.cpp index b8c13f1c..20f38d6e 100644 --- a/src/main.cpp +++ b/src/main.cpp @@ -15,424 +15,456 @@ // You should have received a copy of the GNU General Public License // along with Flameshot. If not, see . -#include "src/core/controller.h" #include "singleapplication.h" -#include "src/utils/filenamehandler.h" -#include "src/utils/confighandler.h" #include "src/cli/commandlineparser.h" -#include "src/utils/systemnotification.h" -#include "src/utils/pathinfo.h" #include "src/core/capturerequest.h" +#include "src/core/controller.h" +#include "src/utils/confighandler.h" +#include "src/utils/filenamehandler.h" +#include "src/utils/pathinfo.h" +#include "src/utils/systemnotification.h" #include +#include #include -#include #include #include -#include +#include #if defined(Q_OS_LINUX) || defined(Q_OS_UNIX) #include "src/core/flameshotdbusadapter.h" #include "src/utils/dbusutils.h" -#include #include +#include #endif -int main(int argc, char *argv[]) { - // required for the button serialization - // TODO: change to QVector in v1.0 - qRegisterMetaTypeStreamOperators >("QList"); - qApp->setApplicationVersion(static_cast(APP_VERSION)); +int +main(int argc, char* argv[]) +{ + // required for the button serialization + // TODO: change to QVector in v1.0 + qRegisterMetaTypeStreamOperators>("QList"); + qApp->setApplicationVersion(static_cast(APP_VERSION)); - // no arguments, just launch Flameshot - if (argc == 1) { - SingleApplication app(argc, argv); + // no arguments, just launch Flameshot + if (argc == 1) { + SingleApplication app(argc, argv); - QTranslator translator, qtTranslator; - QStringList trPaths = PathInfo::translationsPaths(); + QTranslator translator, qtTranslator; + QStringList trPaths = PathInfo::translationsPaths(); - for (const QString &path: trPaths) { - bool match = translator.load(QLocale(), - QStringLiteral("Internationalization"), QStringLiteral("_"), - path); - if (match) { - break; - } - } - - qtTranslator.load(QLocale::system(), "qt", "_", - QLibraryInfo::location(QLibraryInfo::TranslationsPath)); - - app.installTranslator(&translator); - app.installTranslator(&qtTranslator); - app.setAttribute(Qt::AA_DontCreateNativeWidgetSiblings, true); - app.setApplicationName(QStringLiteral("flameshot")); - app.setOrganizationName(QStringLiteral("Dharkael")); - - auto c = Controller::getInstance(); -#if defined(Q_OS_LINUX) || defined(Q_OS_UNIX) - new FlameshotDBusAdapter(c); - QDBusConnection dbus = QDBusConnection::sessionBus(); - if (!dbus.isConnected()) { - SystemNotification().sendMessage( - QObject::tr("Unable to connect via DBus")); - } - dbus.registerObject(QStringLiteral("/"), c); - dbus.registerService(QStringLiteral("org.dharkael.Flameshot")); -#endif - // Exporting captures must be connected after the dbus interface - // or the dbus signal gets blocked until we end the exports. - c->enableExports(); - return app.exec(); + for (const QString& path : trPaths) { + bool match = translator.load(QLocale(), + QStringLiteral("Internationalization"), + QStringLiteral("_"), + path); + if (match) { + break; + } } -#ifndef Q_OS_WIN - /*--------------| - * CLI parsing | - * ------------*/ - QCoreApplication app(argc, argv); + qtTranslator.load(QLocale::system(), + "qt", + "_", + QLibraryInfo::location(QLibraryInfo::TranslationsPath)); + + app.installTranslator(&translator); + app.installTranslator(&qtTranslator); + app.setAttribute(Qt::AA_DontCreateNativeWidgetSiblings, true); app.setApplicationName(QStringLiteral("flameshot")); app.setOrganizationName(QStringLiteral("Dharkael")); - app.setApplicationVersion(qApp->applicationVersion()); - CommandLineParser parser; - // Add description - parser.setDescription( - QStringLiteral("Powerful yet simple to use screenshot software.")); - parser.setGeneralErrorMessage(QStringLiteral("See 'flameshot --help'.")); - // Arguments - CommandArgument fullArgument(QStringLiteral("full"), QStringLiteral("Capture the entire desktop.")); - CommandArgument launcherArgument(QStringLiteral("launcher"), QStringLiteral("Open the capture launcher.")); - CommandArgument guiArgument(QStringLiteral("gui"), QStringLiteral("Start a manual capture in GUI mode.")); - CommandArgument configArgument(QStringLiteral("config"), QStringLiteral("Configure flameshot.")); - CommandArgument screenArgument(QStringLiteral("screen"), QStringLiteral("Capture a single screen.")); - // Options - CommandOption pathOption( - {"p", "path"}, - QStringLiteral("Path where the capture will be saved"), - QStringLiteral("path")); - CommandOption clipboardOption( - {"c", "clipboard"}, - QStringLiteral("Save the capture to the clipboard")); - CommandOption delayOption( - {"d", "delay"}, - QStringLiteral("Delay time in milliseconds"), - QStringLiteral("milliseconds")); - CommandOption filenameOption( - {"f", "filename"}, - QStringLiteral("Set the filename pattern"), - QStringLiteral("pattern")); - CommandOption trayOption( - {"t", "trayicon"}, - QStringLiteral("Enable or disable the trayicon"), - QStringLiteral("bool")); - CommandOption autostartOption( - {"a", "autostart"}, - QStringLiteral("Enable or disable run at startup"), - QStringLiteral("bool")); - CommandOption showHelpOption( - {"s", "showhelp"}, - QStringLiteral("Show the help message in the capture mode"), - QStringLiteral("bool")); - CommandOption mainColorOption( - {"m", "maincolor"}, - QStringLiteral("Define the main UI color"), - QStringLiteral("color-code")); - CommandOption contrastColorOption( - {"k", "contrastcolor"}, - QStringLiteral("Define the contrast UI color"), - QStringLiteral("color-code")); - CommandOption rawImageOption( - {"r", "raw"}, - QStringLiteral("Print raw PNG capture")); - CommandOption screenNumberOption( - {"n", "number"}, - QStringLiteral("Define the screen to capture,\ndefault: screen containing the cursor"), - QStringLiteral("Screen number"), QStringLiteral("-1")); + auto c = Controller::getInstance(); +#if defined(Q_OS_LINUX) || defined(Q_OS_UNIX) + new FlameshotDBusAdapter(c); + QDBusConnection dbus = QDBusConnection::sessionBus(); + if (!dbus.isConnected()) { + SystemNotification().sendMessage( + QObject::tr("Unable to connect via DBus")); + } + dbus.registerObject(QStringLiteral("/"), c); + dbus.registerService(QStringLiteral("org.dharkael.Flameshot")); +#endif + // Exporting captures must be connected after the dbus interface + // or the dbus signal gets blocked until we end the exports. + c->enableExports(); + return app.exec(); + } - // Add checkers - auto colorChecker = [](const QString &colorCode) -> bool { - QColor parsedColor(colorCode); - return parsedColor.isValid() && parsedColor.alphaF() == 1.0; - }; - QString colorErr = "Invalid color, " - "this flag supports the following formats:\n" - "- #RGB (each of R, G, and B is a single hex digit)\n" - "- #RRGGBB\n- #RRRGGGBBB\n" - "- #RRRRGGGGBBBB\n" - "- Named colors like 'blue' or 'red'\n" - "You may need to escape the '#' sign as in '\\#FFF'"; +#ifndef Q_OS_WIN + /*--------------| + * CLI parsing | + * ------------*/ + QCoreApplication app(argc, argv); + app.setApplicationName(QStringLiteral("flameshot")); + app.setOrganizationName(QStringLiteral("Dharkael")); + app.setApplicationVersion(qApp->applicationVersion()); + CommandLineParser parser; + // Add description + parser.setDescription( + QStringLiteral("Powerful yet simple to use screenshot software.")); + parser.setGeneralErrorMessage(QStringLiteral("See 'flameshot --help'.")); + // Arguments + CommandArgument fullArgument(QStringLiteral("full"), + QStringLiteral("Capture the entire desktop.")); + CommandArgument launcherArgument( + QStringLiteral("launcher"), QStringLiteral("Open the capture launcher.")); + CommandArgument guiArgument( + QStringLiteral("gui"), + QStringLiteral("Start a manual capture in GUI mode.")); + CommandArgument configArgument(QStringLiteral("config"), + QStringLiteral("Configure flameshot.")); + CommandArgument screenArgument(QStringLiteral("screen"), + QStringLiteral("Capture a single screen.")); - const QString delayErr = QStringLiteral("Invalid delay, it must be higher than 0"); - const QString numberErr = QStringLiteral("Invalid screen number, it must be non negative"); - auto numericChecker = [](const QString &delayValue) -> bool { - int value = delayValue.toInt(); - return value >= 0; - }; + // Options + CommandOption pathOption( + { "p", "path" }, + QStringLiteral("Path where the capture will be saved"), + QStringLiteral("path")); + CommandOption clipboardOption( + { "c", "clipboard" }, QStringLiteral("Save the capture to the clipboard")); + CommandOption delayOption({ "d", "delay" }, + QStringLiteral("Delay time in milliseconds"), + QStringLiteral("milliseconds")); + CommandOption filenameOption({ "f", "filename" }, + QStringLiteral("Set the filename pattern"), + QStringLiteral("pattern")); + CommandOption trayOption({ "t", "trayicon" }, + QStringLiteral("Enable or disable the trayicon"), + QStringLiteral("bool")); + CommandOption autostartOption( + { "a", "autostart" }, + QStringLiteral("Enable or disable run at startup"), + QStringLiteral("bool")); + CommandOption showHelpOption( + { "s", "showhelp" }, + QStringLiteral("Show the help message in the capture mode"), + QStringLiteral("bool")); + CommandOption mainColorOption({ "m", "maincolor" }, + QStringLiteral("Define the main UI color"), + QStringLiteral("color-code")); + CommandOption contrastColorOption( + { "k", "contrastcolor" }, + QStringLiteral("Define the contrast UI color"), + QStringLiteral("color-code")); + CommandOption rawImageOption({ "r", "raw" }, + QStringLiteral("Print raw PNG capture")); + CommandOption screenNumberOption( + { "n", "number" }, + QStringLiteral( + "Define the screen to capture,\ndefault: screen containing the cursor"), + QStringLiteral("Screen number"), + QStringLiteral("-1")); - const QString pathErr = QStringLiteral("Invalid path, it must be a real path in the system"); - auto pathChecker = [pathErr](const QString &pathValue) -> bool { - bool res = QDir(pathValue).exists(); - if (!res) { - SystemNotification().sendMessage(QObject::tr(pathErr.toLatin1().data())); - } - return res; - }; + // Add checkers + auto colorChecker = [](const QString& colorCode) -> bool { + QColor parsedColor(colorCode); + return parsedColor.isValid() && parsedColor.alphaF() == 1.0; + }; + QString colorErr = "Invalid color, " + "this flag supports the following formats:\n" + "- #RGB (each of R, G, and B is a single hex digit)\n" + "- #RRGGBB\n- #RRRGGGBBB\n" + "- #RRRRGGGGBBBB\n" + "- Named colors like 'blue' or 'red'\n" + "You may need to escape the '#' sign as in '\\#FFF'"; - const QString booleanErr = QStringLiteral("Invalid value, it must be defined as 'true' or 'false'"); - auto booleanChecker = [](const QString &value) -> bool { - return value == QLatin1String("true") || value == QLatin1String("false"); - }; + const QString delayErr = + QStringLiteral("Invalid delay, it must be higher than 0"); + const QString numberErr = + QStringLiteral("Invalid screen number, it must be non negative"); + auto numericChecker = [](const QString& delayValue) -> bool { + int value = delayValue.toInt(); + return value >= 0; + }; - contrastColorOption.addChecker(colorChecker, colorErr); - mainColorOption.addChecker(colorChecker, colorErr); - delayOption.addChecker(numericChecker, delayErr); - pathOption.addChecker(pathChecker, pathErr); - trayOption.addChecker(booleanChecker, booleanErr); - autostartOption.addChecker(booleanChecker, booleanErr); - showHelpOption.addChecker(booleanChecker, booleanErr); - screenNumberOption.addChecker(numericChecker, numberErr); + const QString pathErr = + QStringLiteral("Invalid path, it must be a real path in the system"); + auto pathChecker = [pathErr](const QString& pathValue) -> bool { + bool res = QDir(pathValue).exists(); + if (!res) { + SystemNotification().sendMessage(QObject::tr(pathErr.toLatin1().data())); + } + return res; + }; - // Relationships - parser.AddArgument(guiArgument); - parser.AddArgument(screenArgument); - parser.AddArgument(fullArgument); - parser.AddArgument(launcherArgument); - parser.AddArgument(configArgument); - auto helpOption = parser.addHelpOption(); - auto versionOption = parser.addVersionOption(); - parser.AddOptions({ pathOption, delayOption, rawImageOption }, guiArgument); - parser.AddOptions({ screenNumberOption, clipboardOption, pathOption, - delayOption, rawImageOption }, - screenArgument); - parser.AddOptions({ pathOption, clipboardOption, delayOption, rawImageOption }, - fullArgument); - parser.AddOptions({ autostartOption, filenameOption, trayOption, - showHelpOption, mainColorOption, contrastColorOption }, - configArgument); - // Parse - if (!parser.parse(app.arguments())) { - goto finish; + const QString booleanErr = + QStringLiteral("Invalid value, it must be defined as 'true' or 'false'"); + auto booleanChecker = [](const QString& value) -> bool { + return value == QLatin1String("true") || value == QLatin1String("false"); + }; + + contrastColorOption.addChecker(colorChecker, colorErr); + mainColorOption.addChecker(colorChecker, colorErr); + delayOption.addChecker(numericChecker, delayErr); + pathOption.addChecker(pathChecker, pathErr); + trayOption.addChecker(booleanChecker, booleanErr); + autostartOption.addChecker(booleanChecker, booleanErr); + showHelpOption.addChecker(booleanChecker, booleanErr); + screenNumberOption.addChecker(numericChecker, numberErr); + + // Relationships + parser.AddArgument(guiArgument); + parser.AddArgument(screenArgument); + parser.AddArgument(fullArgument); + parser.AddArgument(launcherArgument); + parser.AddArgument(configArgument); + auto helpOption = parser.addHelpOption(); + auto versionOption = parser.addVersionOption(); + parser.AddOptions({ pathOption, delayOption, rawImageOption }, guiArgument); + parser.AddOptions({ screenNumberOption, + clipboardOption, + pathOption, + delayOption, + rawImageOption }, + screenArgument); + parser.AddOptions( + { pathOption, clipboardOption, delayOption, rawImageOption }, fullArgument); + parser.AddOptions({ autostartOption, + filenameOption, + trayOption, + showHelpOption, + mainColorOption, + contrastColorOption }, + configArgument); + // Parse + if (!parser.parse(app.arguments())) { + goto finish; + } + + // PROCESS DATA + //-------------- + if (parser.isSet(helpOption) || parser.isSet(versionOption)) { + } else if (parser.isSet(launcherArgument)) { // LAUNCHER + QDBusMessage m = + QDBusMessage::createMethodCall(QStringLiteral("org.dharkael.Flameshot"), + QStringLiteral("/"), + QLatin1String(""), + QStringLiteral("openLauncher")); + QDBusConnection sessionBus = QDBusConnection::sessionBus(); + if (!sessionBus.isConnected()) { + SystemNotification().sendMessage( + QObject::tr("Unable to connect via DBus")); + } + sessionBus.call(m); + } else if (parser.isSet(guiArgument)) { // GUI + QString pathValue = parser.value(pathOption); + int delay = parser.value(delayOption).toInt(); + bool isRaw = parser.isSet(rawImageOption); + DBusUtils dbusUtils; + CaptureRequest req(CaptureRequest::GRAPHICAL_MODE, delay, pathValue); + uint id = req.id(); + + // Send message + QDBusMessage m = + QDBusMessage::createMethodCall(QStringLiteral("org.dharkael.Flameshot"), + QStringLiteral("/"), + QLatin1String(""), + QStringLiteral("graphicCapture")); + m << pathValue << delay << id; + QDBusConnection sessionBus = QDBusConnection::sessionBus(); + dbusUtils.checkDBusConnection(sessionBus); + sessionBus.call(m); + + if (isRaw) { + dbusUtils.connectPrintCapture(sessionBus, id); + QTimer t; + t.setInterval(delay + 1000 * 60 * 15); // 15 minutes timeout + QObject::connect(&t, &QTimer::timeout, qApp, &QCoreApplication::quit); + t.start(); + // wait + return app.exec(); + } + } else if (parser.isSet(fullArgument)) { // FULL + QString pathValue = parser.value(pathOption); + int delay = parser.value(delayOption).toInt(); + bool toClipboard = parser.isSet(clipboardOption); + bool isRaw = parser.isSet(rawImageOption); + // Not a valid command + if (!isRaw && !toClipboard && pathValue.isEmpty()) { + QTextStream out(stdout); + out << "Invalid format, set where to save the content with one of " + << "the following flags:\n " + << pathOption.dashedNames().join(QStringLiteral(", ")) << "\n " + << rawImageOption.dashedNames().join(QStringLiteral(", ")) << "\n " + << clipboardOption.dashedNames().join(QStringLiteral(", ")) << "\n\n"; + parser.parse(QStringList() << argv[0] << QStringLiteral("full") + << QStringLiteral("-h")); + goto finish; } - // PROCESS DATA - //-------------- - if (parser.isSet(helpOption) || parser.isSet(versionOption)) { + CaptureRequest req(CaptureRequest::FULLSCREEN_MODE, delay, pathValue); + if (toClipboard) { + req.addTask(CaptureRequest::CLIPBOARD_SAVE_TASK); } - else if (parser.isSet(launcherArgument)) { // LAUNCHER - QDBusMessage m = QDBusMessage::createMethodCall(QStringLiteral("org.dharkael.Flameshot"), - QStringLiteral("/"), QLatin1String(""), QStringLiteral("openLauncher")); - QDBusConnection sessionBus = QDBusConnection::sessionBus(); - if (!sessionBus.isConnected()) { - SystemNotification().sendMessage( - QObject::tr("Unable to connect via DBus")); - } - sessionBus.call(m); + if (!pathValue.isEmpty()) { + req.addTask(CaptureRequest::FILESYSTEM_SAVE_TASK); } - else if (parser.isSet(guiArgument)) { // GUI - QString pathValue = parser.value(pathOption); - int delay = parser.value(delayOption).toInt(); - bool isRaw = parser.isSet(rawImageOption); - DBusUtils dbusUtils; - CaptureRequest req(CaptureRequest::GRAPHICAL_MODE, delay, pathValue); - uint id = req.id(); + uint id = req.id(); + DBusUtils dbusUtils; - // Send message - QDBusMessage m = QDBusMessage::createMethodCall(QStringLiteral("org.dharkael.Flameshot"), - QStringLiteral("/"), QLatin1String(""), QStringLiteral("graphicCapture")); - m << pathValue << delay << id; - QDBusConnection sessionBus = QDBusConnection::sessionBus(); - dbusUtils.checkDBusConnection(sessionBus); - sessionBus.call(m); + // Send message + QDBusMessage m = + QDBusMessage::createMethodCall(QStringLiteral("org.dharkael.Flameshot"), + QStringLiteral("/"), + QLatin1String(""), + QStringLiteral("fullScreen")); + m << pathValue << toClipboard << delay << id; + QDBusConnection sessionBus = QDBusConnection::sessionBus(); + dbusUtils.checkDBusConnection(sessionBus); + sessionBus.call(m); - if (isRaw) { - dbusUtils.connectPrintCapture(sessionBus, id); - QTimer t; - t.setInterval(delay + 1000 * 60 * 15); // 15 minutes timeout - QObject::connect(&t, &QTimer::timeout, qApp, - &QCoreApplication::quit); - t.start(); - // wait - return app.exec(); - } + if (isRaw) { + dbusUtils.connectPrintCapture(sessionBus, id); + // timeout just in case + QTimer t; + t.setInterval(delay + 2000); + QObject::connect(&t, &QTimer::timeout, qApp, &QCoreApplication::quit); + t.start(); + // wait + return app.exec(); } - else if (parser.isSet(fullArgument)) { // FULL - QString pathValue = parser.value(pathOption); - int delay = parser.value(delayOption).toInt(); - bool toClipboard = parser.isSet(clipboardOption); - bool isRaw = parser.isSet(rawImageOption); - // Not a valid command - if (!isRaw && !toClipboard && pathValue.isEmpty()) { - QTextStream out(stdout); - out << "Invalid format, set where to save the content with one of " - << "the following flags:\n " - << pathOption.dashedNames().join(QStringLiteral(", ")) << "\n " - << rawImageOption.dashedNames().join(QStringLiteral(", ")) << "\n " - << clipboardOption.dashedNames().join(QStringLiteral(", ")) << "\n\n"; - parser.parse(QStringList() << argv[0] << QStringLiteral("full") << QStringLiteral("-h")); - goto finish; - } - - CaptureRequest req(CaptureRequest::FULLSCREEN_MODE, delay, pathValue); - if (toClipboard) { - req.addTask(CaptureRequest::CLIPBOARD_SAVE_TASK); - } - if (!pathValue.isEmpty()) { - req.addTask(CaptureRequest::FILESYSTEM_SAVE_TASK); - } - uint id = req.id(); - DBusUtils dbusUtils; - - // Send message - QDBusMessage m = QDBusMessage::createMethodCall(QStringLiteral("org.dharkael.Flameshot"), - QStringLiteral("/"), QLatin1String(""), QStringLiteral("fullScreen")); - m << pathValue << toClipboard << delay << id; - QDBusConnection sessionBus = QDBusConnection::sessionBus(); - dbusUtils.checkDBusConnection(sessionBus); - sessionBus.call(m); - - if (isRaw) { - dbusUtils.connectPrintCapture(sessionBus, id); - // timeout just in case - QTimer t; - t.setInterval(delay + 2000); - QObject::connect(&t, &QTimer::timeout, qApp, - &QCoreApplication::quit); - t.start(); - // wait - return app.exec(); - } + } else if (parser.isSet(screenArgument)) { // SCREEN + QString numberStr = parser.value(screenNumberOption); + int number = + numberStr.startsWith(QLatin1String("-")) ? -1 : numberStr.toInt(); + QString pathValue = parser.value(pathOption); + int delay = parser.value(delayOption).toInt(); + bool toClipboard = parser.isSet(clipboardOption); + bool isRaw = parser.isSet(rawImageOption); + // Not a valid command + if (!isRaw && !toClipboard && pathValue.isEmpty()) { + QTextStream out(stdout); + out << "Invalid format, set where to save the content with one of " + << "the following flags:\n " + << pathOption.dashedNames().join(QStringLiteral(", ")) << "\n " + << rawImageOption.dashedNames().join(QStringLiteral(", ")) << "\n " + << clipboardOption.dashedNames().join(QStringLiteral(", ")) << "\n\n"; + parser.parse(QStringList() << argv[0] << QStringLiteral("screen") + << QStringLiteral("-h")); + goto finish; } - else if (parser.isSet(screenArgument)) { // SCREEN - QString numberStr = parser.value(screenNumberOption); - int number = numberStr.startsWith(QLatin1String("-")) ? -1 : numberStr.toInt(); - QString pathValue = parser.value(pathOption); - int delay = parser.value(delayOption).toInt(); - bool toClipboard = parser.isSet(clipboardOption); - bool isRaw = parser.isSet(rawImageOption); - // Not a valid command - if (!isRaw && !toClipboard && pathValue.isEmpty()) { - QTextStream out(stdout); - out << "Invalid format, set where to save the content with one of " - << "the following flags:\n " - << pathOption.dashedNames().join(QStringLiteral(", ")) << "\n " - << rawImageOption.dashedNames().join(QStringLiteral(", ")) << "\n " - << clipboardOption.dashedNames().join(QStringLiteral(", ")) << "\n\n"; - parser.parse(QStringList() << argv[0] << QStringLiteral("screen") << QStringLiteral("-h")); - goto finish; - } - CaptureRequest req(CaptureRequest::SCREEN_MODE, - delay, pathValue, number); - if (toClipboard) { - req.addTask(CaptureRequest::CLIPBOARD_SAVE_TASK); - } - if (!pathValue.isEmpty()) { - req.addTask(CaptureRequest::FILESYSTEM_SAVE_TASK); - } - uint id = req.id(); - DBusUtils dbusUtils; - - // Send message - QDBusMessage m = QDBusMessage::createMethodCall(QStringLiteral("org.dharkael.Flameshot"), - QStringLiteral("/"), QLatin1String(""), QStringLiteral("captureScreen")); - m << number << pathValue << toClipboard << delay << id; - QDBusConnection sessionBus = QDBusConnection::sessionBus(); - dbusUtils.checkDBusConnection(sessionBus); - sessionBus.call(m); - - if (isRaw) { - dbusUtils.connectPrintCapture(sessionBus, id); - // timeout just in case - QTimer t; - t.setInterval(delay + 2000); - QObject::connect(&t, &QTimer::timeout, qApp, - &QCoreApplication::quit); - t.start(); - // wait - return app.exec(); - } + CaptureRequest req(CaptureRequest::SCREEN_MODE, delay, pathValue, number); + if (toClipboard) { + req.addTask(CaptureRequest::CLIPBOARD_SAVE_TASK); } - else if (parser.isSet(configArgument)) { // CONFIG - bool autostart = parser.isSet(autostartOption); - bool filename = parser.isSet(filenameOption); - bool tray = parser.isSet(trayOption); - bool help = parser.isSet(showHelpOption); - bool mainColor = parser.isSet(mainColorOption); - bool contrastColor = parser.isSet(contrastColorOption); - bool someFlagSet = (filename || tray || help || - mainColor || contrastColor); - ConfigHandler config; - if (autostart) { - QDBusMessage m = QDBusMessage::createMethodCall(QStringLiteral("org.dharkael.Flameshot"), - QStringLiteral("/"), QLatin1String(""), QStringLiteral("autostartEnabled")); - if (parser.value(autostartOption) == QLatin1String("false")) { - m << false; - } else if (parser.value(autostartOption) == QLatin1String("true")) { - m << true; - } - QDBusConnection sessionBus = QDBusConnection::sessionBus(); - if (!sessionBus.isConnected()) { - SystemNotification().sendMessage( - QObject::tr("Unable to connect via DBus")); - } - sessionBus.call(m); - } - if (filename) { - QString newFilename(parser.value(filenameOption)); - config.setFilenamePattern(newFilename); - FileNameHandler fh; - QTextStream(stdout) - << QStringLiteral("The new pattern is '%1'\n" - "Parsed pattern example: %2\n").arg(newFilename) - .arg(fh.parsedPattern()); - } - if (tray) { - QDBusMessage m = QDBusMessage::createMethodCall(QStringLiteral("org.dharkael.Flameshot"), - QStringLiteral("/"), QLatin1String(""), QStringLiteral("trayIconEnabled")); - if (parser.value(trayOption) == QLatin1String("false")) { - m << false; - } else if (parser.value(trayOption) == QLatin1String("true")) { - m << true; - } - QDBusConnection sessionBus = QDBusConnection::sessionBus(); - if (!sessionBus.isConnected()) { - SystemNotification().sendMessage( - QObject::tr("Unable to connect via DBus")); - } - sessionBus.call(m); - } - if (help) { - if (parser.value(showHelpOption) == QLatin1String("false")) { - config.setShowHelp(false); - } else if (parser.value(showHelpOption) == QLatin1String("true")) { - config.setShowHelp(true); - } - } - if (mainColor) { - QString colorCode = parser.value(mainColorOption); - QColor parsedColor(colorCode); - config.setUIMainColor(parsedColor); - } - if (contrastColor) { - QString colorCode = parser.value(contrastColorOption); - QColor parsedColor(colorCode); - config.setUIContrastColor(parsedColor); - } - - // Open gui when no options - if (!someFlagSet) { - QDBusMessage m = QDBusMessage::createMethodCall(QStringLiteral("org.dharkael.Flameshot"), - QStringLiteral("/"), QLatin1String(""), QStringLiteral("openConfig")); - QDBusConnection sessionBus = QDBusConnection::sessionBus(); - if (!sessionBus.isConnected()) { - SystemNotification().sendMessage( - QObject::tr("Unable to connect via DBus")); - } - sessionBus.call(m); - } + if (!pathValue.isEmpty()) { + req.addTask(CaptureRequest::FILESYSTEM_SAVE_TASK); } + uint id = req.id(); + DBusUtils dbusUtils; + + // Send message + QDBusMessage m = + QDBusMessage::createMethodCall(QStringLiteral("org.dharkael.Flameshot"), + QStringLiteral("/"), + QLatin1String(""), + QStringLiteral("captureScreen")); + m << number << pathValue << toClipboard << delay << id; + QDBusConnection sessionBus = QDBusConnection::sessionBus(); + dbusUtils.checkDBusConnection(sessionBus); + sessionBus.call(m); + + if (isRaw) { + dbusUtils.connectPrintCapture(sessionBus, id); + // timeout just in case + QTimer t; + t.setInterval(delay + 2000); + QObject::connect(&t, &QTimer::timeout, qApp, &QCoreApplication::quit); + t.start(); + // wait + return app.exec(); + } + } else if (parser.isSet(configArgument)) { // CONFIG + bool autostart = parser.isSet(autostartOption); + bool filename = parser.isSet(filenameOption); + bool tray = parser.isSet(trayOption); + bool help = parser.isSet(showHelpOption); + bool mainColor = parser.isSet(mainColorOption); + bool contrastColor = parser.isSet(contrastColorOption); + bool someFlagSet = (filename || tray || help || mainColor || contrastColor); + ConfigHandler config; + if (autostart) { + QDBusMessage m = + QDBusMessage::createMethodCall(QStringLiteral("org.dharkael.Flameshot"), + QStringLiteral("/"), + QLatin1String(""), + QStringLiteral("autostartEnabled")); + if (parser.value(autostartOption) == QLatin1String("false")) { + m << false; + } else if (parser.value(autostartOption) == QLatin1String("true")) { + m << true; + } + QDBusConnection sessionBus = QDBusConnection::sessionBus(); + if (!sessionBus.isConnected()) { + SystemNotification().sendMessage( + QObject::tr("Unable to connect via DBus")); + } + sessionBus.call(m); + } + if (filename) { + QString newFilename(parser.value(filenameOption)); + config.setFilenamePattern(newFilename); + FileNameHandler fh; + QTextStream(stdout) << QStringLiteral("The new pattern is '%1'\n" + "Parsed pattern example: %2\n") + .arg(newFilename) + .arg(fh.parsedPattern()); + } + if (tray) { + QDBusMessage m = + QDBusMessage::createMethodCall(QStringLiteral("org.dharkael.Flameshot"), + QStringLiteral("/"), + QLatin1String(""), + QStringLiteral("trayIconEnabled")); + if (parser.value(trayOption) == QLatin1String("false")) { + m << false; + } else if (parser.value(trayOption) == QLatin1String("true")) { + m << true; + } + QDBusConnection sessionBus = QDBusConnection::sessionBus(); + if (!sessionBus.isConnected()) { + SystemNotification().sendMessage( + QObject::tr("Unable to connect via DBus")); + } + sessionBus.call(m); + } + if (help) { + if (parser.value(showHelpOption) == QLatin1String("false")) { + config.setShowHelp(false); + } else if (parser.value(showHelpOption) == QLatin1String("true")) { + config.setShowHelp(true); + } + } + if (mainColor) { + QString colorCode = parser.value(mainColorOption); + QColor parsedColor(colorCode); + config.setUIMainColor(parsedColor); + } + if (contrastColor) { + QString colorCode = parser.value(contrastColorOption); + QColor parsedColor(colorCode); + config.setUIContrastColor(parsedColor); + } + + // Open gui when no options + if (!someFlagSet) { + QDBusMessage m = + QDBusMessage::createMethodCall(QStringLiteral("org.dharkael.Flameshot"), + QStringLiteral("/"), + QLatin1String(""), + QStringLiteral("openConfig")); + QDBusConnection sessionBus = QDBusConnection::sessionBus(); + if (!sessionBus.isConnected()) { + SystemNotification().sendMessage( + QObject::tr("Unable to connect via DBus")); + } + sessionBus.call(m); + } + } finish: #endif - return 0; + return 0; } diff --git a/src/tools/abstractactiontool.cpp b/src/tools/abstractactiontool.cpp index 09eb8b32..2ea69dc3 100644 --- a/src/tools/abstractactiontool.cpp +++ b/src/tools/abstractactiontool.cpp @@ -17,55 +17,78 @@ #include "abstractactiontool.h" -AbstractActionTool::AbstractActionTool(QObject *parent) : CaptureTool(parent) { +AbstractActionTool::AbstractActionTool(QObject* parent) + : CaptureTool(parent) +{} -} - -bool AbstractActionTool::isValid() const { - return true; -} - -bool AbstractActionTool::isSelectable() const { - return false; -} - -bool AbstractActionTool::showMousePreview() const { - return false; -} - -void AbstractActionTool::undo(QPixmap &pixmap) { - Q_UNUSED(pixmap); -} - -void AbstractActionTool::process(QPainter &painter, const QPixmap &pixmap, bool recordUndo) { - Q_UNUSED(painter); - Q_UNUSED(pixmap); - Q_UNUSED(recordUndo); -} - -void AbstractActionTool::paintMousePreview( - QPainter &painter, const CaptureContext &context) +bool +AbstractActionTool::isValid() const { - Q_UNUSED(painter); - Q_UNUSED(context); + return true; } -void AbstractActionTool::drawEnd(const QPoint &p) { - Q_UNUSED(p); +bool +AbstractActionTool::isSelectable() const +{ + return false; } -void AbstractActionTool::drawMove(const QPoint &p) { - Q_UNUSED(p); +bool +AbstractActionTool::showMousePreview() const +{ + return false; } -void AbstractActionTool::drawStart(const CaptureContext &context) { - Q_UNUSED(context); +void +AbstractActionTool::undo(QPixmap& pixmap) +{ + Q_UNUSED(pixmap); } -void AbstractActionTool::colorChanged(const QColor &c) { - Q_UNUSED(c); +void +AbstractActionTool::process(QPainter& painter, + const QPixmap& pixmap, + bool recordUndo) +{ + Q_UNUSED(painter); + Q_UNUSED(pixmap); + Q_UNUSED(recordUndo); } -void AbstractActionTool::thicknessChanged(const int th) { - Q_UNUSED(th); +void +AbstractActionTool::paintMousePreview(QPainter& painter, + const CaptureContext& context) +{ + Q_UNUSED(painter); + Q_UNUSED(context); +} + +void +AbstractActionTool::drawEnd(const QPoint& p) +{ + Q_UNUSED(p); +} + +void +AbstractActionTool::drawMove(const QPoint& p) +{ + Q_UNUSED(p); +} + +void +AbstractActionTool::drawStart(const CaptureContext& context) +{ + Q_UNUSED(context); +} + +void +AbstractActionTool::colorChanged(const QColor& c) +{ + Q_UNUSED(c); +} + +void +AbstractActionTool::thicknessChanged(const int th) +{ + Q_UNUSED(th); } diff --git a/src/tools/abstractactiontool.h b/src/tools/abstractactiontool.h index cf1180c4..815c5276 100644 --- a/src/tools/abstractactiontool.h +++ b/src/tools/abstractactiontool.h @@ -19,23 +19,27 @@ #include "capturetool.h" -class AbstractActionTool : public CaptureTool { - Q_OBJECT +class AbstractActionTool : public CaptureTool +{ + Q_OBJECT public: - explicit AbstractActionTool(QObject *parent = nullptr); + explicit AbstractActionTool(QObject* parent = nullptr); - bool isValid() const override; - bool isSelectable() const override; - bool showMousePreview() const override; + bool isValid() const override; + bool isSelectable() const override; + bool showMousePreview() const override; - void undo(QPixmap &pixmap) override; - void process(QPainter &painter, const QPixmap &pixmap, bool recordUndo = false) override; - void paintMousePreview(QPainter &painter, const CaptureContext &context) override; + void undo(QPixmap& pixmap) override; + void process(QPainter& painter, + const QPixmap& pixmap, + bool recordUndo = false) override; + void paintMousePreview(QPainter& painter, + const CaptureContext& context) override; public slots: - void drawEnd(const QPoint &p) override; - void drawMove(const QPoint &p) override; - void drawStart(const CaptureContext &context) override; - void colorChanged(const QColor &c) override; - void thicknessChanged(const int th) override; + void drawEnd(const QPoint& p) override; + void drawMove(const QPoint& p) override; + void drawStart(const CaptureContext& context) override; + void colorChanged(const QColor& c) override; + void thicknessChanged(const int th) override; }; diff --git a/src/tools/abstractpathtool.cpp b/src/tools/abstractpathtool.cpp index 7f212c91..2ea55b3a 100644 --- a/src/tools/abstractpathtool.cpp +++ b/src/tools/abstractpathtool.cpp @@ -17,68 +17,89 @@ #include "abstractpathtool.h" -AbstractPathTool::AbstractPathTool(QObject *parent) : - CaptureTool(parent), m_thickness(0), m_padding(0) +AbstractPathTool::AbstractPathTool(QObject* parent) + : CaptureTool(parent) + , m_thickness(0) + , m_padding(0) +{} + +bool +AbstractPathTool::isValid() const { - + return m_points.length() > 1; } -bool AbstractPathTool::isValid() const { - return m_points.length() > 1; +bool +AbstractPathTool::closeOnButtonPressed() const +{ + return false; } -bool AbstractPathTool::closeOnButtonPressed() const { - return false; +bool +AbstractPathTool::isSelectable() const +{ + return true; } -bool AbstractPathTool::isSelectable() const { - return true; +bool +AbstractPathTool::showMousePreview() const +{ + return true; } -bool AbstractPathTool::showMousePreview() const { - return true; +void +AbstractPathTool::undo(QPixmap& pixmap) +{ + QPainter p(&pixmap); + const int val = m_thickness + m_padding; + QRect area = m_backupArea + QMargins(val, val, val, val); + p.drawPixmap(area.intersected(pixmap.rect()).topLeft(), m_pixmapBackup); } -void AbstractPathTool::undo(QPixmap &pixmap) { - QPainter p(&pixmap); - const int val = m_thickness + m_padding; - QRect area = m_backupArea + QMargins(val, val, val, val); - p.drawPixmap(area.intersected(pixmap.rect()) - .topLeft(), m_pixmapBackup); +void +AbstractPathTool::drawEnd(const QPoint& p) +{ + Q_UNUSED(p); } -void AbstractPathTool::drawEnd(const QPoint &p) { - Q_UNUSED(p); +void +AbstractPathTool::drawMove(const QPoint& p) +{ + addPoint(p); } -void AbstractPathTool::drawMove(const QPoint &p) { - addPoint(p); +void +AbstractPathTool::colorChanged(const QColor& c) +{ + m_color = c; } -void AbstractPathTool::colorChanged(const QColor &c) { - m_color = c; +void +AbstractPathTool::thicknessChanged(const int th) +{ + m_thickness = th; } -void AbstractPathTool::thicknessChanged(const int th) { - m_thickness = th; +void +AbstractPathTool::updateBackup(const QPixmap& pixmap) +{ + const int val = m_thickness + m_padding; + QRect area = m_backupArea.normalized() + QMargins(val, val, val, val); + m_pixmapBackup = pixmap.copy(area); } -void AbstractPathTool::updateBackup(const QPixmap &pixmap) { - const int val = m_thickness + m_padding; - QRect area = m_backupArea.normalized() + QMargins(val, val, val, val); - m_pixmapBackup = pixmap.copy(area); -} - -void AbstractPathTool::addPoint(const QPoint &point) { - if (m_backupArea.left() > point.x()) { - m_backupArea.setLeft(point.x()); - } else if (m_backupArea.right() < point.x()) { - m_backupArea.setRight(point.x()); - } - if (m_backupArea.top() > point.y()) { - m_backupArea.setTop(point.y()); - } else if (m_backupArea.bottom() < point.y()) { - m_backupArea.setBottom(point.y()); - } - m_points.append(point); +void +AbstractPathTool::addPoint(const QPoint& point) +{ + if (m_backupArea.left() > point.x()) { + m_backupArea.setLeft(point.x()); + } else if (m_backupArea.right() < point.x()) { + m_backupArea.setRight(point.x()); + } + if (m_backupArea.top() > point.y()) { + m_backupArea.setTop(point.y()); + } else if (m_backupArea.bottom() < point.y()) { + m_backupArea.setBottom(point.y()); + } + m_points.append(point); } diff --git a/src/tools/abstractpathtool.h b/src/tools/abstractpathtool.h index e2d0a536..fcff6846 100644 --- a/src/tools/abstractpathtool.h +++ b/src/tools/abstractpathtool.h @@ -19,33 +19,34 @@ #include "capturetool.h" -class AbstractPathTool : public CaptureTool { - Q_OBJECT +class AbstractPathTool : public CaptureTool +{ + Q_OBJECT public: - explicit AbstractPathTool(QObject *parent = nullptr); + explicit AbstractPathTool(QObject* parent = nullptr); - bool isValid() const override; - bool closeOnButtonPressed() const override; - bool isSelectable() const override; - bool showMousePreview() const override; + bool isValid() const override; + bool closeOnButtonPressed() const override; + bool isSelectable() const override; + bool showMousePreview() const override; - void undo(QPixmap &pixmap) override; + void undo(QPixmap& pixmap) override; public slots: - void drawEnd(const QPoint &p) override; - void drawMove(const QPoint &p) override; - void colorChanged(const QColor &c) override; - void thicknessChanged(const int th) override; + void drawEnd(const QPoint& p) override; + void drawMove(const QPoint& p) override; + void colorChanged(const QColor& c) override; + void thicknessChanged(const int th) override; protected: - void updateBackup(const QPixmap &pixmap); - void addPoint(const QPoint &point); + void updateBackup(const QPixmap& pixmap); + void addPoint(const QPoint& point); - QPixmap m_pixmapBackup; - QRect m_backupArea; - QColor m_color; - QVector m_points; - int m_thickness; - // use m_padding to extend the area of the backup - int m_padding; + QPixmap m_pixmapBackup; + QRect m_backupArea; + QColor m_color; + QVector m_points; + int m_thickness; + // use m_padding to extend the area of the backup + int m_padding; }; diff --git a/src/tools/abstracttwopointtool.cpp b/src/tools/abstracttwopointtool.cpp index 3061c98c..b8f47799 100644 --- a/src/tools/abstracttwopointtool.cpp +++ b/src/tools/abstracttwopointtool.cpp @@ -23,113 +23,145 @@ namespace { const double ADJ_UNIT = std::atan(1.0); const int DIRS_NUMBER = 4; -enum UNIT { - HORIZ_DIR = 0, - DIAG1_DIR = 1, - VERT_DIR = 2, - DIAG2_DIR = 3 +enum UNIT +{ + HORIZ_DIR = 0, + DIAG1_DIR = 1, + VERT_DIR = 2, + DIAG2_DIR = 3 }; const double ADJ_DIAG_UNIT = 2 * ADJ_UNIT; const int DIAG_DIRS_NUMBER = 2; -enum DIAG_UNIT { - DIR1 = 0, - DIR2 = 1 +enum DIAG_UNIT +{ + DIR1 = 0, + DIR2 = 1 }; } -AbstractTwoPointTool::AbstractTwoPointTool(QObject *parent) : - CaptureTool(parent), m_thickness(0), m_padding(0) +AbstractTwoPointTool::AbstractTwoPointTool(QObject* parent) + : CaptureTool(parent) + , m_thickness(0) + , m_padding(0) +{} + +bool +AbstractTwoPointTool::isValid() const { - + return (m_points.first != m_points.second); } -bool AbstractTwoPointTool::isValid() const { - return (m_points.first != m_points.second); +bool +AbstractTwoPointTool::closeOnButtonPressed() const +{ + return false; } -bool AbstractTwoPointTool::closeOnButtonPressed() const { - return false; +bool +AbstractTwoPointTool::isSelectable() const +{ + return true; } -bool AbstractTwoPointTool::isSelectable() const { - return true; +bool +AbstractTwoPointTool::showMousePreview() const +{ + return true; } -bool AbstractTwoPointTool::showMousePreview() const { - return true; +void +AbstractTwoPointTool::undo(QPixmap& pixmap) +{ + QPainter p(&pixmap); + p.drawPixmap(backupRect(pixmap.rect()).topLeft(), m_pixmapBackup); } -void AbstractTwoPointTool::undo(QPixmap &pixmap) { - QPainter p(&pixmap); - p.drawPixmap(backupRect(pixmap.rect()).topLeft(), m_pixmapBackup); +void +AbstractTwoPointTool::drawEnd(const QPoint& p) +{ + Q_UNUSED(p); } -void AbstractTwoPointTool::drawEnd(const QPoint &p) { - Q_UNUSED(p); +void +AbstractTwoPointTool::drawMove(const QPoint& p) +{ + m_points.second = p; } -void AbstractTwoPointTool::drawMove(const QPoint &p) { - m_points.second = p; +void +AbstractTwoPointTool::drawMoveWithAdjustment(const QPoint& p) +{ + m_points.second = m_points.first + adjustedVector(p - m_points.first); } -void AbstractTwoPointTool::drawMoveWithAdjustment(const QPoint &p) { - m_points.second = m_points.first + adjustedVector(p - m_points.first); +void +AbstractTwoPointTool::colorChanged(const QColor& c) +{ + m_color = c; } -void AbstractTwoPointTool::colorChanged(const QColor &c) { - m_color = c; +void +AbstractTwoPointTool::thicknessChanged(const int th) +{ + m_thickness = th; } -void AbstractTwoPointTool::thicknessChanged(const int th) { - m_thickness = th; +void +AbstractTwoPointTool::updateBackup(const QPixmap& pixmap) +{ + m_pixmapBackup = pixmap.copy(backupRect(pixmap.rect())); } -void AbstractTwoPointTool::updateBackup(const QPixmap &pixmap) { - m_pixmapBackup = pixmap.copy(backupRect(pixmap.rect())); +QRect +AbstractTwoPointTool::backupRect(const QRect& limits) const +{ + QRect r = QRect(m_points.first, m_points.second).normalized(); + const int val = m_thickness + m_padding; + r += QMargins(val, val, val, val); + return r.intersected(limits); } -QRect AbstractTwoPointTool::backupRect(const QRect &limits) const { - QRect r = QRect(m_points.first, m_points.second).normalized(); - const int val = m_thickness + m_padding; - r += QMargins(val, val, val, val); - return r.intersected(limits); -} - -QPoint AbstractTwoPointTool::adjustedVector(QPoint v) const { - if (m_supportsOrthogonalAdj && m_supportsDiagonalAdj) { - int dir = ( static_cast(round(atan2(-v.y(), v.x()) / ADJ_UNIT)) + DIRS_NUMBER ) % DIRS_NUMBER; - if (dir == UNIT::HORIZ_DIR) { - v.setY(0); - } else if (dir == UNIT::VERT_DIR) { - v.setX(0); - } else if (dir == UNIT::DIAG1_DIR) { - int newX = (v.x() - v.y()) / 2; - int newY = -newX; - v.setX(newX); - v.setY(newY); - } else { - int newX = (v.x() + v.y()) / 2; - int newY = newX; - v.setX(newX); - v.setY(newY); - } - } else if (m_supportsDiagonalAdj) { - int dir = ( static_cast(round((atan2(-v.y(), v.x()) - ADJ_DIAG_UNIT / 2) / ADJ_DIAG_UNIT)) - + DIAG_DIRS_NUMBER ) % DIAG_DIRS_NUMBER; - if (dir == DIAG_UNIT::DIR1) { - int newX = (v.x() - v.y()) / 2; - int newY = -newX; - v.setX(newX); - v.setY(newY); - } else { - int newX = (v.x() + v.y()) / 2; - int newY = newX; - v.setX(newX); - v.setY(newY); - } +QPoint +AbstractTwoPointTool::adjustedVector(QPoint v) const +{ + if (m_supportsOrthogonalAdj && m_supportsDiagonalAdj) { + int dir = + (static_cast(round(atan2(-v.y(), v.x()) / ADJ_UNIT)) + DIRS_NUMBER) % + DIRS_NUMBER; + if (dir == UNIT::HORIZ_DIR) { + v.setY(0); + } else if (dir == UNIT::VERT_DIR) { + v.setX(0); + } else if (dir == UNIT::DIAG1_DIR) { + int newX = (v.x() - v.y()) / 2; + int newY = -newX; + v.setX(newX); + v.setY(newY); + } else { + int newX = (v.x() + v.y()) / 2; + int newY = newX; + v.setX(newX); + v.setY(newY); } - return v; + } else if (m_supportsDiagonalAdj) { + int dir = (static_cast(round( + (atan2(-v.y(), v.x()) - ADJ_DIAG_UNIT / 2) / ADJ_DIAG_UNIT)) + + DIAG_DIRS_NUMBER) % + DIAG_DIRS_NUMBER; + if (dir == DIAG_UNIT::DIR1) { + int newX = (v.x() - v.y()) / 2; + int newY = -newX; + v.setX(newX); + v.setY(newY); + } else { + int newX = (v.x() + v.y()) / 2; + int newY = newX; + v.setX(newX); + v.setY(newY); + } + } + return v; } diff --git a/src/tools/abstracttwopointtool.h b/src/tools/abstracttwopointtool.h index 9a979ef3..5e512a25 100644 --- a/src/tools/abstracttwopointtool.h +++ b/src/tools/abstracttwopointtool.h @@ -19,39 +19,40 @@ #include "capturetool.h" -class AbstractTwoPointTool : public CaptureTool { - Q_OBJECT +class AbstractTwoPointTool : public CaptureTool +{ + Q_OBJECT public: - explicit AbstractTwoPointTool(QObject *parent = nullptr); + explicit AbstractTwoPointTool(QObject* parent = nullptr); - bool isValid() const override; - bool closeOnButtonPressed() const override; - bool isSelectable() const override; - bool showMousePreview() const override; + bool isValid() const override; + bool closeOnButtonPressed() const override; + bool isSelectable() const override; + bool showMousePreview() const override; - void undo(QPixmap &pixmap) override; + void undo(QPixmap& pixmap) override; public slots: - void drawEnd(const QPoint &p) override; - void drawMove(const QPoint &p) override; - void drawMoveWithAdjustment(const QPoint &p) override; - void colorChanged(const QColor &c) override; - void thicknessChanged(const int th) override; + void drawEnd(const QPoint& p) override; + void drawMove(const QPoint& p) override; + void drawMoveWithAdjustment(const QPoint& p) override; + void colorChanged(const QColor& c) override; + void thicknessChanged(const int th) override; protected: - void updateBackup(const QPixmap &pixmap); - QRect backupRect(const QRect &limits) const; + void updateBackup(const QPixmap& pixmap); + QRect backupRect(const QRect& limits) const; - QPixmap m_pixmapBackup; - QPair m_points; - QColor m_color; - int m_thickness; - // use m_padding to extend the area of the backup - int m_padding; + QPixmap m_pixmapBackup; + QPair m_points; + QColor m_color; + int m_thickness; + // use m_padding to extend the area of the backup + int m_padding; - bool m_supportsOrthogonalAdj = false; - bool m_supportsDiagonalAdj = false; + bool m_supportsOrthogonalAdj = false; + bool m_supportsDiagonalAdj = false; private: - QPoint adjustedVector(QPoint v) const; + QPoint adjustedVector(QPoint v) const; }; diff --git a/src/tools/arrow/arrowtool.cpp b/src/tools/arrow/arrowtool.cpp index dd854017..4603279f 100644 --- a/src/tools/arrow/arrowtool.cpp +++ b/src/tools/arrow/arrowtool.cpp @@ -24,97 +24,123 @@ namespace { const int ArrowWidth = 10; const int ArrowHeight = 18; -QPainterPath getArrowHead(QPoint p1, QPoint p2, const int thickness) { - QLineF base(p1, p2); - // Create the vector for the position of the base of the arrowhead - QLineF temp(QPoint(0,0), p2-p1); - int val = ArrowHeight + thickness*4; - if (base.length() < val) { - val = (base.length() + thickness*2); - } - temp.setLength(base.length() + thickness*2 - val); - // Move across the line up to the head - QPointF bottonTranslation(temp.p2()); +QPainterPath +getArrowHead(QPoint p1, QPoint p2, const int thickness) +{ + QLineF base(p1, p2); + // Create the vector for the position of the base of the arrowhead + QLineF temp(QPoint(0, 0), p2 - p1); + int val = ArrowHeight + thickness * 4; + if (base.length() < val) { + val = (base.length() + thickness * 2); + } + temp.setLength(base.length() + thickness * 2 - val); + // Move across the line up to the head + QPointF bottonTranslation(temp.p2()); - // Rotate base of the arrowhead - base.setLength(ArrowWidth + thickness*2); - base.setAngle(base.angle() + 90); - // Move to the correct point - QPointF temp2 = p1 - base.p2(); - // Center it - QPointF centerTranslation((temp2.x()/2), (temp2.y()/2)); + // Rotate base of the arrowhead + base.setLength(ArrowWidth + thickness * 2); + base.setAngle(base.angle() + 90); + // Move to the correct point + QPointF temp2 = p1 - base.p2(); + // Center it + QPointF centerTranslation((temp2.x() / 2), (temp2.y() / 2)); - base.translate(bottonTranslation); - base.translate(centerTranslation); + base.translate(bottonTranslation); + base.translate(centerTranslation); - QPainterPath path; - path.moveTo(p2); - path.lineTo(base.p1()); - path.lineTo(base.p2()); - path.lineTo(p2); - return path; + QPainterPath path; + path.moveTo(p2); + path.lineTo(base.p1()); + path.lineTo(base.p2()); + path.lineTo(p2); + return path; } // gets a shorter line to prevent overlap in the point of the arrow -QLine getShorterLine(QPoint p1, QPoint p2, const int thickness) { - QLineF l(p1, p2); - int val = ArrowHeight + thickness*4; - if (l.length() < val) { - val = (l.length() + thickness*2); - } - l.setLength(l.length() + thickness*2 - val); - return l.toLine(); +QLine +getShorterLine(QPoint p1, QPoint p2, const int thickness) +{ + QLineF l(p1, p2); + int val = ArrowHeight + thickness * 4; + if (l.length() < val) { + val = (l.length() + thickness * 2); + } + l.setLength(l.length() + thickness * 2 - val); + return l.toLine(); } } // unnamed namespace -ArrowTool::ArrowTool(QObject *parent) : AbstractTwoPointTool(parent) { - m_padding = ArrowWidth / 2; - m_supportsOrthogonalAdj = true; - m_supportsDiagonalAdj = true; +ArrowTool::ArrowTool(QObject* parent) + : AbstractTwoPointTool(parent) +{ + m_padding = ArrowWidth / 2; + m_supportsOrthogonalAdj = true; + m_supportsDiagonalAdj = true; } -QIcon ArrowTool::icon(const QColor &background, bool inEditor) const { - Q_UNUSED(inEditor); - return QIcon(iconPath(background) + "arrow-bottom-left.svg"); +QIcon +ArrowTool::icon(const QColor& background, bool inEditor) const +{ + Q_UNUSED(inEditor); + return QIcon(iconPath(background) + "arrow-bottom-left.svg"); } -QString ArrowTool::name() const { - return tr("Arrow"); +QString +ArrowTool::name() const +{ + return tr("Arrow"); } -QString ArrowTool::nameID() { - return QLatin1String(""); +QString +ArrowTool::nameID() +{ + return QLatin1String(""); } -QString ArrowTool::description() const { - return tr("Set the Arrow as the paint tool"); +QString +ArrowTool::description() const +{ + return tr("Set the Arrow as the paint tool"); } -CaptureTool* ArrowTool::copy(QObject *parent) { - return new ArrowTool(parent); +CaptureTool* +ArrowTool::copy(QObject* parent) +{ + return new ArrowTool(parent); } -void ArrowTool::process(QPainter &painter, const QPixmap &pixmap, bool recordUndo) { - if (recordUndo) { - updateBackup(pixmap); - } - painter.setPen(QPen(m_color, m_thickness)); - painter.drawLine(getShorterLine(m_points.first, m_points.second, m_thickness)); - painter.fillPath(getArrowHead(m_points.first, m_points.second, m_thickness), QBrush(m_color)); +void +ArrowTool::process(QPainter& painter, const QPixmap& pixmap, bool recordUndo) +{ + if (recordUndo) { + updateBackup(pixmap); + } + painter.setPen(QPen(m_color, m_thickness)); + painter.drawLine( + getShorterLine(m_points.first, m_points.second, m_thickness)); + painter.fillPath(getArrowHead(m_points.first, m_points.second, m_thickness), + QBrush(m_color)); } -void ArrowTool::paintMousePreview(QPainter &painter, const CaptureContext &context) { - painter.setPen(QPen(context.color, PADDING_VALUE + context.thickness)); - painter.drawLine(context.mousePos, context.mousePos); +void +ArrowTool::paintMousePreview(QPainter& painter, const CaptureContext& context) +{ + painter.setPen(QPen(context.color, PADDING_VALUE + context.thickness)); + painter.drawLine(context.mousePos, context.mousePos); } -void ArrowTool::drawStart(const CaptureContext &context) { - m_color = context.color; - m_thickness = context.thickness + PADDING_VALUE; - m_points.first = context.mousePos; - m_points.second = context.mousePos; +void +ArrowTool::drawStart(const CaptureContext& context) +{ + m_color = context.color; + m_thickness = context.thickness + PADDING_VALUE; + m_points.first = context.mousePos; + m_points.second = context.mousePos; } -void ArrowTool::pressed(const CaptureContext &context) { - Q_UNUSED(context); +void +ArrowTool::pressed(const CaptureContext& context) +{ + Q_UNUSED(context); } diff --git a/src/tools/arrow/arrowtool.h b/src/tools/arrow/arrowtool.h index add23691..dd7db9e3 100644 --- a/src/tools/arrow/arrowtool.h +++ b/src/tools/arrow/arrowtool.h @@ -21,22 +21,25 @@ #include #include -class ArrowTool : public AbstractTwoPointTool { - Q_OBJECT +class ArrowTool : public AbstractTwoPointTool +{ + Q_OBJECT public: - explicit ArrowTool(QObject *parent = nullptr); + explicit ArrowTool(QObject* parent = nullptr); - QIcon icon(const QColor &background, bool inEditor) const override; - QString name() const override; - static QString nameID(); - QString description() const override; + QIcon icon(const QColor& background, bool inEditor) const override; + QString name() const override; + static QString nameID(); + QString description() const override; - CaptureTool* copy(QObject *parent = nullptr) override; - void process( - QPainter &painter, const QPixmap &pixmap, bool recordUndo = false) override; - void paintMousePreview(QPainter &painter, const CaptureContext &context) override; + CaptureTool* copy(QObject* parent = nullptr) override; + void process(QPainter& painter, + const QPixmap& pixmap, + bool recordUndo = false) override; + void paintMousePreview(QPainter& painter, + const CaptureContext& context) override; public slots: - void drawStart(const CaptureContext &context) override; - void pressed(const CaptureContext &context) override; + void drawStart(const CaptureContext& context) override; + void pressed(const CaptureContext& context) override; }; diff --git a/src/tools/blur/blurtool.cpp b/src/tools/blur/blurtool.cpp index 597e326d..4dd7b653 100644 --- a/src/tools/blur/blurtool.cpp +++ b/src/tools/blur/blurtool.cpp @@ -23,41 +23,59 @@ #include #include -BlurTool::BlurTool(QObject *parent) : AbstractTwoPointTool(parent) {} +BlurTool::BlurTool(QObject* parent) + : AbstractTwoPointTool(parent) +{} -QIcon BlurTool::icon(const QColor &background, bool inEditor) const +QIcon +BlurTool::icon(const QColor& background, bool inEditor) const { Q_UNUSED(inEditor); return QIcon(iconPath(background) + "blur.svg"); } -QString BlurTool::name() const { return tr("Blur"); } +QString +BlurTool::name() const +{ + return tr("Blur"); +} -QString BlurTool::nameID() { return QLatin1String(""); } +QString +BlurTool::nameID() +{ + return QLatin1String(""); +} -QString BlurTool::description() const +QString +BlurTool::description() const { return tr("Set Blur as the paint tool"); } -CaptureTool *BlurTool::copy(QObject *parent) { return new BlurTool(parent); } +CaptureTool* +BlurTool::copy(QObject* parent) +{ + return new BlurTool(parent); +} -void write_block(QImage &image, int x_start, int y_start, int pixel_size, - QRgb block_color) +void +write_block(QImage& image, + int x_start, + int y_start, + int pixel_size, + QRgb block_color) { assert(x_start + pixel_size < image.width()); assert(y_start + pixel_size < image.height()); - for (auto x = x_start; x < x_start + pixel_size; x++) - { - for (auto y = y_start; y < y_start + pixel_size; y++) - { + for (auto x = x_start; x < x_start + pixel_size; x++) { + for (auto y = y_start; y < y_start + pixel_size; y++) { image.setPixel(x, y, block_color); } } } -QRgb calculate_block_averge(QImage &image, int x_start, int y_start, - int pixel_size) +QRgb +calculate_block_averge(QImage& image, int x_start, int y_start, int pixel_size) { assert(x_start + pixel_size < image.width()); assert(y_start + pixel_size < image.height()); @@ -66,10 +84,8 @@ QRgb calculate_block_averge(QImage &image, int x_start, int y_start, int blue_count = 0; int green_count = 0; int pixel_count = 0; - for (auto x = x_start; x < x_start + pixel_size; x++) - { - for (auto y = y_start; y < y_start + pixel_size; y++) - { + for (auto x = x_start; x < x_start + pixel_size; x++) { + for (auto y = y_start; y < y_start + pixel_size; y++) { auto pixel = image.pixel(x, y); red_count += qRed(pixel); @@ -78,51 +94,46 @@ QRgb calculate_block_averge(QImage &image, int x_start, int y_start, pixel_count++; } } - return (qRgb(red_count / pixel_count, green_count / pixel_count, + return (qRgb(red_count / pixel_count, + green_count / pixel_count, blue_count / pixel_count)); } -void BlurTool::process(QPainter &painter, const QPixmap &pixmap, - bool recordUndo) +void +BlurTool::process(QPainter& painter, const QPixmap& pixmap, bool recordUndo) { - if (recordUndo) - { + if (recordUndo) { updateBackup(pixmap); } - QPoint &p0 = m_points.first; - QPoint &p1 = m_points.second; + QPoint& p0 = m_points.first; + QPoint& p1 = m_points.second; auto pixelRatio = pixmap.devicePixelRatio(); QRect selection = QRect(p0, p1).normalized(); QRect selectionScaled = QRect(p0 * pixelRatio, p1 * pixelRatio).normalized(); - QPixmap *source = new QPixmap(pixmap.copy(selectionScaled)); + QPixmap* source = new QPixmap(pixmap.copy(selectionScaled)); - QImage original_image{source->toImage()}; - QImage imageResult{source->toImage()}; + QImage original_image{ source->toImage() }; + QImage imageResult{ source->toImage() }; unsigned int pixel_size = m_thickness; - if (pixel_size < 1) - { - pixel_size =1; + if (pixel_size < 1) { + pixel_size = 1; } - const unsigned int width = source->width(); const unsigned int height = source->height(); // Don't start pixelating until the region is at least as big as the pixel - if ((width > pixel_size) && (height > pixel_size)) - { - for (unsigned int x = 0; x < (width - pixel_size); x += pixel_size) - { - for (unsigned int y = 0; y < (height - pixel_size); y += pixel_size) - { + if ((width > pixel_size) && (height > pixel_size)) { + for (unsigned int x = 0; x < (width - pixel_size); x += pixel_size) { + for (unsigned int y = 0; y < (height - pixel_size); y += pixel_size) { auto block_color = calculate_block_averge(original_image, x, y, pixel_size); write_block(imageResult, x, y, pixel_size, block_color); } } } - QPixmap result{QPixmap::fromImage(imageResult)}; + QPixmap result{ QPixmap::fromImage(imageResult) }; QGraphicsScene scene; scene.addPixmap(result); @@ -130,18 +141,23 @@ void BlurTool::process(QPainter &painter, const QPixmap &pixmap, scene.render(&painter, selection, QRectF()); } -void BlurTool::paintMousePreview(QPainter &painter, - const CaptureContext &context) +void +BlurTool::paintMousePreview(QPainter& painter, const CaptureContext& context) { Q_UNUSED(context); Q_UNUSED(painter); } -void BlurTool::drawStart(const CaptureContext &context) +void +BlurTool::drawStart(const CaptureContext& context) { m_thickness = context.thickness; m_points.first = context.mousePos; m_points.second = context.mousePos; } -void BlurTool::pressed(const CaptureContext &context) { Q_UNUSED(context); } +void +BlurTool::pressed(const CaptureContext& context) +{ + Q_UNUSED(context); +} diff --git a/src/tools/blur/blurtool.h b/src/tools/blur/blurtool.h index aa549a61..e9fca4f7 100644 --- a/src/tools/blur/blurtool.h +++ b/src/tools/blur/blurtool.h @@ -19,22 +19,25 @@ #include "src/tools/abstracttwopointtool.h" -class BlurTool : public AbstractTwoPointTool { - Q_OBJECT +class BlurTool : public AbstractTwoPointTool +{ + Q_OBJECT public: - explicit BlurTool(QObject *parent = nullptr); + explicit BlurTool(QObject* parent = nullptr); - QIcon icon(const QColor &background, bool inEditor) const override; - QString name() const override; - static QString nameID(); - QString description() const override; + QIcon icon(const QColor& background, bool inEditor) const override; + QString name() const override; + static QString nameID(); + QString description() const override; - CaptureTool* copy(QObject *parent = nullptr) override; - void process( - QPainter &painter, const QPixmap &pixmap, bool recordUndo = false) override; - void paintMousePreview(QPainter &painter, const CaptureContext &context) override; + CaptureTool* copy(QObject* parent = nullptr) override; + void process(QPainter& painter, + const QPixmap& pixmap, + bool recordUndo = false) override; + void paintMousePreview(QPainter& painter, + const CaptureContext& context) override; public slots: - void drawStart(const CaptureContext &context) override; - void pressed(const CaptureContext &context) override; + void drawStart(const CaptureContext& context) override; + void pressed(const CaptureContext& context) override; }; diff --git a/src/tools/capturecontext.cpp b/src/tools/capturecontext.cpp index 2af6593e..01f41cbc 100644 --- a/src/tools/capturecontext.cpp +++ b/src/tools/capturecontext.cpp @@ -17,11 +17,12 @@ #include "capturecontext.h" -QPixmap CaptureContext::selectedScreenshotArea() const { - if (selection.isNull()) { - return screenshot; - } else { - return screenshot.copy(selection); - } +QPixmap +CaptureContext::selectedScreenshotArea() const +{ + if (selection.isNull()) { + return screenshot; + } else { + return screenshot.copy(selection); + } } - diff --git a/src/tools/capturecontext.h b/src/tools/capturecontext.h index 9ce19148..c4153a1f 100644 --- a/src/tools/capturecontext.h +++ b/src/tools/capturecontext.h @@ -17,33 +17,34 @@ #pragma once -#include -#include -#include #include +#include +#include +#include -struct CaptureContext { - // screenshot with modifications - QPixmap screenshot; - // unmodified screenshot - QPixmap origScreenshot; - // Selection area - QRect selection; - // Widget dimensions - QRect widgetDimensions; - // Selected tool color - QColor color; - // Path where the content has to be saved - QString savePath; - // Ofset of the capture widget based on the system's screen (top-left) - QPoint widgetOffset; - // Mouse position inside the widget - QPoint mousePos; - // Value of the desired thickness - int thickness; - int circleCount; - // Mode of the capture widget - bool fullscreen; +struct CaptureContext +{ + // screenshot with modifications + QPixmap screenshot; + // unmodified screenshot + QPixmap origScreenshot; + // Selection area + QRect selection; + // Widget dimensions + QRect widgetDimensions; + // Selected tool color + QColor color; + // Path where the content has to be saved + QString savePath; + // Ofset of the capture widget based on the system's screen (top-left) + QPoint widgetOffset; + // Mouse position inside the widget + QPoint mousePos; + // Value of the desired thickness + int thickness; + int circleCount; + // Mode of the capture widget + bool fullscreen; - QPixmap selectedScreenshotArea() const ; + QPixmap selectedScreenshotArea() const; }; diff --git a/src/tools/capturetool.h b/src/tools/capturetool.h index 9f2382af..2deb2081 100644 --- a/src/tools/capturetool.h +++ b/src/tools/capturetool.h @@ -23,131 +23,128 @@ #include #include -class CaptureTool : public QObject { - Q_OBJECT +class CaptureTool : public QObject +{ + Q_OBJECT public: - // Request actions on the main widget - enum Request { - // Call close() in the editor. - REQ_CLOSE_GUI, - // Call hide() in the editor. - REQ_HIDE_GUI, - // Select the whole screen. - REQ_SELECT_ALL, - // Disable the selection. - REQ_HIDE_SELECTION, - // Undo the last active modification in the stack. - REQ_UNDO_MODIFICATION, - // Redo the next modification in the stack. - REQ_REDO_MODIFICATION, - // Remove all the modifications. - REQ_CLEAR_MODIFICATIONS, - // Disable the active tool. - REQ_MOVE_MODE, - // Open the color picker under the mouse. - REQ_SHOW_COLOR_PICKER, - // Open/Close the side-panel. - REQ_TOGGLE_SIDEBAR, - // Call update() in the editor. - REQ_REDRAW, - // Append this tool to the undo/redo stack - REQ_APPEND_TO_STACK, - // Notify is the screenshot has been saved. - REQ_CAPTURE_DONE_OK, - // Instance this->widget()'s widget inside the editor under the mouse. - REQ_ADD_CHILD_WIDGET, - // Instance this->widget()'s widget as a window which closes after - // closing the editor. - REQ_ADD_CHILD_WINDOW, - // Instance this->widget()'s widget which handles its own lifetime. - REQ_ADD_EXTERNAL_WIDGETS, + // Request actions on the main widget + enum Request + { + // Call close() in the editor. + REQ_CLOSE_GUI, + // Call hide() in the editor. + REQ_HIDE_GUI, + // Select the whole screen. + REQ_SELECT_ALL, + // Disable the selection. + REQ_HIDE_SELECTION, + // Undo the last active modification in the stack. + REQ_UNDO_MODIFICATION, + // Redo the next modification in the stack. + REQ_REDO_MODIFICATION, + // Remove all the modifications. + REQ_CLEAR_MODIFICATIONS, + // Disable the active tool. + REQ_MOVE_MODE, + // Open the color picker under the mouse. + REQ_SHOW_COLOR_PICKER, + // Open/Close the side-panel. + REQ_TOGGLE_SIDEBAR, + // Call update() in the editor. + REQ_REDRAW, + // Append this tool to the undo/redo stack + REQ_APPEND_TO_STACK, + // Notify is the screenshot has been saved. + REQ_CAPTURE_DONE_OK, + // Instance this->widget()'s widget inside the editor under the mouse. + REQ_ADD_CHILD_WIDGET, + // Instance this->widget()'s widget as a window which closes after + // closing the editor. + REQ_ADD_CHILD_WINDOW, + // Instance this->widget()'s widget which handles its own lifetime. + REQ_ADD_EXTERNAL_WIDGETS, - REQ_INCREMENT_CIRCLE_COUNT, - }; + REQ_INCREMENT_CIRCLE_COUNT, + }; - explicit CaptureTool(QObject *parent = nullptr) : QObject(parent){} + explicit CaptureTool(QObject* parent = nullptr) + : QObject(parent) + {} - // Returns false when the tool is in an inconsistent state and shouldn't - // be included in the tool undo/redo stack. - virtual bool isValid() const = 0; - // Close the capture after the process() call if the tool was activated - // from a button press. - virtual bool closeOnButtonPressed() const = 0; - // If the tool keeps active after the selection. - virtual bool isSelectable() const = 0; - // Enable mouse preview. - virtual bool showMousePreview() const = 0; + // Returns false when the tool is in an inconsistent state and shouldn't + // be included in the tool undo/redo stack. + virtual bool isValid() const = 0; + // Close the capture after the process() call if the tool was activated + // from a button press. + virtual bool closeOnButtonPressed() const = 0; + // If the tool keeps active after the selection. + virtual bool isSelectable() const = 0; + // Enable mouse preview. + virtual bool showMousePreview() const = 0; - // The icon of the tool. - // inEditor is true when the icon is requested inside the editor - // and false otherwise. - virtual QIcon icon(const QColor &background, - bool inEditor) const = 0; - // Name displayed for the tool, this could be translated with tr() - virtual QString name() const = 0; - // Codename for the tool, this hsouldn't change as it is used as ID - // for the tool in the internals of Flameshot - static QString nameID(); - // Short description of the tool. - virtual QString description() const = 0; + // The icon of the tool. + // inEditor is true when the icon is requested inside the editor + // and false otherwise. + virtual QIcon icon(const QColor& background, bool inEditor) const = 0; + // Name displayed for the tool, this could be translated with tr() + virtual QString name() const = 0; + // Codename for the tool, this hsouldn't change as it is used as ID + // for the tool in the internals of Flameshot + static QString nameID(); + // Short description of the tool. + virtual QString description() const = 0; - // if the type is TYPE_WIDGET the widget is loaded in the main widget. - // If the type is TYPE_EXTERNAL_WIDGET it is created outside as an - // individual widget. - virtual QWidget* widget() { - return nullptr; - } - // When the tool is selected this method is called and the widget is added - // to the configuration panel inside the main widget. - virtual QWidget* configurationWidget() { - return nullptr; - } - // Permanent configuration used in the configuration outside of the - // capture. - virtual QWidget* permanentConfigurationWidget() { - return nullptr; - } - // Return a copy of the tool - virtual CaptureTool* copy(QObject *parent = nullptr) = 0; + // if the type is TYPE_WIDGET the widget is loaded in the main widget. + // If the type is TYPE_EXTERNAL_WIDGET it is created outside as an + // individual widget. + virtual QWidget* widget() { return nullptr; } + // When the tool is selected this method is called and the widget is added + // to the configuration panel inside the main widget. + virtual QWidget* configurationWidget() { return nullptr; } + // Permanent configuration used in the configuration outside of the + // capture. + virtual QWidget* permanentConfigurationWidget() { return nullptr; } + // Return a copy of the tool + virtual CaptureTool* copy(QObject* parent = nullptr) = 0; - // revert changes - virtual void undo(QPixmap &pixmap) = 0; - // Called every time the tool has to draw - // recordUndo indicates when the tool should save the information - // for the undo(), if the value is false calling undo() after - // that process should not modify revert the changes. - virtual void process(QPainter &painter, - const QPixmap &pixmap, - bool recordUndo = false) = 0; - // When the tool is selected, this is called when the mouse moves - virtual void paintMousePreview(QPainter &painter, const CaptureContext &context) = 0; + // revert changes + virtual void undo(QPixmap& pixmap) = 0; + // Called every time the tool has to draw + // recordUndo indicates when the tool should save the information + // for the undo(), if the value is false calling undo() after + // that process should not modify revert the changes. + virtual void process(QPainter& painter, + const QPixmap& pixmap, + bool recordUndo = false) = 0; + // When the tool is selected, this is called when the mouse moves + virtual void paintMousePreview(QPainter& painter, + const CaptureContext& context) = 0; signals: - void requestAction(Request r); + void requestAction(Request r); protected: - QString iconPath(const QColor &c) const { - return ColorUtils::colorIsDark(c) ? - PathInfo::whiteIconPath() : PathInfo::blackIconPath(); - } + QString iconPath(const QColor& c) const + { + return ColorUtils::colorIsDark(c) ? PathInfo::whiteIconPath() + : PathInfo::blackIconPath(); + } public slots: - // On mouse release. - virtual void drawEnd(const QPoint &p) = 0; - // Mouse pressed and moving, called once a pixel. - virtual void drawMove(const QPoint &p) = 0; - // Called when drawMove is needed with an adjustment; - // should be overridden in case an adjustment is applicable. - virtual void drawMoveWithAdjustment(const QPoint &p) { - drawMove(p); - } - // Called when the tool is activated. - virtual void drawStart(const CaptureContext &context) = 0; - // Called right after pressign the button which activates the tool. - virtual void pressed(const CaptureContext &context) = 0; - // Called when the color is changed in the editor. - virtual void colorChanged(const QColor &c) = 0; - // Called when the thickness of the tool is updated in the editor. - virtual void thicknessChanged(const int th) = 0; + // On mouse release. + virtual void drawEnd(const QPoint& p) = 0; + // Mouse pressed and moving, called once a pixel. + virtual void drawMove(const QPoint& p) = 0; + // Called when drawMove is needed with an adjustment; + // should be overridden in case an adjustment is applicable. + virtual void drawMoveWithAdjustment(const QPoint& p) { drawMove(p); } + // Called when the tool is activated. + virtual void drawStart(const CaptureContext& context) = 0; + // Called right after pressign the button which activates the tool. + virtual void pressed(const CaptureContext& context) = 0; + // Called when the color is changed in the editor. + virtual void colorChanged(const QColor& c) = 0; + // Called when the thickness of the tool is updated in the editor. + virtual void thicknessChanged(const int th) = 0; }; diff --git a/src/tools/circle/circletool.cpp b/src/tools/circle/circletool.cpp index ca6e187c..4c4f6491 100644 --- a/src/tools/circle/circletool.cpp +++ b/src/tools/circle/circletool.cpp @@ -22,50 +22,70 @@ namespace { #define PADDING_VALUE 2 } -CircleTool::CircleTool(QObject *parent) : AbstractTwoPointTool(parent) { - m_supportsDiagonalAdj = true; +CircleTool::CircleTool(QObject* parent) + : AbstractTwoPointTool(parent) +{ + m_supportsDiagonalAdj = true; } -QIcon CircleTool::icon(const QColor &background, bool inEditor) const { - Q_UNUSED(inEditor); - return QIcon(iconPath(background) + "circle-outline.svg"); +QIcon +CircleTool::icon(const QColor& background, bool inEditor) const +{ + Q_UNUSED(inEditor); + return QIcon(iconPath(background) + "circle-outline.svg"); } -QString CircleTool::name() const { - return tr("Circle"); +QString +CircleTool::name() const +{ + return tr("Circle"); } -QString CircleTool::nameID() { - return QLatin1String(""); +QString +CircleTool::nameID() +{ + return QLatin1String(""); } -QString CircleTool::description() const { - return tr("Set the Circle as the paint tool"); +QString +CircleTool::description() const +{ + return tr("Set the Circle as the paint tool"); } -CaptureTool* CircleTool::copy(QObject *parent) { - return new CircleTool(parent); +CaptureTool* +CircleTool::copy(QObject* parent) +{ + return new CircleTool(parent); } -void CircleTool::process(QPainter &painter, const QPixmap &pixmap, bool recordUndo) { - if (recordUndo) { - updateBackup(pixmap); - } - painter.setPen(QPen(m_color, m_thickness)); - painter.drawEllipse(QRect(m_points.first, m_points.second)); +void +CircleTool::process(QPainter& painter, const QPixmap& pixmap, bool recordUndo) +{ + if (recordUndo) { + updateBackup(pixmap); + } + painter.setPen(QPen(m_color, m_thickness)); + painter.drawEllipse(QRect(m_points.first, m_points.second)); } -void CircleTool::paintMousePreview(QPainter &painter, const CaptureContext &context) { - painter.setPen(QPen(context.color, PADDING_VALUE + context.thickness)); - painter.drawLine(context.mousePos, context.mousePos); +void +CircleTool::paintMousePreview(QPainter& painter, const CaptureContext& context) +{ + painter.setPen(QPen(context.color, PADDING_VALUE + context.thickness)); + painter.drawLine(context.mousePos, context.mousePos); } -void CircleTool::drawStart(const CaptureContext &context) { - m_color = context.color; - m_thickness = context.thickness + PADDING_VALUE; - m_points.first = context.mousePos; - m_points.second = context.mousePos; +void +CircleTool::drawStart(const CaptureContext& context) +{ + m_color = context.color; + m_thickness = context.thickness + PADDING_VALUE; + m_points.first = context.mousePos; + m_points.second = context.mousePos; } -void CircleTool::pressed(const CaptureContext &context) { - Q_UNUSED(context); +void +CircleTool::pressed(const CaptureContext& context) +{ + Q_UNUSED(context); } diff --git a/src/tools/circle/circletool.h b/src/tools/circle/circletool.h index ea4eb8e0..3a42b980 100644 --- a/src/tools/circle/circletool.h +++ b/src/tools/circle/circletool.h @@ -19,22 +19,25 @@ #include "src/tools/abstracttwopointtool.h" -class CircleTool : public AbstractTwoPointTool { - Q_OBJECT +class CircleTool : public AbstractTwoPointTool +{ + Q_OBJECT public: - explicit CircleTool(QObject *parent = nullptr); + explicit CircleTool(QObject* parent = nullptr); - QIcon icon(const QColor &background, bool inEditor) const override; - QString name() const override; - static QString nameID(); - QString description() const override; + QIcon icon(const QColor& background, bool inEditor) const override; + QString name() const override; + static QString nameID(); + QString description() const override; - CaptureTool* copy(QObject *parent = nullptr) override; - void process( - QPainter &painter, const QPixmap &pixmap, bool recordUndo = false) override; - void paintMousePreview(QPainter &painter, const CaptureContext &context) override; + CaptureTool* copy(QObject* parent = nullptr) override; + void process(QPainter& painter, + const QPixmap& pixmap, + bool recordUndo = false) override; + void paintMousePreview(QPainter& painter, + const CaptureContext& context) override; public slots: - void drawStart(const CaptureContext &context) override; - void pressed(const CaptureContext &context) override; + void drawStart(const CaptureContext& context) override; + void pressed(const CaptureContext& context) override; }; diff --git a/src/tools/circlecount/circlecounttool.cpp b/src/tools/circlecount/circlecounttool.cpp index 25494158..6c290417 100644 --- a/src/tools/circlecount/circlecounttool.cpp +++ b/src/tools/circlecount/circlecounttool.cpp @@ -21,55 +21,82 @@ namespace { #define PADDING_VALUE 2 } -CircleCountTool::CircleCountTool(QObject *parent) : AbstractTwoPointTool(parent) { - m_count = 0; +CircleCountTool::CircleCountTool(QObject* parent) + : AbstractTwoPointTool(parent) +{ + m_count = 0; } -QIcon CircleCountTool::icon(const QColor &background, bool inEditor) const { - Q_UNUSED(inEditor); - return QIcon(iconPath(background) + "circlecount-outline.svg"); +QIcon +CircleCountTool::icon(const QColor& background, bool inEditor) const +{ + Q_UNUSED(inEditor); + return QIcon(iconPath(background) + "circlecount-outline.svg"); } -QString CircleCountTool::name() const { - return tr("Circle Counter"); +QString +CircleCountTool::name() const +{ + return tr("Circle Counter"); } -QString CircleCountTool::nameID() { - return QLatin1String(""); +QString +CircleCountTool::nameID() +{ + return QLatin1String(""); } -QString CircleCountTool::description() const { - return tr("Add an autoincrementing counter bubble"); +QString +CircleCountTool::description() const +{ + return tr("Add an autoincrementing counter bubble"); } -CaptureTool* CircleCountTool::copy(QObject *parent) { - return new CircleCountTool(parent); +CaptureTool* +CircleCountTool::copy(QObject* parent) +{ + return new CircleCountTool(parent); } -void CircleCountTool::process(QPainter &painter, const QPixmap &pixmap, bool recordUndo) { - if (recordUndo) { - updateBackup(pixmap); - } - painter.setBrush(m_color); +void +CircleCountTool::process(QPainter& painter, + const QPixmap& pixmap, + bool recordUndo) +{ + if (recordUndo) { + updateBackup(pixmap); + } + painter.setBrush(m_color); - int bubble_size=16; - painter.drawEllipse(m_points.first,bubble_size,bubble_size); - painter.drawText(QRectF(m_points.first.x()-bubble_size/2, m_points.first.y()-bubble_size/2, bubble_size, bubble_size), Qt::AlignCenter, QString::number(m_count)); + int bubble_size = 16; + painter.drawEllipse(m_points.first, bubble_size, bubble_size); + painter.drawText(QRectF(m_points.first.x() - bubble_size / 2, + m_points.first.y() - bubble_size / 2, + bubble_size, + bubble_size), + Qt::AlignCenter, + QString::number(m_count)); } -void CircleCountTool::paintMousePreview(QPainter &painter, const CaptureContext &context) { - painter.setPen(QPen(context.color, PADDING_VALUE + context.thickness)); - painter.drawLine(context.mousePos, context.mousePos); +void +CircleCountTool::paintMousePreview(QPainter& painter, + const CaptureContext& context) +{ + painter.setPen(QPen(context.color, PADDING_VALUE + context.thickness)); + painter.drawLine(context.mousePos, context.mousePos); } -void CircleCountTool::drawStart(const CaptureContext &context) { - m_color = context.color; - m_thickness = context.thickness + PADDING_VALUE; - m_points.first = context.mousePos; - m_count = context.circleCount; - emit requestAction(REQ_INCREMENT_CIRCLE_COUNT); - +void +CircleCountTool::drawStart(const CaptureContext& context) +{ + m_color = context.color; + m_thickness = context.thickness + PADDING_VALUE; + m_points.first = context.mousePos; + m_count = context.circleCount; + emit requestAction(REQ_INCREMENT_CIRCLE_COUNT); } -void CircleCountTool::pressed(const CaptureContext &context) { - Q_UNUSED(context); +void +CircleCountTool::pressed(const CaptureContext& context) +{ + Q_UNUSED(context); } diff --git a/src/tools/circlecount/circlecounttool.h b/src/tools/circlecount/circlecounttool.h index 7893384a..7087a4b2 100644 --- a/src/tools/circlecount/circlecounttool.h +++ b/src/tools/circlecount/circlecounttool.h @@ -19,23 +19,27 @@ #include "src/tools/abstracttwopointtool.h" -class CircleCountTool : public AbstractTwoPointTool { - Q_OBJECT +class CircleCountTool : public AbstractTwoPointTool +{ + Q_OBJECT public: - explicit CircleCountTool(QObject *parent = nullptr); + explicit CircleCountTool(QObject* parent = nullptr); - QIcon icon(const QColor &background, bool inEditor) const override; - QString name() const override; - static QString nameID(); - QString description() const override; + QIcon icon(const QColor& background, bool inEditor) const override; + QString name() const override; + static QString nameID(); + QString description() const override; + + CaptureTool* copy(QObject* parent = nullptr) override; + void process(QPainter& painter, + const QPixmap& pixmap, + bool recordUndo = false) override; + void paintMousePreview(QPainter& painter, + const CaptureContext& context) override; - CaptureTool* copy(QObject *parent = nullptr) override; - void process( - QPainter &painter, const QPixmap &pixmap, bool recordUndo = false) override; - void paintMousePreview(QPainter &painter, const CaptureContext &context) override; private: - unsigned int m_count; + unsigned int m_count; public slots: - void drawStart(const CaptureContext &context) override; - void pressed(const CaptureContext &context) override; + void drawStart(const CaptureContext& context) override; + void pressed(const CaptureContext& context) override; }; diff --git a/src/tools/copy/copytool.cpp b/src/tools/copy/copytool.cpp index 89d1b2ef..1b2eb3c2 100644 --- a/src/tools/copy/copytool.cpp +++ b/src/tools/copy/copytool.cpp @@ -19,35 +19,49 @@ #include "src/utils/screenshotsaver.h" #include -CopyTool::CopyTool(QObject *parent) : AbstractActionTool(parent) { +CopyTool::CopyTool(QObject* parent) + : AbstractActionTool(parent) +{} +bool +CopyTool::closeOnButtonPressed() const +{ + return true; } -bool CopyTool::closeOnButtonPressed() const { - return true; +QIcon +CopyTool::icon(const QColor& background, bool inEditor) const +{ + Q_UNUSED(inEditor); + return QIcon(iconPath(background) + "content-copy.svg"); +} +QString +CopyTool::name() const +{ + return tr("Copy"); } -QIcon CopyTool::icon(const QColor &background, bool inEditor) const { - Q_UNUSED(inEditor); - return QIcon(iconPath(background) + "content-copy.svg"); -} -QString CopyTool::name() const { - return tr("Copy"); +QString +CopyTool::nameID() +{ + return QLatin1String(""); } -QString CopyTool::nameID() { - return QLatin1String(""); +QString +CopyTool::description() const +{ + return tr("Copy the selection into the clipboard"); } -QString CopyTool::description() const { - return tr("Copy the selection into the clipboard"); +CaptureTool* +CopyTool::copy(QObject* parent) +{ + return new CopyTool(parent); } -CaptureTool* CopyTool::copy(QObject *parent) { - return new CopyTool(parent); -} - -void CopyTool::pressed(const CaptureContext &context) { - emit requestAction(REQ_CAPTURE_DONE_OK); - ScreenshotSaver().saveToClipboard(context.selectedScreenshotArea()); +void +CopyTool::pressed(const CaptureContext& context) +{ + emit requestAction(REQ_CAPTURE_DONE_OK); + ScreenshotSaver().saveToClipboard(context.selectedScreenshotArea()); } diff --git a/src/tools/copy/copytool.h b/src/tools/copy/copytool.h index 2d9dc454..42727fdc 100644 --- a/src/tools/copy/copytool.h +++ b/src/tools/copy/copytool.h @@ -19,20 +19,21 @@ #include "src/tools/abstractactiontool.h" -class CopyTool : public AbstractActionTool { - Q_OBJECT +class CopyTool : public AbstractActionTool +{ + Q_OBJECT public: - explicit CopyTool(QObject *parent = nullptr); + explicit CopyTool(QObject* parent = nullptr); - bool closeOnButtonPressed() const; + bool closeOnButtonPressed() const; - QIcon icon(const QColor &background, bool inEditor) const override; - QString name() const override; - static QString nameID(); - QString description() const override; + QIcon icon(const QColor& background, bool inEditor) const override; + QString name() const override; + static QString nameID(); + QString description() const override; - CaptureTool* copy(QObject *parent = nullptr) override; + CaptureTool* copy(QObject* parent = nullptr) override; public slots: - void pressed(const CaptureContext &context) override; + void pressed(const CaptureContext& context) override; }; diff --git a/src/tools/exit/exittool.cpp b/src/tools/exit/exittool.cpp index b36b0ecf..53fb5725 100644 --- a/src/tools/exit/exittool.cpp +++ b/src/tools/exit/exittool.cpp @@ -18,35 +18,49 @@ #include "exittool.h" #include -ExitTool::ExitTool(QObject *parent) : AbstractActionTool(parent) { +ExitTool::ExitTool(QObject* parent) + : AbstractActionTool(parent) +{} +bool +ExitTool::closeOnButtonPressed() const +{ + return true; } -bool ExitTool::closeOnButtonPressed() const { - return true; +QIcon +ExitTool::icon(const QColor& background, bool inEditor) const +{ + Q_UNUSED(inEditor); + return QIcon(iconPath(background) + "close.svg"); +} +QString +ExitTool::name() const +{ + return tr("Exit"); } -QIcon ExitTool::icon(const QColor &background, bool inEditor) const { - Q_UNUSED(inEditor); - return QIcon(iconPath(background) + "close.svg"); -} -QString ExitTool::name() const { - return tr("Exit"); +QString +ExitTool::nameID() +{ + return QLatin1String(""); } -QString ExitTool::nameID() { - return QLatin1String(""); +QString +ExitTool::description() const +{ + return tr("Leave the capture screen"); } -QString ExitTool::description() const { - return tr("Leave the capture screen"); +CaptureTool* +ExitTool::copy(QObject* parent) +{ + return new ExitTool(parent); } -CaptureTool* ExitTool::copy(QObject *parent) { - return new ExitTool(parent); -} - -void ExitTool::pressed(const CaptureContext &context) { - Q_UNUSED(context); - emit requestAction(REQ_CLOSE_GUI); +void +ExitTool::pressed(const CaptureContext& context) +{ + Q_UNUSED(context); + emit requestAction(REQ_CLOSE_GUI); } diff --git a/src/tools/exit/exittool.h b/src/tools/exit/exittool.h index 92fed347..62a1cbbf 100644 --- a/src/tools/exit/exittool.h +++ b/src/tools/exit/exittool.h @@ -19,20 +19,21 @@ #include "src/tools/abstractactiontool.h" -class ExitTool : public AbstractActionTool { - Q_OBJECT +class ExitTool : public AbstractActionTool +{ + Q_OBJECT public: - explicit ExitTool(QObject *parent = nullptr); + explicit ExitTool(QObject* parent = nullptr); - bool closeOnButtonPressed() const; + bool closeOnButtonPressed() const; - QIcon icon(const QColor &background, bool inEditor) const override; - QString name() const override; - static QString nameID(); - QString description() const override; + QIcon icon(const QColor& background, bool inEditor) const override; + QString name() const override; + static QString nameID(); + QString description() const override; - CaptureTool* copy(QObject *parent = nullptr) override; + CaptureTool* copy(QObject* parent = nullptr) override; public slots: - void pressed(const CaptureContext &context) override; + void pressed(const CaptureContext& context) override; }; diff --git a/src/tools/imgur/imguruploader.cpp b/src/tools/imgur/imguruploader.cpp index cd0dfc63..5cc11edb 100644 --- a/src/tools/imgur/imguruploader.cpp +++ b/src/tools/imgur/imguruploader.cpp @@ -16,167 +16,194 @@ // along with Flameshot. If not, see . #include "imguruploader.h" +#include "src/utils/confighandler.h" #include "src/utils/filenamehandler.h" #include "src/utils/systemnotification.h" -#include "src/widgets/loadspinner.h" #include "src/widgets/imagelabel.h" +#include "src/widgets/loadspinner.h" #include "src/widgets/notificationwidget.h" -#include "src/utils/confighandler.h" #include +#include #include #include -#include -#include -#include -#include -#include #include -#include -#include -#include -#include -#include -#include -#include +#include #include #include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include -ImgurUploader::ImgurUploader(const QPixmap &capture, QWidget *parent) : - QWidget(parent), m_pixmap(capture) +ImgurUploader::ImgurUploader(const QPixmap& capture, QWidget* parent) + : QWidget(parent) + , m_pixmap(capture) { - setWindowTitle(tr("Upload to Imgur")); - setWindowIcon(QIcon(":img/app/flameshot.svg")); + setWindowTitle(tr("Upload to Imgur")); + setWindowIcon(QIcon(":img/app/flameshot.svg")); - m_spinner = new LoadSpinner(this); - m_spinner->setColor(ConfigHandler().uiMainColorValue()); - m_spinner->start(); + m_spinner = new LoadSpinner(this); + m_spinner->setColor(ConfigHandler().uiMainColorValue()); + m_spinner->start(); - m_infoLabel = new QLabel(tr("Uploading Image")); + m_infoLabel = new QLabel(tr("Uploading Image")); - m_vLayout = new QVBoxLayout(); - setLayout(m_vLayout); - m_vLayout->addWidget(m_spinner, 0, Qt::AlignHCenter); - m_vLayout->addWidget(m_infoLabel); + m_vLayout = new QVBoxLayout(); + setLayout(m_vLayout); + m_vLayout->addWidget(m_spinner, 0, Qt::AlignHCenter); + m_vLayout->addWidget(m_infoLabel); - m_NetworkAM = new QNetworkAccessManager(this); - connect(m_NetworkAM, &QNetworkAccessManager::finished, this, - &ImgurUploader::handleReply); + m_NetworkAM = new QNetworkAccessManager(this); + connect(m_NetworkAM, + &QNetworkAccessManager::finished, + this, + &ImgurUploader::handleReply); - setAttribute(Qt::WA_DeleteOnClose); + setAttribute(Qt::WA_DeleteOnClose); - upload(); - // QTimer::singleShot(2000, this, &ImgurUploader::onUploadOk); // testing + upload(); + // QTimer::singleShot(2000, this, &ImgurUploader::onUploadOk); // testing } -void ImgurUploader::handleReply(QNetworkReply *reply) { - m_spinner->deleteLater(); - if (reply->error() == QNetworkReply::NoError) { - QJsonDocument response = QJsonDocument::fromJson(reply->readAll()); - QJsonObject json = response.object(); - QJsonObject data = json[QStringLiteral("data")].toObject(); - m_imageURL.setUrl(data[QStringLiteral("link")].toString()); - m_deleteImageURL.setUrl(QStringLiteral("https://imgur.com/delete/%1").arg( - data[QStringLiteral("deletehash")].toString())); - if (ConfigHandler().copyAndCloseAfterUploadEnabled()) { - QApplication::clipboard()->setText(m_imageURL.toString()); - SystemNotification().sendMessage(QObject::tr("URL copied to clipboard.")); - close(); - } else { - onUploadOk(); - } +void +ImgurUploader::handleReply(QNetworkReply* reply) +{ + m_spinner->deleteLater(); + if (reply->error() == QNetworkReply::NoError) { + QJsonDocument response = QJsonDocument::fromJson(reply->readAll()); + QJsonObject json = response.object(); + QJsonObject data = json[QStringLiteral("data")].toObject(); + m_imageURL.setUrl(data[QStringLiteral("link")].toString()); + m_deleteImageURL.setUrl( + QStringLiteral("https://imgur.com/delete/%1") + .arg(data[QStringLiteral("deletehash")].toString())); + if (ConfigHandler().copyAndCloseAfterUploadEnabled()) { + QApplication::clipboard()->setText(m_imageURL.toString()); + SystemNotification().sendMessage(QObject::tr("URL copied to clipboard.")); + close(); } else { - m_infoLabel->setText(reply->errorString()); + onUploadOk(); } - new QShortcut(Qt::Key_Escape, this, SLOT(close())); + } else { + m_infoLabel->setText(reply->errorString()); + } + new QShortcut(Qt::Key_Escape, this, SLOT(close())); } -void ImgurUploader::startDrag() { - QMimeData *mimeData = new QMimeData; - mimeData->setUrls(QList { m_imageURL }); - mimeData->setImageData(m_pixmap); - - QDrag *dragHandler = new QDrag(this); - dragHandler->setMimeData(mimeData); - dragHandler->setPixmap(m_pixmap.scaled(256, 256, Qt::KeepAspectRatioByExpanding, - Qt::SmoothTransformation)); - dragHandler->exec(); -} - -void ImgurUploader::upload() { - QByteArray byteArray; - QBuffer buffer(&byteArray); - m_pixmap.save(&buffer, "PNG"); - - QUrlQuery urlQuery; - urlQuery.addQueryItem(QStringLiteral("title"), QStringLiteral("flameshot_screenshot")); - QString description = FileNameHandler().parsedPattern(); - urlQuery.addQueryItem(QStringLiteral("description"), description); - - QUrl url(QStringLiteral("https://api.imgur.com/3/image")); - url.setQuery(urlQuery); - QNetworkRequest request(url); - request.setHeader(QNetworkRequest::ContentTypeHeader, - "application/application/x-www-form-urlencoded"); - request.setRawHeader("Authorization", QStringLiteral("Client-ID %1").arg(IMGUR_CLIENT_ID).toUtf8()); - - m_NetworkAM->post(request, byteArray); -} - -void ImgurUploader::onUploadOk() { - m_infoLabel->deleteLater(); - - m_notification = new NotificationWidget(); - m_vLayout->addWidget(m_notification); - - ImageLabel *imageLabel = new ImageLabel(); - imageLabel->setScreenshot(m_pixmap); - imageLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); - connect(imageLabel, &ImageLabel::dragInitiated, this, &ImgurUploader::startDrag); - m_vLayout->addWidget(imageLabel); - - m_hLayout = new QHBoxLayout(); - m_vLayout->addLayout(m_hLayout); - - m_copyUrlButton = new QPushButton(tr("Copy URL")); - m_openUrlButton = new QPushButton(tr("Open URL")); - m_openDeleteUrlButton = new QPushButton(tr("Delete image")); - m_toClipboardButton = new QPushButton(tr("Image to Clipboard.")); - m_hLayout->addWidget(m_copyUrlButton); - m_hLayout->addWidget(m_openUrlButton); - m_hLayout->addWidget(m_openDeleteUrlButton); - m_hLayout->addWidget(m_toClipboardButton); - - connect(m_copyUrlButton, &QPushButton::clicked, - this, &ImgurUploader::copyURL); - connect(m_openUrlButton, &QPushButton::clicked, - this, &ImgurUploader::openURL); - connect(m_openDeleteUrlButton, &QPushButton::clicked, - this, &ImgurUploader::openDeleteURL); - connect(m_toClipboardButton, &QPushButton::clicked, - this, &ImgurUploader::copyImage); -} - -void ImgurUploader::openURL() { - bool successful = QDesktopServices::openUrl(m_imageURL); - if (!successful) { - m_notification->showMessage(tr("Unable to open the URL.")); - } -} - -void ImgurUploader::copyURL() { - QApplication::clipboard()->setText(m_imageURL.toString()); - m_notification->showMessage(tr("URL copied to clipboard.")); -} - -void ImgurUploader::openDeleteURL() +void +ImgurUploader::startDrag() { - bool successful = QDesktopServices::openUrl(m_deleteImageURL); - if (!successful) { - m_notification->showMessage(tr("Unable to open the URL.")); - } + QMimeData* mimeData = new QMimeData; + mimeData->setUrls(QList{ m_imageURL }); + mimeData->setImageData(m_pixmap); + + QDrag* dragHandler = new QDrag(this); + dragHandler->setMimeData(mimeData); + dragHandler->setPixmap(m_pixmap.scaled( + 256, 256, Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation)); + dragHandler->exec(); } -void ImgurUploader::copyImage() { - QApplication::clipboard()->setPixmap(m_pixmap); - m_notification->showMessage(tr("Screenshot copied to clipboard.")); +void +ImgurUploader::upload() +{ + QByteArray byteArray; + QBuffer buffer(&byteArray); + m_pixmap.save(&buffer, "PNG"); + + QUrlQuery urlQuery; + urlQuery.addQueryItem(QStringLiteral("title"), + QStringLiteral("flameshot_screenshot")); + QString description = FileNameHandler().parsedPattern(); + urlQuery.addQueryItem(QStringLiteral("description"), description); + + QUrl url(QStringLiteral("https://api.imgur.com/3/image")); + url.setQuery(urlQuery); + QNetworkRequest request(url); + request.setHeader(QNetworkRequest::ContentTypeHeader, + "application/application/x-www-form-urlencoded"); + request.setRawHeader( + "Authorization", + QStringLiteral("Client-ID %1").arg(IMGUR_CLIENT_ID).toUtf8()); + + m_NetworkAM->post(request, byteArray); +} + +void +ImgurUploader::onUploadOk() +{ + m_infoLabel->deleteLater(); + + m_notification = new NotificationWidget(); + m_vLayout->addWidget(m_notification); + + ImageLabel* imageLabel = new ImageLabel(); + imageLabel->setScreenshot(m_pixmap); + imageLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); + connect( + imageLabel, &ImageLabel::dragInitiated, this, &ImgurUploader::startDrag); + m_vLayout->addWidget(imageLabel); + + m_hLayout = new QHBoxLayout(); + m_vLayout->addLayout(m_hLayout); + + m_copyUrlButton = new QPushButton(tr("Copy URL")); + m_openUrlButton = new QPushButton(tr("Open URL")); + m_openDeleteUrlButton = new QPushButton(tr("Delete image")); + m_toClipboardButton = new QPushButton(tr("Image to Clipboard.")); + m_hLayout->addWidget(m_copyUrlButton); + m_hLayout->addWidget(m_openUrlButton); + m_hLayout->addWidget(m_openDeleteUrlButton); + m_hLayout->addWidget(m_toClipboardButton); + + connect( + m_copyUrlButton, &QPushButton::clicked, this, &ImgurUploader::copyURL); + connect( + m_openUrlButton, &QPushButton::clicked, this, &ImgurUploader::openURL); + connect(m_openDeleteUrlButton, + &QPushButton::clicked, + this, + &ImgurUploader::openDeleteURL); + connect(m_toClipboardButton, + &QPushButton::clicked, + this, + &ImgurUploader::copyImage); +} + +void +ImgurUploader::openURL() +{ + bool successful = QDesktopServices::openUrl(m_imageURL); + if (!successful) { + m_notification->showMessage(tr("Unable to open the URL.")); + } +} + +void +ImgurUploader::copyURL() +{ + QApplication::clipboard()->setText(m_imageURL.toString()); + m_notification->showMessage(tr("URL copied to clipboard.")); +} + +void +ImgurUploader::openDeleteURL() +{ + bool successful = QDesktopServices::openUrl(m_deleteImageURL); + if (!successful) { + m_notification->showMessage(tr("Unable to open the URL.")); + } +} + +void +ImgurUploader::copyImage() +{ + QApplication::clipboard()->setPixmap(m_pixmap); + m_notification->showMessage(tr("Screenshot copied to clipboard.")); } diff --git a/src/tools/imgur/imguruploader.h b/src/tools/imgur/imguruploader.h index 94458655..082767d1 100644 --- a/src/tools/imgur/imguruploader.h +++ b/src/tools/imgur/imguruploader.h @@ -17,8 +17,8 @@ #pragma once -#include #include +#include class QNetworkReply; class QNetworkAccessManager; @@ -30,38 +30,39 @@ class QPushButton; class QUrl; class NotificationWidget; -class ImgurUploader : public QWidget { - Q_OBJECT +class ImgurUploader : public QWidget +{ + Q_OBJECT public: - explicit ImgurUploader(const QPixmap &capture, QWidget *parent = nullptr); + explicit ImgurUploader(const QPixmap& capture, QWidget* parent = nullptr); private slots: - void handleReply(QNetworkReply *reply); - void startDrag(); + void handleReply(QNetworkReply* reply); + void startDrag(); - void openURL(); - void copyURL(); - void openDeleteURL(); - void copyImage(); + void openURL(); + void copyURL(); + void openDeleteURL(); + void copyImage(); private: - QPixmap m_pixmap; - QNetworkAccessManager *m_NetworkAM; + QPixmap m_pixmap; + QNetworkAccessManager* m_NetworkAM; - QVBoxLayout *m_vLayout; - QHBoxLayout *m_hLayout; - // loading - QLabel *m_infoLabel; - LoadSpinner *m_spinner; - // uploaded - QPushButton *m_openUrlButton; - QPushButton *m_openDeleteUrlButton; - QPushButton *m_copyUrlButton; - QPushButton *m_toClipboardButton; - QUrl m_imageURL; - QUrl m_deleteImageURL; - NotificationWidget *m_notification; + QVBoxLayout* m_vLayout; + QHBoxLayout* m_hLayout; + // loading + QLabel* m_infoLabel; + LoadSpinner* m_spinner; + // uploaded + QPushButton* m_openUrlButton; + QPushButton* m_openDeleteUrlButton; + QPushButton* m_copyUrlButton; + QPushButton* m_toClipboardButton; + QUrl m_imageURL; + QUrl m_deleteImageURL; + NotificationWidget* m_notification; - void upload(); - void onUploadOk(); + void upload(); + void onUploadOk(); }; diff --git a/src/tools/imgur/imguruploadertool.cpp b/src/tools/imgur/imguruploadertool.cpp index ea68303c..7d5185dc 100644 --- a/src/tools/imgur/imguruploadertool.cpp +++ b/src/tools/imgur/imguruploadertool.cpp @@ -19,40 +19,56 @@ #include "imguruploader.h" #include -ImgurUploaderTool::ImgurUploaderTool(QObject *parent) : AbstractActionTool(parent) { +ImgurUploaderTool::ImgurUploaderTool(QObject* parent) + : AbstractActionTool(parent) +{} +bool +ImgurUploaderTool::closeOnButtonPressed() const +{ + return true; } -bool ImgurUploaderTool::closeOnButtonPressed() const { - return true; +QIcon +ImgurUploaderTool::icon(const QColor& background, bool inEditor) const +{ + Q_UNUSED(inEditor); + return QIcon(iconPath(background) + "cloud-upload.svg"); +} +QString +ImgurUploaderTool::name() const +{ + return tr("Image Uploader"); } -QIcon ImgurUploaderTool::icon(const QColor &background, bool inEditor) const { - Q_UNUSED(inEditor); - return QIcon(iconPath(background) + "cloud-upload.svg"); -} -QString ImgurUploaderTool::name() const { - return tr("Image Uploader"); +QString +ImgurUploaderTool::nameID() +{ + return QLatin1String(""); } -QString ImgurUploaderTool::nameID() { - return QLatin1String(""); +QString +ImgurUploaderTool::description() const +{ + return tr("Upload the selection to Imgur"); } -QString ImgurUploaderTool::description() const { - return tr("Upload the selection to Imgur"); +QWidget* +ImgurUploaderTool::widget() +{ + return new ImgurUploader(capture); } -QWidget* ImgurUploaderTool::widget() { - return new ImgurUploader(capture); +CaptureTool* +ImgurUploaderTool::copy(QObject* parent) +{ + return new ImgurUploaderTool(parent); } -CaptureTool* ImgurUploaderTool::copy(QObject *parent) { - return new ImgurUploaderTool(parent); -} - -void ImgurUploaderTool::pressed(const CaptureContext &context) { - capture = context.selectedScreenshotArea(); - emit requestAction(REQ_CAPTURE_DONE_OK); - emit requestAction(REQ_ADD_EXTERNAL_WIDGETS); +void +ImgurUploaderTool::pressed(const CaptureContext& context) +{ + capture = context.selectedScreenshotArea(); + emit requestAction(REQ_CAPTURE_DONE_OK); + emit requestAction(REQ_ADD_EXTERNAL_WIDGETS); } diff --git a/src/tools/imgur/imguruploadertool.h b/src/tools/imgur/imguruploadertool.h index e0e49617..4a27b61a 100644 --- a/src/tools/imgur/imguruploadertool.h +++ b/src/tools/imgur/imguruploadertool.h @@ -19,25 +19,26 @@ #include "src/tools/abstractactiontool.h" -class ImgurUploaderTool : public AbstractActionTool { - Q_OBJECT +class ImgurUploaderTool : public AbstractActionTool +{ + Q_OBJECT public: - explicit ImgurUploaderTool(QObject *parent = nullptr); + explicit ImgurUploaderTool(QObject* parent = nullptr); - bool closeOnButtonPressed() const; + bool closeOnButtonPressed() const; - QIcon icon(const QColor &background, bool inEditor) const override; - QString name() const override; - static QString nameID(); - QString description() const override; + QIcon icon(const QColor& background, bool inEditor) const override; + QString name() const override; + static QString nameID(); + QString description() const override; - QWidget* widget() override; + QWidget* widget() override; - CaptureTool* copy(QObject *parent = nullptr) override; + CaptureTool* copy(QObject* parent = nullptr) override; public slots: - void pressed(const CaptureContext &context) override; + void pressed(const CaptureContext& context) override; private: - QPixmap capture; + QPixmap capture; }; diff --git a/src/tools/launcher/applaunchertool.cpp b/src/tools/launcher/applaunchertool.cpp index 4070c4b6..cff4a04f 100644 --- a/src/tools/launcher/applaunchertool.cpp +++ b/src/tools/launcher/applaunchertool.cpp @@ -18,40 +18,56 @@ #include "applaunchertool.h" #include "applauncherwidget.h" -AppLauncher::AppLauncher(QObject *parent) : AbstractActionTool(parent) { +AppLauncher::AppLauncher(QObject* parent) + : AbstractActionTool(parent) +{} +bool +AppLauncher::closeOnButtonPressed() const +{ + return true; } -bool AppLauncher::closeOnButtonPressed() const { - return true; +QIcon +AppLauncher::icon(const QColor& background, bool inEditor) const +{ + Q_UNUSED(inEditor); + return QIcon(iconPath(background) + "open_with.svg"); +} +QString +AppLauncher::name() const +{ + return tr("App Launcher"); } -QIcon AppLauncher::icon(const QColor &background, bool inEditor) const { - Q_UNUSED(inEditor); - return QIcon(iconPath(background) + "open_with.svg"); -} -QString AppLauncher::name() const { - return tr("App Launcher"); +QString +AppLauncher::nameID() +{ + return QLatin1String(""); } -QString AppLauncher::nameID() { - return QLatin1String(""); +QString +AppLauncher::description() const +{ + return tr("Choose an app to open the capture"); } -QString AppLauncher::description() const { - return tr("Choose an app to open the capture"); +QWidget* +AppLauncher::widget() +{ + return new AppLauncherWidget(capture); } -QWidget* AppLauncher::widget() { - return new AppLauncherWidget(capture); +CaptureTool* +AppLauncher::copy(QObject* parent) +{ + return new AppLauncher(parent); } -CaptureTool* AppLauncher::copy(QObject *parent) { - return new AppLauncher(parent); -} - -void AppLauncher::pressed(const CaptureContext &context) { - capture = context.selectedScreenshotArea(); - emit requestAction(REQ_CAPTURE_DONE_OK); - emit requestAction(REQ_ADD_EXTERNAL_WIDGETS); +void +AppLauncher::pressed(const CaptureContext& context) +{ + capture = context.selectedScreenshotArea(); + emit requestAction(REQ_CAPTURE_DONE_OK); + emit requestAction(REQ_ADD_EXTERNAL_WIDGETS); } diff --git a/src/tools/launcher/applaunchertool.h b/src/tools/launcher/applaunchertool.h index 3adc425a..1527b95a 100644 --- a/src/tools/launcher/applaunchertool.h +++ b/src/tools/launcher/applaunchertool.h @@ -19,25 +19,26 @@ #include "src/tools/abstractactiontool.h" -class AppLauncher : public AbstractActionTool { - Q_OBJECT +class AppLauncher : public AbstractActionTool +{ + Q_OBJECT public: - explicit AppLauncher(QObject *parent = nullptr); + explicit AppLauncher(QObject* parent = nullptr); - bool closeOnButtonPressed() const; + bool closeOnButtonPressed() const; - QIcon icon(const QColor &background, bool inEditor) const override; - QString name() const override; - static QString nameID(); - QString description() const override; + QIcon icon(const QColor& background, bool inEditor) const override; + QString name() const override; + static QString nameID(); + QString description() const override; - QWidget* widget() override; + QWidget* widget() override; - CaptureTool* copy(QObject *parent = nullptr) override; + CaptureTool* copy(QObject* parent = nullptr) override; public slots: - void pressed(const CaptureContext &context) override; + void pressed(const CaptureContext& context) override; private: - QPixmap capture; + QPixmap capture; }; diff --git a/src/tools/launcher/applauncherwidget.cpp b/src/tools/launcher/applauncherwidget.cpp index a44e4c57..cdbd93a7 100644 --- a/src/tools/launcher/applauncherwidget.cpp +++ b/src/tools/launcher/applauncherwidget.cpp @@ -16,233 +16,253 @@ // along with Flameshot. If not, see . #include "applauncherwidget.h" -#include "src/utils/filenamehandler.h" #include "src/tools/launcher/launcheritemdelegate.h" -#include "src/utils/globalvalues.h" #include "src/utils/confighandler.h" +#include "src/utils/filenamehandler.h" +#include "src/utils/globalvalues.h" #include "terminallauncher.h" -#include -#include -#include -#include -#include -#include -#include -#include #include +#include +#include #include +#include +#include +#include #include +#include +#include +#include namespace { -QMap catIconNames({ - { "Multimedia", "applications-multimedia" }, - { "Development","applications-development" }, - { "Graphics", "applications-graphics" }, - { "Network", "preferences-system-network" }, - { "Office", "applications-office" }, - { "Science", "applications-science" }, - { "Settings", "preferences-desktop" }, - { "System", "preferences-system" }, - { "Utility", "applications-utilities" } - }); +QMap catIconNames( + { { "Multimedia", "applications-multimedia" }, + { "Development", "applications-development" }, + { "Graphics", "applications-graphics" }, + { "Network", "preferences-system-network" }, + { "Office", "applications-office" }, + { "Science", "applications-science" }, + { "Settings", "preferences-desktop" }, + { "System", "preferences-system" }, + { "Utility", "applications-utilities" } }); } -AppLauncherWidget::AppLauncherWidget(const QPixmap &p, QWidget *parent): - QWidget(parent), m_pixmap(p) +AppLauncherWidget::AppLauncherWidget(const QPixmap& p, QWidget* parent) + : QWidget(parent) + , m_pixmap(p) { - setAttribute(Qt::WA_DeleteOnClose); - setWindowIcon(QIcon(":img/app/flameshot.svg")); - setWindowTitle(tr("Open With")); + setAttribute(Qt::WA_DeleteOnClose); + setWindowIcon(QIcon(":img/app/flameshot.svg")); + setWindowTitle(tr("Open With")); - m_keepOpen = ConfigHandler().keepOpenAppLauncherValue(); + m_keepOpen = ConfigHandler().keepOpenAppLauncherValue(); - QString dirLocal = QDir::homePath() + "/.local/share/applications/"; - QDir appsDirLocal(dirLocal); - m_parser.processDirectory(appsDirLocal); + QString dirLocal = QDir::homePath() + "/.local/share/applications/"; + QDir appsDirLocal(dirLocal); + m_parser.processDirectory(appsDirLocal); - QString dir = QStringLiteral("/usr/share/applications/"); - QDir appsDir(dir); - m_parser.processDirectory(appsDir); + QString dir = QStringLiteral("/usr/share/applications/"); + QDir appsDir(dir); + m_parser.processDirectory(appsDir); - initAppMap(); - initListWidget(); + initAppMap(); + initListWidget(); - m_terminalCheckbox = new QCheckBox(tr("Launch in terminal"), this); - m_keepOpenCheckbox = new QCheckBox(tr("Keep open after selection"), this); - m_keepOpenCheckbox->setChecked(ConfigHandler().keepOpenAppLauncherValue()); - connect(m_keepOpenCheckbox, &QCheckBox::clicked, this, &AppLauncherWidget::checkboxClicked); + m_terminalCheckbox = new QCheckBox(tr("Launch in terminal"), this); + m_keepOpenCheckbox = new QCheckBox(tr("Keep open after selection"), this); + m_keepOpenCheckbox->setChecked(ConfigHandler().keepOpenAppLauncherValue()); + connect(m_keepOpenCheckbox, + &QCheckBox::clicked, + this, + &AppLauncherWidget::checkboxClicked); - // search items - m_lineEdit = new QLineEdit; - connect(m_lineEdit, &QLineEdit::textChanged, - this, &AppLauncherWidget::searchChanged); - m_filterList = new QListWidget; + // search items + m_lineEdit = new QLineEdit; + connect(m_lineEdit, + &QLineEdit::textChanged, + this, + &AppLauncherWidget::searchChanged); + m_filterList = new QListWidget; + m_filterList->hide(); + configureListView(m_filterList); + connect( + m_filterList, &QListWidget::clicked, this, &AppLauncherWidget::launch); + + m_layout = new QVBoxLayout(this); + m_layout->addWidget(m_filterList); + m_layout->addWidget(m_tabWidget); + m_layout->addWidget(m_lineEdit); + m_layout->addWidget(m_keepOpenCheckbox); + m_layout->addWidget(m_terminalCheckbox); + m_lineEdit->setFocus(); +} + +void +AppLauncherWidget::launch(const QModelIndex& index) +{ + if (!QFileInfo(m_tempFile).isReadable()) { + m_tempFile = + FileNameHandler().generateAbsolutePath(QDir::tempPath()) + ".png"; + bool ok = m_pixmap.save(m_tempFile); + if (!ok) { + QMessageBox::about( + this, tr("Error"), tr("Unable to write in") + QDir::tempPath()); + return; + } + } + QString command = index.data(Qt::UserRole) + .toString() + .replace(QRegExp("(\\%.)"), '"' + m_tempFile + '"'); + + QString app_name = index.data(Qt::UserRole).toString().split(" ").at(0); + bool inTerminal = + index.data(Qt::UserRole + 1).toBool() || m_terminalCheckbox->isChecked(); + if (inTerminal) { + bool ok = TerminalLauncher::launchDetached(command); + if (!ok) { + QMessageBox::about( + this, tr("Error"), tr("Unable to launch in terminal.")); + } + } else { + QProcess::startDetached(app_name, { m_tempFile }); + } + if (!m_keepOpen) { + close(); + } +} + +void +AppLauncherWidget::checkboxClicked(const bool enabled) +{ + m_keepOpen = enabled; + ConfigHandler().setKeepOpenAppLauncher(enabled); + m_keepOpenCheckbox->setChecked(enabled); +} + +void +AppLauncherWidget::searchChanged(const QString& text) +{ + if (text.isEmpty()) { m_filterList->hide(); - configureListView(m_filterList); - connect(m_filterList, &QListWidget::clicked, this, &AppLauncherWidget::launch); - - m_layout = new QVBoxLayout(this); - m_layout->addWidget(m_filterList); - m_layout->addWidget(m_tabWidget); - m_layout->addWidget(m_lineEdit); - m_layout->addWidget(m_keepOpenCheckbox); - m_layout->addWidget(m_terminalCheckbox); - m_lineEdit->setFocus(); -} - -void AppLauncherWidget::launch(const QModelIndex &index) { - if (!QFileInfo(m_tempFile).isReadable()) { - m_tempFile = FileNameHandler().generateAbsolutePath(QDir::tempPath()) + ".png"; - bool ok = m_pixmap.save(m_tempFile); - if (!ok) { - QMessageBox::about(this, tr("Error"), tr("Unable to write in") - + QDir::tempPath()); - return; - } - } - QString command = index.data(Qt::UserRole).toString().replace( - QRegExp("(\\%.)"), '"' + m_tempFile + '"'); - - QString app_name = index.data(Qt::UserRole).toString().split(" ").at(0); - bool inTerminal = index.data(Qt::UserRole+1).toBool() || - m_terminalCheckbox->isChecked(); - if (inTerminal) { - bool ok = TerminalLauncher::launchDetached(command); - if (!ok) { - QMessageBox::about(this, tr("Error"), - tr("Unable to launch in terminal.")); - } - } else { - QProcess::startDetached(app_name,{m_tempFile}); - } - if (!m_keepOpen) { - close(); - } -} - -void AppLauncherWidget::checkboxClicked(const bool enabled) { - m_keepOpen = enabled; - ConfigHandler().setKeepOpenAppLauncher(enabled); - m_keepOpenCheckbox->setChecked(enabled); -} - -void AppLauncherWidget::searchChanged(const QString &text) { - if (text.isEmpty()) { - m_filterList->hide(); - m_tabWidget->show(); - } else { - m_tabWidget->hide(); - m_filterList->show(); - m_filterList->clear(); - QRegExp regexp(text, Qt::CaseInsensitive, QRegExp::Wildcard); - QVector apps; - - for (auto const& i : catIconNames.toStdMap()) { - const QString &cat = i.first; - if (!m_appsMap.contains(cat)) { - continue; - } - const QVector &appList = m_appsMap[cat]; - for (const DesktopAppData &app: appList) { - if (!apps.contains(app) && (app.name.contains(regexp) || - app.description.contains(regexp) )) - { - apps.append(app); - } - } - } - addAppsToListWidget(m_filterList, apps); - } -} - -void AppLauncherWidget::initListWidget() { - m_tabWidget = new QTabWidget; - const int size = GlobalValues::buttonBaseSize(); - m_tabWidget->setIconSize(QSize(size, size)); + m_tabWidget->show(); + } else { + m_tabWidget->hide(); + m_filterList->show(); + m_filterList->clear(); + QRegExp regexp(text, Qt::CaseInsensitive, QRegExp::Wildcard); + QVector apps; for (auto const& i : catIconNames.toStdMap()) { - const QString &cat = i.first; - const QString &iconName = i.second; - - if (!m_appsMap.contains(cat)) { - continue; - } - - QListWidget *itemsWidget = new QListWidget(); - configureListView(itemsWidget); - - const QVector &appList = m_appsMap[cat]; - addAppsToListWidget(itemsWidget, appList); - - m_tabWidget->addTab(itemsWidget, QIcon::fromTheme(iconName), QLatin1String("")); - m_tabWidget->setTabToolTip(m_tabWidget->count(), cat); - if (cat == QLatin1String("Graphics")) { - m_tabWidget->setCurrentIndex(m_tabWidget->count() -1); + const QString& cat = i.first; + if (!m_appsMap.contains(cat)) { + continue; + } + const QVector& appList = m_appsMap[cat]; + for (const DesktopAppData& app : appList) { + if (!apps.contains(app) && + (app.name.contains(regexp) || app.description.contains(regexp))) { + apps.append(app); } + } } + addAppsToListWidget(m_filterList, apps); + } } -void AppLauncherWidget::initAppMap() { - QStringList categories({"AudioVideo", - "Audio", - "Video", - "Development", - "Graphics", - "Network", - "Office", - "Science", - "Settings", - "System", - "Utility"}); - - m_appsMap = m_parser.getAppsByCategory(categories); - - // Unify multimedia. - QVector multimediaList; - QStringList multimediaNames; - multimediaNames << QStringLiteral("AudioVideo") << QStringLiteral("Audio") << QStringLiteral("Video"); - for (const QString &name : multimediaNames) { - if(!m_appsMap.contains(name)) { - continue; - } - for (auto i : m_appsMap[name]) { - if (!multimediaList.contains(i)) { - multimediaList.append(i); - } - } - m_appsMap.remove(name); - } - m_appsMap.insert(QStringLiteral("Multimedia"), multimediaList); -} - -void AppLauncherWidget::configureListView(QListWidget *widget) { - widget->setItemDelegate(new LauncherItemDelegate()); - widget->setViewMode(QListWidget::IconMode); - widget->setResizeMode(QListView::Adjust); - widget->setSpacing(4); - widget->setFlow(QListView::LeftToRight); - widget->setDragEnabled(false); - widget->setMinimumWidth(GlobalValues::buttonBaseSize() * 11); - connect(widget, &QListWidget::clicked, - this, &AppLauncherWidget::launch); -} - -void AppLauncherWidget::addAppsToListWidget( - QListWidget *widget, const QVector &appList) +void +AppLauncherWidget::initListWidget() { - for (const DesktopAppData &app: appList) { - QListWidgetItem *buttonItem = new QListWidgetItem(widget); - buttonItem->setData(Qt::DecorationRole, app.icon); - buttonItem->setData(Qt::DisplayRole, app.name); - buttonItem->setData(Qt::UserRole, app.exec); - buttonItem->setData(Qt::UserRole+1, app.showInTerminal); - QColor foregroundColor = - this->palette().color(QWidget::foregroundRole()); - buttonItem->setForeground(foregroundColor); + m_tabWidget = new QTabWidget; + const int size = GlobalValues::buttonBaseSize(); + m_tabWidget->setIconSize(QSize(size, size)); - buttonItem->setIcon(app.icon); - buttonItem->setText(app.name); - buttonItem->setToolTip(app.description); + for (auto const& i : catIconNames.toStdMap()) { + const QString& cat = i.first; + const QString& iconName = i.second; + + if (!m_appsMap.contains(cat)) { + continue; } + + QListWidget* itemsWidget = new QListWidget(); + configureListView(itemsWidget); + + const QVector& appList = m_appsMap[cat]; + addAppsToListWidget(itemsWidget, appList); + + m_tabWidget->addTab( + itemsWidget, QIcon::fromTheme(iconName), QLatin1String("")); + m_tabWidget->setTabToolTip(m_tabWidget->count(), cat); + if (cat == QLatin1String("Graphics")) { + m_tabWidget->setCurrentIndex(m_tabWidget->count() - 1); + } + } +} + +void +AppLauncherWidget::initAppMap() +{ + QStringList categories({ "AudioVideo", + "Audio", + "Video", + "Development", + "Graphics", + "Network", + "Office", + "Science", + "Settings", + "System", + "Utility" }); + + m_appsMap = m_parser.getAppsByCategory(categories); + + // Unify multimedia. + QVector multimediaList; + QStringList multimediaNames; + multimediaNames << QStringLiteral("AudioVideo") << QStringLiteral("Audio") + << QStringLiteral("Video"); + for (const QString& name : multimediaNames) { + if (!m_appsMap.contains(name)) { + continue; + } + for (auto i : m_appsMap[name]) { + if (!multimediaList.contains(i)) { + multimediaList.append(i); + } + } + m_appsMap.remove(name); + } + m_appsMap.insert(QStringLiteral("Multimedia"), multimediaList); +} + +void +AppLauncherWidget::configureListView(QListWidget* widget) +{ + widget->setItemDelegate(new LauncherItemDelegate()); + widget->setViewMode(QListWidget::IconMode); + widget->setResizeMode(QListView::Adjust); + widget->setSpacing(4); + widget->setFlow(QListView::LeftToRight); + widget->setDragEnabled(false); + widget->setMinimumWidth(GlobalValues::buttonBaseSize() * 11); + connect(widget, &QListWidget::clicked, this, &AppLauncherWidget::launch); +} + +void +AppLauncherWidget::addAppsToListWidget(QListWidget* widget, + const QVector& appList) +{ + for (const DesktopAppData& app : appList) { + QListWidgetItem* buttonItem = new QListWidgetItem(widget); + buttonItem->setData(Qt::DecorationRole, app.icon); + buttonItem->setData(Qt::DisplayRole, app.name); + buttonItem->setData(Qt::UserRole, app.exec); + buttonItem->setData(Qt::UserRole + 1, app.showInTerminal); + QColor foregroundColor = this->palette().color(QWidget::foregroundRole()); + buttonItem->setForeground(foregroundColor); + + buttonItem->setIcon(app.icon); + buttonItem->setText(app.name); + buttonItem->setToolTip(app.description); + } } diff --git a/src/tools/launcher/applauncherwidget.h b/src/tools/launcher/applauncherwidget.h index e6bd15dd..5724edd8 100644 --- a/src/tools/launcher/applauncherwidget.h +++ b/src/tools/launcher/applauncherwidget.h @@ -18,8 +18,8 @@ #pragma once #include "src/utils/desktopfileparse.h" -#include #include +#include class QTabWidget; class QCheckBox; @@ -27,32 +27,33 @@ class QVBoxLayout; class QLineEdit; class QListWidget; -class AppLauncherWidget: public QWidget { - Q_OBJECT +class AppLauncherWidget : public QWidget +{ + Q_OBJECT public: - explicit AppLauncherWidget(const QPixmap &p, QWidget *parent = nullptr); + explicit AppLauncherWidget(const QPixmap& p, QWidget* parent = nullptr); private slots: - void launch(const QModelIndex &index); - void checkboxClicked(const bool enabled); - void searchChanged(const QString &text); + void launch(const QModelIndex& index); + void checkboxClicked(const bool enabled); + void searchChanged(const QString& text); private: - void initListWidget(); - void initAppMap(); - void configureListView(QListWidget *widget); - void addAppsToListWidget(QListWidget *widget, - const QVector &appList); + void initListWidget(); + void initAppMap(); + void configureListView(QListWidget* widget); + void addAppsToListWidget(QListWidget* widget, + const QVector& appList); - DesktopFileParser m_parser; - QPixmap m_pixmap; - QString m_tempFile; - bool m_keepOpen; - QMap> m_appsMap; - QCheckBox *m_keepOpenCheckbox; - QCheckBox *m_terminalCheckbox; - QVBoxLayout *m_layout; - QLineEdit *m_lineEdit; - QListWidget *m_filterList; - QTabWidget *m_tabWidget; + DesktopFileParser m_parser; + QPixmap m_pixmap; + QString m_tempFile; + bool m_keepOpen; + QMap> m_appsMap; + QCheckBox* m_keepOpenCheckbox; + QCheckBox* m_terminalCheckbox; + QVBoxLayout* m_layout; + QLineEdit* m_lineEdit; + QListWidget* m_filterList; + QTabWidget* m_tabWidget; }; diff --git a/src/tools/launcher/launcheritemdelegate.cpp b/src/tools/launcher/launcheritemdelegate.cpp index 8c3a2e5b..c7fd5a38 100644 --- a/src/tools/launcher/launcheritemdelegate.cpp +++ b/src/tools/launcher/launcheritemdelegate.cpp @@ -19,48 +19,49 @@ #include "src/utils/globalvalues.h" #include -LauncherItemDelegate::LauncherItemDelegate(QObject *parent) : - QStyledItemDelegate(parent) +LauncherItemDelegate::LauncherItemDelegate(QObject* parent) + : QStyledItemDelegate(parent) +{} + +void +LauncherItemDelegate::paint(QPainter* painter, + const QStyleOptionViewItem& option, + const QModelIndex& index) const { + const QRect& rect = option.rect; + if (option.state & (QStyle::State_Selected | QStyle::State_MouseOver)) { + painter->save(); + painter->setPen(Qt::transparent); + painter->setBrush(QPalette().highlight()); + painter->drawRect(rect.x(), rect.y(), rect.width() - 1, rect.height() - 1); + painter->restore(); + } + QIcon icon = index.data(Qt::DecorationRole).value(); + + const int iconSide = GlobalValues::buttonBaseSize() * 1.3; + const int halfIcon = iconSide / 2; + const int halfWidth = rect.width() / 2; + const int halfHeight = rect.height() / 2; + QSize size(iconSide, iconSide); + QPixmap pixIcon = icon.pixmap(size).scaled(size, Qt::KeepAspectRatio); + painter->drawPixmap(rect.x() + (halfWidth - halfIcon), + rect.y() + (halfHeight / 2 - halfIcon), + iconSide, + iconSide, + pixIcon); + const QRect textRect( + rect.x(), rect.y() + halfHeight, rect.width(), halfHeight); + painter->drawText(textRect, + Qt::TextWordWrap | Qt::AlignHCenter, + index.data(Qt::DisplayRole).toString()); } -void LauncherItemDelegate::paint( - QPainter *painter, - const QStyleOptionViewItem &option, - const QModelIndex &index) const +QSize +LauncherItemDelegate::sizeHint(const QStyleOptionViewItem& option, + const QModelIndex& index) const { - const QRect &rect = option.rect; - if (option.state & (QStyle::State_Selected | QStyle::State_MouseOver)) { - painter->save(); - painter->setPen(Qt::transparent); - painter->setBrush(QPalette().highlight()); - painter->drawRect(rect.x(), rect.y(), - rect.width() -1, rect.height() -1); - painter->restore(); - } - QIcon icon = index.data(Qt::DecorationRole).value(); - - const int iconSide = GlobalValues::buttonBaseSize() * 1.3; - const int halfIcon = iconSide/2; - const int halfWidth = rect.width()/2; - const int halfHeight = rect.height()/2; - QSize size(iconSide, iconSide); - QPixmap pixIcon = icon.pixmap(size).scaled(size, Qt::KeepAspectRatio); - painter->drawPixmap(rect.x() + (halfWidth - halfIcon), - rect.y()+ (halfHeight/2 - halfIcon), - iconSide, iconSide, pixIcon); - const QRect textRect(rect.x(), rect.y() + halfHeight, - rect.width(), halfHeight); - painter->drawText(textRect, Qt::TextWordWrap | Qt::AlignHCenter, - index.data(Qt::DisplayRole).toString()); -} - -QSize LauncherItemDelegate::sizeHint( - const QStyleOptionViewItem &option, - const QModelIndex &index) const -{ - Q_UNUSED(option); - Q_UNUSED(index); - const int size = GlobalValues::buttonBaseSize(); - return QSize(size * 3.2, size * 3.7); + Q_UNUSED(option); + Q_UNUSED(index); + const int size = GlobalValues::buttonBaseSize(); + return QSize(size * 3.2, size * 3.7); } diff --git a/src/tools/launcher/launcheritemdelegate.h b/src/tools/launcher/launcheritemdelegate.h index 2e662426..3360edc0 100644 --- a/src/tools/launcher/launcheritemdelegate.h +++ b/src/tools/launcher/launcheritemdelegate.h @@ -20,14 +20,16 @@ #include "src/utils/desktopfileparse.h" #include -class LauncherItemDelegate : public QStyledItemDelegate { - Q_OBJECT +class LauncherItemDelegate : public QStyledItemDelegate +{ + Q_OBJECT public: - explicit LauncherItemDelegate(QObject *parent = nullptr); + explicit LauncherItemDelegate(QObject* parent = nullptr); - void paint(QPainter *painter, - const QStyleOptionViewItem &option, - const QModelIndex &index) const; + void paint(QPainter* painter, + const QStyleOptionViewItem& option, + const QModelIndex& index) const; - QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const; + QSize sizeHint(const QStyleOptionViewItem& option, + const QModelIndex& index) const; }; diff --git a/src/tools/launcher/openwithprogram.cpp b/src/tools/launcher/openwithprogram.cpp index e5fb6e20..28cb1a6f 100644 --- a/src/tools/launcher/openwithprogram.cpp +++ b/src/tools/launcher/openwithprogram.cpp @@ -15,40 +15,42 @@ // You should have received a copy of the GNU General Public License // along with Flameshot. If not, see . - #include "openwithprogram.h" #if defined(Q_OS_WIN) #include "src/utils/filenamehandler.h" #include #include -#include #include +#include #pragma comment(lib, "Shell32.lib") #else #include "src/tools/launcher/applauncherwidget.h" #endif -void showOpenWithMenu(const QPixmap &capture) { +void +showOpenWithMenu(const QPixmap& capture) +{ #if defined(Q_OS_WIN) - QString tempFile = - FileNameHandler().generateAbsolutePath(QDir::tempPath()) + ".png"; - bool ok = capture.save(tempFile); - if (!ok) { - QMessageBox::about(nullptr, QObject::tr("Error"), - QObject::tr("Unable to write in") + QDir::tempPath()); - return; - } + QString tempFile = + FileNameHandler().generateAbsolutePath(QDir::tempPath()) + ".png"; + bool ok = capture.save(tempFile); + if (!ok) { + QMessageBox::about(nullptr, + QObject::tr("Error"), + QObject::tr("Unable to write in") + QDir::tempPath()); + return; + } - OPENASINFO info; - auto wStringFile = tempFile.replace("/", "\\").toStdWString(); - info.pcszFile = wStringFile.c_str(); - info.pcszClass = nullptr; - info.oaifInFlags = OAIF_ALLOW_REGISTRATION | OAIF_EXEC; - SHOpenWithDialog(nullptr, &info); + OPENASINFO info; + auto wStringFile = tempFile.replace("/", "\\").toStdWString(); + info.pcszFile = wStringFile.c_str(); + info.pcszClass = nullptr; + info.oaifInFlags = OAIF_ALLOW_REGISTRATION | OAIF_EXEC; + SHOpenWithDialog(nullptr, &info); #else - auto w = new AppLauncherWidget(capture); - w->show(); + auto w = new AppLauncherWidget(capture); + w->show(); #endif } diff --git a/src/tools/launcher/openwithprogram.h b/src/tools/launcher/openwithprogram.h index eed4f892..5aa9b24c 100644 --- a/src/tools/launcher/openwithprogram.h +++ b/src/tools/launcher/openwithprogram.h @@ -19,4 +19,5 @@ #include -void showOpenWithMenu(const QPixmap &capture); +void +showOpenWithMenu(const QPixmap& capture); diff --git a/src/tools/launcher/terminallauncher.cpp b/src/tools/launcher/terminallauncher.cpp index 4369d2e1..e7a27d43 100644 --- a/src/tools/launcher/terminallauncher.cpp +++ b/src/tools/launcher/terminallauncher.cpp @@ -16,45 +16,50 @@ // along with Flameshot. If not, see . #include "terminallauncher.h" -#include #include -#include +#include #include +#include namespace { - static const TerminalApp terminalApps[] = { - { "x-terminal-emulator", "-e" }, - { "xfce4-terminal", "-x" }, - { "konsole", "-e" }, - { "gnome-terminal", "--" }, - { "terminator", "-e" }, - { "terminology", "-e" }, - { "tilix", "-e" }, - { "xterm", "-e" }, - { "aterm", "-e" }, - { "Eterm", "-e" }, - { "rxvt", "-e" }, - { "urxvt", "-e" }, - }; +static const TerminalApp terminalApps[] = { + { "x-terminal-emulator", "-e" }, + { "xfce4-terminal", "-x" }, + { "konsole", "-e" }, + { "gnome-terminal", "--" }, + { "terminator", "-e" }, + { "terminology", "-e" }, + { "tilix", "-e" }, + { "xterm", "-e" }, + { "aterm", "-e" }, + { "Eterm", "-e" }, + { "rxvt", "-e" }, + { "urxvt", "-e" }, +}; } -TerminalLauncher::TerminalLauncher(QObject *parent) : QObject(parent) { -} +TerminalLauncher::TerminalLauncher(QObject* parent) + : QObject(parent) +{} -TerminalApp TerminalLauncher::getPreferedTerminal() { - TerminalApp res; - for (const TerminalApp &app : terminalApps) { - QString path = QStandardPaths::findExecutable(app.name); - if (!path.isEmpty()) { - res = app; - break; - } +TerminalApp +TerminalLauncher::getPreferedTerminal() +{ + TerminalApp res; + for (const TerminalApp& app : terminalApps) { + QString path = QStandardPaths::findExecutable(app.name); + if (!path.isEmpty()) { + res = app; + break; } - return res; + } + return res; } -bool TerminalLauncher::launchDetached(const QString &command) { - TerminalApp app = getPreferedTerminal(); - QString s = app.name + " " + app.arg + " " + command; - return QProcess::startDetached(app.name, {app.arg,command}); +bool +TerminalLauncher::launchDetached(const QString& command) +{ + TerminalApp app = getPreferedTerminal(); + QString s = app.name + " " + app.arg + " " + command; + return QProcess::startDetached(app.name, { app.arg, command }); } diff --git a/src/tools/launcher/terminallauncher.h b/src/tools/launcher/terminallauncher.h index 9a9af38e..c2fbf828 100644 --- a/src/tools/launcher/terminallauncher.h +++ b/src/tools/launcher/terminallauncher.h @@ -19,17 +19,20 @@ #include -struct TerminalApp { - QString name; - QString arg; +struct TerminalApp +{ + QString name; + QString arg; }; -class TerminalLauncher : public QObject { - Q_OBJECT +class TerminalLauncher : public QObject +{ + Q_OBJECT public: - explicit TerminalLauncher(QObject *parent = nullptr); + explicit TerminalLauncher(QObject* parent = nullptr); + + static bool launchDetached(const QString& command); - static bool launchDetached(const QString &command); private: - static TerminalApp getPreferedTerminal(); + static TerminalApp getPreferedTerminal(); }; diff --git a/src/tools/line/linetool.cpp b/src/tools/line/linetool.cpp index 343d3eb1..9231a869 100644 --- a/src/tools/line/linetool.cpp +++ b/src/tools/line/linetool.cpp @@ -24,51 +24,71 @@ namespace { } -LineTool::LineTool(QObject *parent) : AbstractTwoPointTool(parent) { - m_supportsOrthogonalAdj = true; - m_supportsDiagonalAdj = true; +LineTool::LineTool(QObject* parent) + : AbstractTwoPointTool(parent) +{ + m_supportsOrthogonalAdj = true; + m_supportsDiagonalAdj = true; } -QIcon LineTool::icon(const QColor &background, bool inEditor) const { - Q_UNUSED(inEditor); - return QIcon(iconPath(background) + "line.svg"); +QIcon +LineTool::icon(const QColor& background, bool inEditor) const +{ + Q_UNUSED(inEditor); + return QIcon(iconPath(background) + "line.svg"); } -QString LineTool::name() const { - return tr("Line"); +QString +LineTool::name() const +{ + return tr("Line"); } -QString LineTool::nameID() { - return QLatin1String(""); +QString +LineTool::nameID() +{ + return QLatin1String(""); } -QString LineTool::description() const { - return tr("Set the Line as the paint tool"); +QString +LineTool::description() const +{ + return tr("Set the Line as the paint tool"); } -CaptureTool* LineTool::copy(QObject *parent) { - return new LineTool(parent); +CaptureTool* +LineTool::copy(QObject* parent) +{ + return new LineTool(parent); } -void LineTool::process(QPainter &painter, const QPixmap &pixmap, bool recordUndo) { - if (recordUndo) { - updateBackup(pixmap); - } - painter.setPen(QPen(m_color, m_thickness)); - painter.drawLine(m_points.first, m_points.second); +void +LineTool::process(QPainter& painter, const QPixmap& pixmap, bool recordUndo) +{ + if (recordUndo) { + updateBackup(pixmap); + } + painter.setPen(QPen(m_color, m_thickness)); + painter.drawLine(m_points.first, m_points.second); } -void LineTool::paintMousePreview(QPainter &painter, const CaptureContext &context) { - painter.setPen(QPen(context.color, PADDING_VALUE + context.thickness)); - painter.drawLine(context.mousePos, context.mousePos); +void +LineTool::paintMousePreview(QPainter& painter, const CaptureContext& context) +{ + painter.setPen(QPen(context.color, PADDING_VALUE + context.thickness)); + painter.drawLine(context.mousePos, context.mousePos); } -void LineTool::drawStart(const CaptureContext &context) { - m_color = context.color; - m_thickness = context.thickness + PADDING_VALUE; - m_points.first = context.mousePos; - m_points.second = context.mousePos; +void +LineTool::drawStart(const CaptureContext& context) +{ + m_color = context.color; + m_thickness = context.thickness + PADDING_VALUE; + m_points.first = context.mousePos; + m_points.second = context.mousePos; } -void LineTool::pressed(const CaptureContext &context) { - Q_UNUSED(context); +void +LineTool::pressed(const CaptureContext& context) +{ + Q_UNUSED(context); } diff --git a/src/tools/line/linetool.h b/src/tools/line/linetool.h index bb140656..90bc98d7 100644 --- a/src/tools/line/linetool.h +++ b/src/tools/line/linetool.h @@ -19,22 +19,25 @@ #include "src/tools/abstracttwopointtool.h" -class LineTool : public AbstractTwoPointTool { - Q_OBJECT +class LineTool : public AbstractTwoPointTool +{ + Q_OBJECT public: - explicit LineTool(QObject *parent = nullptr); + explicit LineTool(QObject* parent = nullptr); - QIcon icon(const QColor &background, bool inEditor) const override; - QString name() const override; - static QString nameID(); - QString description() const override; + QIcon icon(const QColor& background, bool inEditor) const override; + QString name() const override; + static QString nameID(); + QString description() const override; - CaptureTool* copy(QObject *parent = nullptr) override; - void process( - QPainter &painter, const QPixmap &pixmap, bool recordUndo = false) override; - void paintMousePreview(QPainter &painter, const CaptureContext &context) override; + CaptureTool* copy(QObject* parent = nullptr) override; + void process(QPainter& painter, + const QPixmap& pixmap, + bool recordUndo = false) override; + void paintMousePreview(QPainter& painter, + const CaptureContext& context) override; public slots: - void drawStart(const CaptureContext &context) override; - void pressed(const CaptureContext &context) override; + void drawStart(const CaptureContext& context) override; + void pressed(const CaptureContext& context) override; }; diff --git a/src/tools/marker/markertool.cpp b/src/tools/marker/markertool.cpp index b5d027bb..8f899f8b 100644 --- a/src/tools/marker/markertool.cpp +++ b/src/tools/marker/markertool.cpp @@ -24,59 +24,81 @@ namespace { } -MarkerTool::MarkerTool(QObject *parent) : AbstractTwoPointTool(parent) { - m_supportsOrthogonalAdj = true; - m_supportsDiagonalAdj = true; +MarkerTool::MarkerTool(QObject* parent) + : AbstractTwoPointTool(parent) +{ + m_supportsOrthogonalAdj = true; + m_supportsDiagonalAdj = true; } -QIcon MarkerTool::icon(const QColor &background, bool inEditor) const { - Q_UNUSED(inEditor); - return QIcon(iconPath(background) + "marker.svg"); +QIcon +MarkerTool::icon(const QColor& background, bool inEditor) const +{ + Q_UNUSED(inEditor); + return QIcon(iconPath(background) + "marker.svg"); } -QString MarkerTool::name() const { - return tr("Marker"); +QString +MarkerTool::name() const +{ + return tr("Marker"); } -QString MarkerTool::nameID() { - return QLatin1String(""); +QString +MarkerTool::nameID() +{ + return QLatin1String(""); } -QString MarkerTool::description() const { - return tr("Set the Marker as the paint tool"); +QString +MarkerTool::description() const +{ + return tr("Set the Marker as the paint tool"); } -CaptureTool* MarkerTool::copy(QObject *parent) { - return new MarkerTool(parent); +CaptureTool* +MarkerTool::copy(QObject* parent) +{ + return new MarkerTool(parent); } -void MarkerTool::process(QPainter &painter, const QPixmap &pixmap, bool recordUndo) { - if (recordUndo) { - updateBackup(pixmap); - } - painter.setCompositionMode(QPainter::CompositionMode_Multiply); - painter.setOpacity(0.35); - painter.setPen(QPen(m_color, m_thickness)); - painter.drawLine(m_points.first, m_points.second); +void +MarkerTool::process(QPainter& painter, const QPixmap& pixmap, bool recordUndo) +{ + if (recordUndo) { + updateBackup(pixmap); + } + painter.setCompositionMode(QPainter::CompositionMode_Multiply); + painter.setOpacity(0.35); + painter.setPen(QPen(m_color, m_thickness)); + painter.drawLine(m_points.first, m_points.second); } -void MarkerTool::paintMousePreview(QPainter &painter, const CaptureContext &context) { - painter.setCompositionMode(QPainter::CompositionMode_Multiply); - painter.setOpacity(0.35); - painter.setPen(QPen(context.color, PADDING_VALUE + context.thickness)); - painter.drawLine(context.mousePos, context.mousePos); +void +MarkerTool::paintMousePreview(QPainter& painter, const CaptureContext& context) +{ + painter.setCompositionMode(QPainter::CompositionMode_Multiply); + painter.setOpacity(0.35); + painter.setPen(QPen(context.color, PADDING_VALUE + context.thickness)); + painter.drawLine(context.mousePos, context.mousePos); } -void MarkerTool::drawStart(const CaptureContext &context) { - m_color = context.color; - m_thickness = context.thickness + PADDING_VALUE; - m_points.first = context.mousePos; - m_points.second = context.mousePos; +void +MarkerTool::drawStart(const CaptureContext& context) +{ + m_color = context.color; + m_thickness = context.thickness + PADDING_VALUE; + m_points.first = context.mousePos; + m_points.second = context.mousePos; } -void MarkerTool::pressed(const CaptureContext &context) { - Q_UNUSED(context); +void +MarkerTool::pressed(const CaptureContext& context) +{ + Q_UNUSED(context); } -void MarkerTool::thicknessChanged(const int th) { - m_thickness = th + PADDING_VALUE; +void +MarkerTool::thicknessChanged(const int th) +{ + m_thickness = th + PADDING_VALUE; } diff --git a/src/tools/marker/markertool.h b/src/tools/marker/markertool.h index 4d71e48e..d243a544 100644 --- a/src/tools/marker/markertool.h +++ b/src/tools/marker/markertool.h @@ -19,23 +19,26 @@ #include "src/tools/abstracttwopointtool.h" -class MarkerTool : public AbstractTwoPointTool { - Q_OBJECT +class MarkerTool : public AbstractTwoPointTool +{ + Q_OBJECT public: - explicit MarkerTool(QObject *parent = nullptr); + explicit MarkerTool(QObject* parent = nullptr); - QIcon icon(const QColor &background, bool inEditor) const override; - QString name() const override; - static QString nameID(); - QString description() const override; + QIcon icon(const QColor& background, bool inEditor) const override; + QString name() const override; + static QString nameID(); + QString description() const override; - CaptureTool* copy(QObject *parent = nullptr) override; - void process( - QPainter &painter, const QPixmap &pixmap, bool recordUndo = false) override; - void paintMousePreview(QPainter &painter, const CaptureContext &context) override; + CaptureTool* copy(QObject* parent = nullptr) override; + void process(QPainter& painter, + const QPixmap& pixmap, + bool recordUndo = false) override; + void paintMousePreview(QPainter& painter, + const CaptureContext& context) override; public slots: - void drawStart(const CaptureContext &context) override; - void pressed(const CaptureContext &context) override; - void thicknessChanged(const int th) override; + void drawStart(const CaptureContext& context) override; + void pressed(const CaptureContext& context) override; + void thicknessChanged(const int th) override; }; diff --git a/src/tools/move/movetool.cpp b/src/tools/move/movetool.cpp index faa1cca3..3dbd4bf1 100644 --- a/src/tools/move/movetool.cpp +++ b/src/tools/move/movetool.cpp @@ -18,35 +18,49 @@ #include "movetool.h" #include -MoveTool::MoveTool(QObject *parent) : AbstractActionTool(parent) { +MoveTool::MoveTool(QObject* parent) + : AbstractActionTool(parent) +{} +bool +MoveTool::closeOnButtonPressed() const +{ + return false; } -bool MoveTool::closeOnButtonPressed() const { - return false; +QIcon +MoveTool::icon(const QColor& background, bool inEditor) const +{ + Q_UNUSED(inEditor); + return QIcon(iconPath(background) + "cursor-move.svg"); +} +QString +MoveTool::name() const +{ + return tr("Move"); } -QIcon MoveTool::icon(const QColor &background, bool inEditor) const { - Q_UNUSED(inEditor); - return QIcon(iconPath(background) + "cursor-move.svg"); -} -QString MoveTool::name() const { - return tr("Move"); +QString +MoveTool::nameID() +{ + return QLatin1String(""); } -QString MoveTool::nameID() { - return QLatin1String(""); +QString +MoveTool::description() const +{ + return tr("Move the selection area"); } -QString MoveTool::description() const { - return tr("Move the selection area"); +CaptureTool* +MoveTool::copy(QObject* parent) +{ + return new MoveTool(parent); } -CaptureTool* MoveTool::copy(QObject *parent) { - return new MoveTool(parent); -} - -void MoveTool::pressed(const CaptureContext &context) { - Q_UNUSED(context); - emit requestAction(REQ_MOVE_MODE); +void +MoveTool::pressed(const CaptureContext& context) +{ + Q_UNUSED(context); + emit requestAction(REQ_MOVE_MODE); } diff --git a/src/tools/move/movetool.h b/src/tools/move/movetool.h index 5126eb77..c1f64464 100644 --- a/src/tools/move/movetool.h +++ b/src/tools/move/movetool.h @@ -19,20 +19,21 @@ #include "src/tools/abstractactiontool.h" -class MoveTool : public AbstractActionTool { - Q_OBJECT +class MoveTool : public AbstractActionTool +{ + Q_OBJECT public: - explicit MoveTool(QObject *parent = nullptr); + explicit MoveTool(QObject* parent = nullptr); - bool closeOnButtonPressed() const; + bool closeOnButtonPressed() const; - QIcon icon(const QColor &background, bool inEditor) const override; - QString name() const override; - static QString nameID(); - QString description() const override; + QIcon icon(const QColor& background, bool inEditor) const override; + QString name() const override; + static QString nameID(); + QString description() const override; - CaptureTool* copy(QObject *parent = nullptr) override; + CaptureTool* copy(QObject* parent = nullptr) override; public slots: - void pressed(const CaptureContext &context) override; + void pressed(const CaptureContext& context) override; }; diff --git a/src/tools/pencil/penciltool.cpp b/src/tools/pencil/penciltool.cpp index 377a80a4..1225a1da 100644 --- a/src/tools/pencil/penciltool.cpp +++ b/src/tools/pencil/penciltool.cpp @@ -18,51 +18,69 @@ #include "penciltool.h" #include -PencilTool::PencilTool(QObject *parent) : AbstractPathTool(parent) { +PencilTool::PencilTool(QObject* parent) + : AbstractPathTool(parent) +{} +QIcon +PencilTool::icon(const QColor& background, bool inEditor) const +{ + Q_UNUSED(inEditor); + return QIcon(iconPath(background) + "pencil.svg"); +} +QString +PencilTool::name() const +{ + return tr("Pencil"); } -QIcon PencilTool::icon(const QColor &background, bool inEditor) const { - Q_UNUSED(inEditor); - return QIcon(iconPath(background) + "pencil.svg"); -} -QString PencilTool::name() const { - return tr("Pencil"); +QString +PencilTool::nameID() +{ + return QLatin1String(""); } -QString PencilTool::nameID() { - return QLatin1String(""); +QString +PencilTool::description() const +{ + return tr("Set the Pencil as the paint tool"); } -QString PencilTool::description() const { - return tr("Set the Pencil as the paint tool"); +CaptureTool* +PencilTool::copy(QObject* parent) +{ + return new PencilTool(parent); } -CaptureTool* PencilTool::copy(QObject *parent) { - return new PencilTool(parent); +void +PencilTool::process(QPainter& painter, const QPixmap& pixmap, bool recordUndo) +{ + if (recordUndo) { + updateBackup(pixmap); + } + painter.setPen(QPen(m_color, m_thickness)); + painter.drawPolyline(m_points.data(), m_points.size()); } -void PencilTool::process(QPainter &painter, const QPixmap &pixmap, bool recordUndo) { - if (recordUndo) { - updateBackup(pixmap); - } - painter.setPen(QPen(m_color, m_thickness)); - painter.drawPolyline(m_points.data(), m_points.size()); +void +PencilTool::paintMousePreview(QPainter& painter, const CaptureContext& context) +{ + painter.setPen(QPen(context.color, context.thickness + 2)); + painter.drawLine(context.mousePos, context.mousePos); } -void PencilTool::paintMousePreview(QPainter &painter, const CaptureContext &context) { - painter.setPen(QPen(context.color, context.thickness + 2)); - painter.drawLine(context.mousePos, context.mousePos); +void +PencilTool::drawStart(const CaptureContext& context) +{ + m_color = context.color; + m_thickness = context.thickness + 2; + m_points.append(context.mousePos); + m_backupArea.setTopLeft(context.mousePos); + m_backupArea.setBottomRight(context.mousePos); } -void PencilTool::drawStart(const CaptureContext &context) { - m_color = context.color; - m_thickness = context.thickness + 2; - m_points.append(context.mousePos); - m_backupArea.setTopLeft(context.mousePos); - m_backupArea.setBottomRight(context.mousePos); -} - -void PencilTool::pressed(const CaptureContext &context) { - Q_UNUSED(context); +void +PencilTool::pressed(const CaptureContext& context) +{ + Q_UNUSED(context); } diff --git a/src/tools/pencil/penciltool.h b/src/tools/pencil/penciltool.h index feaf9c07..89dce824 100644 --- a/src/tools/pencil/penciltool.h +++ b/src/tools/pencil/penciltool.h @@ -19,23 +19,26 @@ #include "src/tools/abstractpathtool.h" -class PencilTool : public AbstractPathTool { - Q_OBJECT +class PencilTool : public AbstractPathTool +{ + Q_OBJECT public: - explicit PencilTool(QObject *parent = nullptr); + explicit PencilTool(QObject* parent = nullptr); - QIcon icon(const QColor &background, bool inEditor) const override; - QString name() const override; - static QString nameID(); - QString description() const override; + QIcon icon(const QColor& background, bool inEditor) const override; + QString name() const override; + static QString nameID(); + QString description() const override; - CaptureTool* copy(QObject *parent = nullptr) override; + CaptureTool* copy(QObject* parent = nullptr) override; - void process( - QPainter &painter, const QPixmap &pixmap, bool recordUndo = false) override; - void paintMousePreview(QPainter &painter, const CaptureContext &context) override; + void process(QPainter& painter, + const QPixmap& pixmap, + bool recordUndo = false) override; + void paintMousePreview(QPainter& painter, + const CaptureContext& context) override; public slots: - void drawStart(const CaptureContext &context) override; - void pressed(const CaptureContext &context) override; + void drawStart(const CaptureContext& context) override; + void pressed(const CaptureContext& context) override; }; diff --git a/src/tools/pin/pintool.cpp b/src/tools/pin/pintool.cpp index 20a70194..54b10af4 100644 --- a/src/tools/pin/pintool.cpp +++ b/src/tools/pin/pintool.cpp @@ -18,47 +18,62 @@ #include "pintool.h" #include "src/tools/pin/pinwidget.h" -PinTool::PinTool(QObject *parent) : AbstractActionTool(parent) { +PinTool::PinTool(QObject* parent) + : AbstractActionTool(parent) +{} +bool +PinTool::closeOnButtonPressed() const +{ + return true; } -bool PinTool::closeOnButtonPressed() const { - return true; +QIcon +PinTool::icon(const QColor& background, bool inEditor) const +{ + Q_UNUSED(inEditor); + return QIcon(iconPath(background) + "pin.svg"); +} +QString +PinTool::name() const +{ + return tr("Pin Tool"); } -QIcon PinTool::icon(const QColor &background, bool inEditor) const { - Q_UNUSED(inEditor); - return QIcon(iconPath(background) + "pin.svg"); -} -QString PinTool::name() const { - return tr("Pin Tool"); +QString +PinTool::nameID() +{ + return QLatin1String(""); } -QString PinTool::nameID() { - return QLatin1String(""); +QString +PinTool::description() const +{ + return tr("Pin image on the desktop"); } -QString PinTool::description() const { - return tr("Pin image on the desktop"); +QWidget* +PinTool::widget() +{ + PinWidget* w = new PinWidget(m_pixmap); + const int&& m = w->margin(); + QRect adjusted_pos = m_geometry + QMargins(m, m, m, m); + w->setGeometry(adjusted_pos); + return w; } -QWidget* PinTool::widget() { - PinWidget *w = new PinWidget(m_pixmap); - const int &&m = w->margin(); - QRect adjusted_pos = m_geometry + QMargins(m, m, m, m); - w->setGeometry(adjusted_pos); - return w; +CaptureTool* +PinTool::copy(QObject* parent) +{ + return new PinTool(parent); } -CaptureTool* PinTool::copy(QObject *parent) { - return new PinTool(parent); -} - -void PinTool::pressed(const CaptureContext &context) { - emit requestAction(REQ_CAPTURE_DONE_OK); - m_geometry = context.selection; - m_geometry.setTopLeft(m_geometry.topLeft() + context.widgetOffset); - m_pixmap = context.selectedScreenshotArea(); - emit requestAction(REQ_ADD_EXTERNAL_WIDGETS); - +void +PinTool::pressed(const CaptureContext& context) +{ + emit requestAction(REQ_CAPTURE_DONE_OK); + m_geometry = context.selection; + m_geometry.setTopLeft(m_geometry.topLeft() + context.widgetOffset); + m_pixmap = context.selectedScreenshotArea(); + emit requestAction(REQ_ADD_EXTERNAL_WIDGETS); } diff --git a/src/tools/pin/pintool.h b/src/tools/pin/pintool.h old mode 100755 new mode 100644 index 7690517f..e4c911f4 --- a/src/tools/pin/pintool.h +++ b/src/tools/pin/pintool.h @@ -19,26 +19,27 @@ #include "src/tools/abstractactiontool.h" -class PinTool : public AbstractActionTool { - Q_OBJECT +class PinTool : public AbstractActionTool +{ + Q_OBJECT public: - explicit PinTool(QObject *parent = nullptr); + explicit PinTool(QObject* parent = nullptr); - bool closeOnButtonPressed() const; + bool closeOnButtonPressed() const; - QIcon icon(const QColor &background, bool inEditor) const override; - QString name() const override; - static QString nameID(); - QString description() const override; + QIcon icon(const QColor& background, bool inEditor) const override; + QString name() const override; + static QString nameID(); + QString description() const override; - QWidget* widget() override; + QWidget* widget() override; - CaptureTool* copy(QObject *parent = nullptr) override; + CaptureTool* copy(QObject* parent = nullptr) override; public slots: - void pressed(const CaptureContext &context) override; + void pressed(const CaptureContext& context) override; private: - QRect m_geometry; - QPixmap m_pixmap; + QRect m_geometry; + QPixmap m_pixmap; }; diff --git a/src/tools/pin/pinwidget.cpp b/src/tools/pin/pinwidget.cpp index 6999839b..d50288ce 100644 --- a/src/tools/pin/pinwidget.cpp +++ b/src/tools/pin/pinwidget.cpp @@ -17,86 +17,103 @@ #include "pinwidget.h" #include "src/utils/confighandler.h" +#include #include +#include #include #include -#include -#include -PinWidget::PinWidget(const QPixmap &pixmap, QWidget *parent) : - QWidget(parent), m_pixmap(pixmap) +PinWidget::PinWidget(const QPixmap& pixmap, QWidget* parent) + : QWidget(parent) + , m_pixmap(pixmap) { - setWindowFlags(Qt::WindowStaysOnTopHint - | Qt::FramelessWindowHint); - //set the bottom widget background transparent - setAttribute(Qt::WA_TranslucentBackground); + setWindowFlags(Qt::WindowStaysOnTopHint | Qt::FramelessWindowHint); + // set the bottom widget background transparent + setAttribute(Qt::WA_TranslucentBackground); - ConfigHandler conf; - m_baseColor = conf.uiMainColorValue(); - m_hoverColor = conf.uiContrastColorValue(); + ConfigHandler conf; + m_baseColor = conf.uiMainColorValue(); + m_hoverColor = conf.uiContrastColorValue(); - m_layout = new QVBoxLayout(this); - const int margin = this->margin(); - m_layout->setContentsMargins(margin, margin, margin, margin); + m_layout = new QVBoxLayout(this); + const int margin = this->margin(); + m_layout->setContentsMargins(margin, margin, margin, margin); - m_shadowEffect = new QGraphicsDropShadowEffect(this); - m_shadowEffect->setColor(m_baseColor); - m_shadowEffect->setBlurRadius(2 * margin); - m_shadowEffect->setOffset(0, 0); - setGraphicsEffect(m_shadowEffect); + m_shadowEffect = new QGraphicsDropShadowEffect(this); + m_shadowEffect->setColor(m_baseColor); + m_shadowEffect->setBlurRadius(2 * margin); + m_shadowEffect->setOffset(0, 0); + setGraphicsEffect(m_shadowEffect); - m_label = new QLabel(); - m_label->setPixmap(m_pixmap); - m_layout->addWidget(m_label); + m_label = new QLabel(); + m_label->setPixmap(m_pixmap); + m_layout->addWidget(m_label); - new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_Q), this, SLOT(close())); - new QShortcut(Qt::Key_Escape, this, SLOT(close())); + new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_Q), this, SLOT(close())); + new QShortcut(Qt::Key_Escape, this, SLOT(close())); } -int PinWidget::margin() const { - return 7; +int +PinWidget::margin() const +{ + return 7; } -void PinWidget::wheelEvent(QWheelEvent *e) { - int val = e->angleDelta().y() > 0 ? 15 : -15; - int newWidth = qBound(50, m_label->width() + val, maximumWidth()); - int newHeight = qBound(50, m_label->height() + val, maximumHeight()); +void +PinWidget::wheelEvent(QWheelEvent* e) +{ + int val = e->angleDelta().y() > 0 ? 15 : -15; + int newWidth = qBound(50, m_label->width() + val, maximumWidth()); + int newHeight = qBound(50, m_label->height() + val, maximumHeight()); - QSize size(newWidth, newHeight); - setScaledPixmap(size); - adjustSize(); + QSize size(newWidth, newHeight); + setScaledPixmap(size); + adjustSize(); - e->accept(); + e->accept(); } -void PinWidget::enterEvent(QEvent *) { - m_shadowEffect->setColor(m_hoverColor); +void +PinWidget::enterEvent(QEvent*) +{ + m_shadowEffect->setColor(m_hoverColor); } -void PinWidget::leaveEvent(QEvent *) { - m_shadowEffect->setColor(m_baseColor); +void +PinWidget::leaveEvent(QEvent*) +{ + m_shadowEffect->setColor(m_baseColor); } -void PinWidget::mouseDoubleClickEvent(QMouseEvent *) { - close(); +void +PinWidget::mouseDoubleClickEvent(QMouseEvent*) +{ + close(); } -void PinWidget::mousePressEvent(QMouseEvent *e) { - m_dragStart = e->globalPos(); - m_offsetX = e->localPos().x() / width(); - m_offsetY = e->localPos().y() / height(); +void +PinWidget::mousePressEvent(QMouseEvent* e) +{ + m_dragStart = e->globalPos(); + m_offsetX = e->localPos().x() / width(); + m_offsetY = e->localPos().y() / height(); } -void PinWidget::mouseMoveEvent(QMouseEvent *e) { - const QPoint delta = e->globalPos() - m_dragStart; - int offsetW = width() * m_offsetX; - int offsetH = height() * m_offsetY; - move(m_dragStart.x() + delta.x() - offsetW, m_dragStart.y() + delta.y() - offsetH); +void +PinWidget::mouseMoveEvent(QMouseEvent* e) +{ + const QPoint delta = e->globalPos() - m_dragStart; + int offsetW = width() * m_offsetX; + int offsetH = height() * m_offsetY; + move(m_dragStart.x() + delta.x() - offsetW, + m_dragStart.y() + delta.y() - offsetH); } -void PinWidget::setScaledPixmap(const QSize &size) { - const qreal scale = qApp->devicePixelRatio(); - QPixmap scaledPixmap = m_pixmap.scaled(size * scale, Qt::KeepAspectRatio, - Qt::SmoothTransformation); - scaledPixmap.setDevicePixelRatio(scale); - m_label->setPixmap(scaledPixmap); +void +PinWidget::setScaledPixmap(const QSize& size) +{ + const qreal scale = qApp->devicePixelRatio(); + QPixmap scaledPixmap = m_pixmap.scaled( + size * scale, Qt::KeepAspectRatio, Qt::SmoothTransformation); + scaledPixmap.setDevicePixelRatio(scale); + m_label->setPixmap(scaledPixmap); } diff --git a/src/tools/pin/pinwidget.h b/src/tools/pin/pinwidget.h index 8dab1d38..435b72da 100644 --- a/src/tools/pin/pinwidget.h +++ b/src/tools/pin/pinwidget.h @@ -17,35 +17,36 @@ #pragma once -#include #include +#include class QVBoxLayout; class QLabel; -class PinWidget : public QWidget { - Q_OBJECT +class PinWidget : public QWidget +{ + Q_OBJECT public: - explicit PinWidget(const QPixmap &pixmap, QWidget *parent = nullptr); + explicit PinWidget(const QPixmap& pixmap, QWidget* parent = nullptr); - int margin() const; + int margin() const; protected: - void wheelEvent(QWheelEvent *e); - void mouseDoubleClickEvent(QMouseEvent *); - void mousePressEvent(QMouseEvent *); - void mouseMoveEvent(QMouseEvent *); - void enterEvent(QEvent *); - void leaveEvent(QEvent *); + void wheelEvent(QWheelEvent* e); + void mouseDoubleClickEvent(QMouseEvent*); + void mousePressEvent(QMouseEvent*); + void mouseMoveEvent(QMouseEvent*); + void enterEvent(QEvent*); + void leaveEvent(QEvent*); private: - void setScaledPixmap(const QSize &size); + void setScaledPixmap(const QSize& size); - QPixmap m_pixmap; - QVBoxLayout *m_layout; - QLabel *m_label; - QPoint m_dragStart; - qreal m_offsetX, m_offsetY; - QGraphicsDropShadowEffect *m_shadowEffect; - QColor m_baseColor, m_hoverColor; + QPixmap m_pixmap; + QVBoxLayout* m_layout; + QLabel* m_label; + QPoint m_dragStart; + qreal m_offsetX, m_offsetY; + QGraphicsDropShadowEffect* m_shadowEffect; + QColor m_baseColor, m_hoverColor; }; diff --git a/src/tools/rectangle/rectangletool.cpp b/src/tools/rectangle/rectangletool.cpp index 9d972582..a1215f2e 100644 --- a/src/tools/rectangle/rectangletool.cpp +++ b/src/tools/rectangle/rectangletool.cpp @@ -22,51 +22,74 @@ namespace { #define PADDING_VALUE 2 } -RectangleTool::RectangleTool(QObject *parent) : AbstractTwoPointTool(parent) { - m_supportsDiagonalAdj = true; +RectangleTool::RectangleTool(QObject* parent) + : AbstractTwoPointTool(parent) +{ + m_supportsDiagonalAdj = true; } -QIcon RectangleTool::icon(const QColor &background, bool inEditor) const { - Q_UNUSED(inEditor); - return QIcon(iconPath(background) + "square.svg"); +QIcon +RectangleTool::icon(const QColor& background, bool inEditor) const +{ + Q_UNUSED(inEditor); + return QIcon(iconPath(background) + "square.svg"); } -QString RectangleTool::name() const { - return tr("Rectangle"); +QString +RectangleTool::name() const +{ + return tr("Rectangle"); } -QString RectangleTool::nameID() { - return QLatin1String(""); +QString +RectangleTool::nameID() +{ + return QLatin1String(""); } -QString RectangleTool::description() const { - return tr("Set the Rectangle as the paint tool"); +QString +RectangleTool::description() const +{ + return tr("Set the Rectangle as the paint tool"); } -CaptureTool* RectangleTool::copy(QObject *parent) { - return new RectangleTool(parent); +CaptureTool* +RectangleTool::copy(QObject* parent) +{ + return new RectangleTool(parent); } -void RectangleTool::process(QPainter &painter, const QPixmap &pixmap, bool recordUndo) { - if (recordUndo) { - updateBackup(pixmap); - } - painter.setPen(QPen(m_color, m_thickness)); - painter.setBrush(QBrush(m_color)); - painter.drawRect(QRect(m_points.first, m_points.second)); +void +RectangleTool::process(QPainter& painter, + const QPixmap& pixmap, + bool recordUndo) +{ + if (recordUndo) { + updateBackup(pixmap); + } + painter.setPen(QPen(m_color, m_thickness)); + painter.setBrush(QBrush(m_color)); + painter.drawRect(QRect(m_points.first, m_points.second)); } -void RectangleTool::paintMousePreview(QPainter &painter, const CaptureContext &context) { - painter.setPen(QPen(context.color, PADDING_VALUE + context.thickness)); - painter.drawLine(context.mousePos, context.mousePos); +void +RectangleTool::paintMousePreview(QPainter& painter, + const CaptureContext& context) +{ + painter.setPen(QPen(context.color, PADDING_VALUE + context.thickness)); + painter.drawLine(context.mousePos, context.mousePos); } -void RectangleTool::drawStart(const CaptureContext &context) { - m_color = context.color; - m_thickness = context.thickness + PADDING_VALUE; - m_points.first = context.mousePos; - m_points.second = context.mousePos; +void +RectangleTool::drawStart(const CaptureContext& context) +{ + m_color = context.color; + m_thickness = context.thickness + PADDING_VALUE; + m_points.first = context.mousePos; + m_points.second = context.mousePos; } -void RectangleTool::pressed(const CaptureContext &context) { - Q_UNUSED(context); +void +RectangleTool::pressed(const CaptureContext& context) +{ + Q_UNUSED(context); } diff --git a/src/tools/rectangle/rectangletool.h b/src/tools/rectangle/rectangletool.h index 99d1b21f..3116d36f 100644 --- a/src/tools/rectangle/rectangletool.h +++ b/src/tools/rectangle/rectangletool.h @@ -19,22 +19,25 @@ #include "src/tools/abstracttwopointtool.h" -class RectangleTool : public AbstractTwoPointTool { - Q_OBJECT +class RectangleTool : public AbstractTwoPointTool +{ + Q_OBJECT public: - explicit RectangleTool(QObject *parent = nullptr); + explicit RectangleTool(QObject* parent = nullptr); - QIcon icon(const QColor &background, bool inEditor) const override; - QString name() const override; - static QString nameID(); - QString description() const override; + QIcon icon(const QColor& background, bool inEditor) const override; + QString name() const override; + static QString nameID(); + QString description() const override; - CaptureTool* copy(QObject *parent = nullptr) override; - void process( - QPainter &painter, const QPixmap &pixmap, bool recordUndo = false) override; - void paintMousePreview(QPainter &painter, const CaptureContext &context) override; + CaptureTool* copy(QObject* parent = nullptr) override; + void process(QPainter& painter, + const QPixmap& pixmap, + bool recordUndo = false) override; + void paintMousePreview(QPainter& painter, + const CaptureContext& context) override; public slots: - void drawStart(const CaptureContext &context) override; - void pressed(const CaptureContext &context) override; + void drawStart(const CaptureContext& context) override; + void pressed(const CaptureContext& context) override; }; diff --git a/src/tools/redo/redotool.cpp b/src/tools/redo/redotool.cpp index 0f8d4e02..45ca5304 100644 --- a/src/tools/redo/redotool.cpp +++ b/src/tools/redo/redotool.cpp @@ -18,35 +18,49 @@ #include "redotool.h" #include -RedoTool::RedoTool(QObject *parent) : AbstractActionTool(parent) { +RedoTool::RedoTool(QObject* parent) + : AbstractActionTool(parent) +{} +bool +RedoTool::closeOnButtonPressed() const +{ + return false; } -bool RedoTool::closeOnButtonPressed() const { - return false; +QIcon +RedoTool::icon(const QColor& background, bool inEditor) const +{ + Q_UNUSED(inEditor); + return QIcon(iconPath(background) + "redo-variant.svg"); +} +QString +RedoTool::name() const +{ + return tr("Redo"); } -QIcon RedoTool::icon(const QColor &background, bool inEditor) const { - Q_UNUSED(inEditor); - return QIcon(iconPath(background) + "redo-variant.svg"); -} -QString RedoTool::name() const { - return tr("Redo"); +QString +RedoTool::nameID() +{ + return QLatin1String(""); } -QString RedoTool::nameID() { - return QLatin1String(""); +QString +RedoTool::description() const +{ + return tr("Redo the next modification"); } -QString RedoTool::description() const { - return tr("Redo the next modification"); +CaptureTool* +RedoTool::copy(QObject* parent) +{ + return new RedoTool(parent); } -CaptureTool* RedoTool::copy(QObject *parent) { - return new RedoTool(parent); -} - -void RedoTool::pressed(const CaptureContext &context) { - Q_UNUSED(context); - emit requestAction(REQ_REDO_MODIFICATION); +void +RedoTool::pressed(const CaptureContext& context) +{ + Q_UNUSED(context); + emit requestAction(REQ_REDO_MODIFICATION); } diff --git a/src/tools/redo/redotool.h b/src/tools/redo/redotool.h index f538f137..876339a3 100644 --- a/src/tools/redo/redotool.h +++ b/src/tools/redo/redotool.h @@ -19,21 +19,21 @@ #include "src/tools/abstractactiontool.h" -class RedoTool : public AbstractActionTool { - Q_OBJECT +class RedoTool : public AbstractActionTool +{ + Q_OBJECT public: - explicit RedoTool(QObject *parent = nullptr); + explicit RedoTool(QObject* parent = nullptr); - bool closeOnButtonPressed() const; + bool closeOnButtonPressed() const; - QIcon icon(const QColor &background, bool inEditor) const override; - QString name() const override; - static QString nameID(); - QString description() const override; + QIcon icon(const QColor& background, bool inEditor) const override; + QString name() const override; + static QString nameID(); + QString description() const override; - CaptureTool* copy(QObject *parent = nullptr) override; + CaptureTool* copy(QObject* parent = nullptr) override; public slots: - void pressed(const CaptureContext &context) override; - + void pressed(const CaptureContext& context) override; }; diff --git a/src/tools/save/savetool.cpp b/src/tools/save/savetool.cpp index 29c337f5..05832ec3 100644 --- a/src/tools/save/savetool.cpp +++ b/src/tools/save/savetool.cpp @@ -19,47 +19,61 @@ #include "src/utils/screenshotsaver.h" #include -SaveTool::SaveTool(QObject *parent) : AbstractActionTool(parent) { +SaveTool::SaveTool(QObject* parent) + : AbstractActionTool(parent) +{} +bool +SaveTool::closeOnButtonPressed() const +{ + return true; } -bool SaveTool::closeOnButtonPressed() const { - return true; +QIcon +SaveTool::icon(const QColor& background, bool inEditor) const +{ + Q_UNUSED(inEditor); + return QIcon(iconPath(background) + "content-save.svg"); +} +QString +SaveTool::name() const +{ + return tr("Save"); } -QIcon SaveTool::icon(const QColor &background, bool inEditor) const { - Q_UNUSED(inEditor); - return QIcon(iconPath(background) + "content-save.svg"); -} -QString SaveTool::name() const { - return tr("Save"); +QString +SaveTool::nameID() +{ + return QLatin1String(""); } -QString SaveTool::nameID() { - return QLatin1String(""); +QString +SaveTool::description() const +{ + return tr("Save the capture"); } -QString SaveTool::description() const { - return tr("Save the capture"); +CaptureTool* +SaveTool::copy(QObject* parent) +{ + return new SaveTool(parent); } -CaptureTool* SaveTool::copy(QObject *parent) { - return new SaveTool(parent); -} - -void SaveTool::pressed(const CaptureContext &context) { - if (context.savePath.isEmpty()) { - emit requestAction(REQ_HIDE_GUI); - bool ok = ScreenshotSaver().saveToFilesystemGUI( - context.selectedScreenshotArea()); - if (ok) { - emit requestAction(REQ_CAPTURE_DONE_OK); - } - } else { - bool ok = ScreenshotSaver().saveToFilesystem( - context.selectedScreenshotArea(), context.savePath); - if (ok) { - emit requestAction(REQ_CAPTURE_DONE_OK); - } +void +SaveTool::pressed(const CaptureContext& context) +{ + if (context.savePath.isEmpty()) { + emit requestAction(REQ_HIDE_GUI); + bool ok = + ScreenshotSaver().saveToFilesystemGUI(context.selectedScreenshotArea()); + if (ok) { + emit requestAction(REQ_CAPTURE_DONE_OK); } + } else { + bool ok = ScreenshotSaver().saveToFilesystem( + context.selectedScreenshotArea(), context.savePath); + if (ok) { + emit requestAction(REQ_CAPTURE_DONE_OK); + } + } } diff --git a/src/tools/save/savetool.h b/src/tools/save/savetool.h index d5f75813..f3887c14 100644 --- a/src/tools/save/savetool.h +++ b/src/tools/save/savetool.h @@ -19,20 +19,21 @@ #include "src/tools/abstractactiontool.h" -class SaveTool : public AbstractActionTool { - Q_OBJECT +class SaveTool : public AbstractActionTool +{ + Q_OBJECT public: - explicit SaveTool(QObject *parent = nullptr); + explicit SaveTool(QObject* parent = nullptr); - bool closeOnButtonPressed() const; + bool closeOnButtonPressed() const; - QIcon icon(const QColor &background, bool inEditor) const override; - QString name() const override; - static QString nameID(); - QString description() const override; + QIcon icon(const QColor& background, bool inEditor) const override; + QString name() const override; + static QString nameID(); + QString description() const override; - CaptureTool* copy(QObject *parent = nullptr) override; + CaptureTool* copy(QObject* parent = nullptr) override; public slots: - void pressed(const CaptureContext &context) override; + void pressed(const CaptureContext& context) override; }; diff --git a/src/tools/selection/selectiontool.cpp b/src/tools/selection/selectiontool.cpp index 2717da9a..51d1ddcb 100644 --- a/src/tools/selection/selectiontool.cpp +++ b/src/tools/selection/selectiontool.cpp @@ -22,54 +22,79 @@ namespace { #define PADDING_VALUE 2 } -SelectionTool::SelectionTool(QObject *parent) : AbstractTwoPointTool(parent) { - m_supportsDiagonalAdj = true; +SelectionTool::SelectionTool(QObject* parent) + : AbstractTwoPointTool(parent) +{ + m_supportsDiagonalAdj = true; } -bool SelectionTool::closeOnButtonPressed() const { - return false; +bool +SelectionTool::closeOnButtonPressed() const +{ + return false; } -QIcon SelectionTool::icon(const QColor &background, bool inEditor) const { - Q_UNUSED(inEditor); - return QIcon(iconPath(background) + "square-outline.svg"); +QIcon +SelectionTool::icon(const QColor& background, bool inEditor) const +{ + Q_UNUSED(inEditor); + return QIcon(iconPath(background) + "square-outline.svg"); } -QString SelectionTool::name() const { - return tr("Rectangular Selection"); +QString +SelectionTool::name() const +{ + return tr("Rectangular Selection"); } -QString SelectionTool::nameID() { - return QLatin1String(""); +QString +SelectionTool::nameID() +{ + return QLatin1String(""); } -QString SelectionTool::description() const { - return tr("Set Selection as the paint tool"); +QString +SelectionTool::description() const +{ + return tr("Set Selection as the paint tool"); } -CaptureTool* SelectionTool::copy(QObject *parent) { - return new SelectionTool(parent); +CaptureTool* +SelectionTool::copy(QObject* parent) +{ + return new SelectionTool(parent); } -void SelectionTool::process(QPainter &painter, const QPixmap &pixmap, bool recordUndo) { - if (recordUndo) { - updateBackup(pixmap); - } - painter.setPen(QPen(m_color, m_thickness)); - painter.drawRect(QRect(m_points.first, m_points.second)); +void +SelectionTool::process(QPainter& painter, + const QPixmap& pixmap, + bool recordUndo) +{ + if (recordUndo) { + updateBackup(pixmap); + } + painter.setPen(QPen(m_color, m_thickness)); + painter.drawRect(QRect(m_points.first, m_points.second)); } -void SelectionTool::paintMousePreview(QPainter &painter, const CaptureContext &context) { - painter.setPen(QPen(context.color, PADDING_VALUE + context.thickness)); - painter.drawLine(context.mousePos, context.mousePos); +void +SelectionTool::paintMousePreview(QPainter& painter, + const CaptureContext& context) +{ + painter.setPen(QPen(context.color, PADDING_VALUE + context.thickness)); + painter.drawLine(context.mousePos, context.mousePos); } -void SelectionTool::drawStart(const CaptureContext &context) { - m_color = context.color; - m_thickness = context.thickness + PADDING_VALUE; - m_points.first = context.mousePos; - m_points.second = context.mousePos; +void +SelectionTool::drawStart(const CaptureContext& context) +{ + m_color = context.color; + m_thickness = context.thickness + PADDING_VALUE; + m_points.first = context.mousePos; + m_points.second = context.mousePos; } -void SelectionTool::pressed(const CaptureContext &context) { - Q_UNUSED(context); +void +SelectionTool::pressed(const CaptureContext& context) +{ + Q_UNUSED(context); } diff --git a/src/tools/selection/selectiontool.h b/src/tools/selection/selectiontool.h index af46d407..9b124b5c 100644 --- a/src/tools/selection/selectiontool.h +++ b/src/tools/selection/selectiontool.h @@ -19,24 +19,27 @@ #include "src/tools/abstracttwopointtool.h" -class SelectionTool : public AbstractTwoPointTool { - Q_OBJECT +class SelectionTool : public AbstractTwoPointTool +{ + Q_OBJECT public: - explicit SelectionTool(QObject *parent = nullptr); + explicit SelectionTool(QObject* parent = nullptr); - bool closeOnButtonPressed() const; + bool closeOnButtonPressed() const; - QIcon icon(const QColor &background, bool inEditor) const override; - QString name() const override; - static QString nameID(); - QString description() const override; + QIcon icon(const QColor& background, bool inEditor) const override; + QString name() const override; + static QString nameID(); + QString description() const override; - CaptureTool* copy(QObject *parent = nullptr) override; - void process( - QPainter &painter, const QPixmap &pixmap, bool recordUndo = false) override; - void paintMousePreview(QPainter &painter, const CaptureContext &context) override; + CaptureTool* copy(QObject* parent = nullptr) override; + void process(QPainter& painter, + const QPixmap& pixmap, + bool recordUndo = false) override; + void paintMousePreview(QPainter& painter, + const CaptureContext& context) override; public slots: - void drawStart(const CaptureContext &context) override; - void pressed(const CaptureContext &context) override; + void drawStart(const CaptureContext& context) override; + void pressed(const CaptureContext& context) override; }; diff --git a/src/tools/sizeindicator/sizeindicatortool.cpp b/src/tools/sizeindicator/sizeindicatortool.cpp index 3277a30f..bbb9ae01 100644 --- a/src/tools/sizeindicator/sizeindicatortool.cpp +++ b/src/tools/sizeindicator/sizeindicatortool.cpp @@ -18,34 +18,48 @@ #include "sizeindicatortool.h" #include -SizeIndicatorTool::SizeIndicatorTool(QObject *parent) : AbstractActionTool(parent) { +SizeIndicatorTool::SizeIndicatorTool(QObject* parent) + : AbstractActionTool(parent) +{} +bool +SizeIndicatorTool::closeOnButtonPressed() const +{ + return false; } -bool SizeIndicatorTool::closeOnButtonPressed() const { - return false; +QIcon +SizeIndicatorTool::icon(const QColor& background, bool inEditor) const +{ + return inEditor ? QIcon() + : QIcon(iconPath(background) + "size_indicator.svg"); +} +QString +SizeIndicatorTool::name() const +{ + return tr("Selection Size Indicator"); } -QIcon SizeIndicatorTool::icon(const QColor &background, bool inEditor) const { - return inEditor ? QIcon() : - QIcon(iconPath(background) + "size_indicator.svg"); -} -QString SizeIndicatorTool::name() const { - return tr("Selection Size Indicator"); +QString +SizeIndicatorTool::nameID() +{ + return QLatin1String(""); } -QString SizeIndicatorTool::nameID() { - return QLatin1String(""); +QString +SizeIndicatorTool::description() const +{ + return tr("Show the dimensions of the selection (X Y)"); } -QString SizeIndicatorTool::description() const { - return tr("Show the dimensions of the selection (X Y)"); +CaptureTool* +SizeIndicatorTool::copy(QObject* parent) +{ + return new SizeIndicatorTool(parent); } -CaptureTool* SizeIndicatorTool::copy(QObject *parent) { - return new SizeIndicatorTool(parent); -} - -void SizeIndicatorTool::pressed(const CaptureContext &context) { - Q_UNUSED(context); +void +SizeIndicatorTool::pressed(const CaptureContext& context) +{ + Q_UNUSED(context); } diff --git a/src/tools/sizeindicator/sizeindicatortool.h b/src/tools/sizeindicator/sizeindicatortool.h index 17dccb17..966d4f57 100644 --- a/src/tools/sizeindicator/sizeindicatortool.h +++ b/src/tools/sizeindicator/sizeindicatortool.h @@ -19,20 +19,21 @@ #include "src/tools/abstractactiontool.h" -class SizeIndicatorTool : public AbstractActionTool { - Q_OBJECT +class SizeIndicatorTool : public AbstractActionTool +{ + Q_OBJECT public: - explicit SizeIndicatorTool(QObject *parent = nullptr); + explicit SizeIndicatorTool(QObject* parent = nullptr); - bool closeOnButtonPressed() const; + bool closeOnButtonPressed() const; - QIcon icon(const QColor &background, bool inEditor) const override; - QString name() const override; - static QString nameID(); - QString description() const override; + QIcon icon(const QColor& background, bool inEditor) const override; + QString name() const override; + static QString nameID(); + QString description() const override; - CaptureTool* copy(QObject *parent = nullptr) override; + CaptureTool* copy(QObject* parent = nullptr) override; public slots: - void pressed(const CaptureContext &context) override; + void pressed(const CaptureContext& context) override; }; diff --git a/src/tools/text/textconfig.cpp b/src/tools/text/textconfig.cpp index f63b3069..2d096e55 100644 --- a/src/tools/text/textconfig.cpp +++ b/src/tools/text/textconfig.cpp @@ -18,86 +18,108 @@ #include "textconfig.h" #include "src/utils/colorutils.h" #include "src/utils/pathinfo.h" -#include #include -#include +#include #include #include +#include -TextConfig::TextConfig(QWidget *parent) : QWidget(parent) { - m_layout = new QVBoxLayout(this); +TextConfig::TextConfig(QWidget* parent) + : QWidget(parent) +{ + m_layout = new QVBoxLayout(this); - QFontDatabase fontDB; - QComboBox *fontsCB = new QComboBox(); - connect(fontsCB, &QComboBox::currentTextChanged, - this, &TextConfig::fontFamilyChanged); - fontsCB->addItems(fontDB.families()); - // TODO save family in config - int index = fontsCB->findText(font().family()); - fontsCB->setCurrentIndex(index); + QFontDatabase fontDB; + QComboBox* fontsCB = new QComboBox(); + connect(fontsCB, + &QComboBox::currentTextChanged, + this, + &TextConfig::fontFamilyChanged); + fontsCB->addItems(fontDB.families()); + // TODO save family in config + int index = fontsCB->findText(font().family()); + fontsCB->setCurrentIndex(index); - QColor bgColor(palette().windowText().color()); - QString iconPrefix = ColorUtils::colorIsDark(bgColor) ? - PathInfo::whiteIconPath() : - PathInfo::blackIconPath(); + QColor bgColor(palette().windowText().color()); + QString iconPrefix = ColorUtils::colorIsDark(bgColor) + ? PathInfo::whiteIconPath() + : PathInfo::blackIconPath(); - m_strikeOutButton = new QPushButton( - QIcon(iconPrefix + "format_strikethrough.svg"), QLatin1String("")); - m_strikeOutButton->setCheckable(true); - connect(m_strikeOutButton, &QPushButton::clicked, - this, &TextConfig::fontStrikeOutChanged); - m_strikeOutButton->setToolTip(tr("StrikeOut")); + m_strikeOutButton = new QPushButton( + QIcon(iconPrefix + "format_strikethrough.svg"), QLatin1String("")); + m_strikeOutButton->setCheckable(true); + connect(m_strikeOutButton, + &QPushButton::clicked, + this, + &TextConfig::fontStrikeOutChanged); + m_strikeOutButton->setToolTip(tr("StrikeOut")); - m_underlineButton = new QPushButton( - QIcon(iconPrefix + "format_underlined.svg"), QLatin1String("")); - m_underlineButton->setCheckable(true); - connect(m_underlineButton, &QPushButton::clicked, - this, &TextConfig::fontUnderlineChanged); - m_underlineButton->setToolTip(tr("Underline")); + m_underlineButton = new QPushButton( + QIcon(iconPrefix + "format_underlined.svg"), QLatin1String("")); + m_underlineButton->setCheckable(true); + connect(m_underlineButton, + &QPushButton::clicked, + this, + &TextConfig::fontUnderlineChanged); + m_underlineButton->setToolTip(tr("Underline")); - m_weightButton = new QPushButton( - QIcon(iconPrefix + "format_bold.svg"), QLatin1String("")); - m_weightButton->setCheckable(true); - connect(m_weightButton, &QPushButton::clicked, - this, &TextConfig::weightButtonPressed); - m_weightButton->setToolTip(tr("Bold")); + m_weightButton = + new QPushButton(QIcon(iconPrefix + "format_bold.svg"), QLatin1String("")); + m_weightButton->setCheckable(true); + connect(m_weightButton, + &QPushButton::clicked, + this, + &TextConfig::weightButtonPressed); + m_weightButton->setToolTip(tr("Bold")); - m_italicButton = new QPushButton( - QIcon(iconPrefix + "format_italic.svg"), QLatin1String("")); - m_italicButton->setCheckable(true); - connect(m_italicButton, &QPushButton::clicked, - this, &TextConfig::fontItalicChanged); - m_italicButton->setToolTip(tr("Italic")); - QHBoxLayout *modifiersLayout = new QHBoxLayout(); + m_italicButton = + new QPushButton(QIcon(iconPrefix + "format_italic.svg"), QLatin1String("")); + m_italicButton->setCheckable(true); + connect(m_italicButton, + &QPushButton::clicked, + this, + &TextConfig::fontItalicChanged); + m_italicButton->setToolTip(tr("Italic")); + QHBoxLayout* modifiersLayout = new QHBoxLayout(); - m_layout->addWidget(fontsCB); - modifiersLayout->addWidget(m_strikeOutButton); - modifiersLayout->addWidget(m_underlineButton); - modifiersLayout->addWidget(m_weightButton); - modifiersLayout->addWidget(m_italicButton); - m_layout->addLayout(modifiersLayout); + m_layout->addWidget(fontsCB); + modifiersLayout->addWidget(m_strikeOutButton); + modifiersLayout->addWidget(m_underlineButton); + modifiersLayout->addWidget(m_weightButton); + modifiersLayout->addWidget(m_italicButton); + m_layout->addLayout(modifiersLayout); } -void TextConfig::setUnderline(const bool u) { - m_underlineButton->setChecked(u); +void +TextConfig::setUnderline(const bool u) +{ + m_underlineButton->setChecked(u); } -void TextConfig::setStrikeOut(const bool s) { - m_strikeOutButton->setChecked(s); +void +TextConfig::setStrikeOut(const bool s) +{ + m_strikeOutButton->setChecked(s); } -void TextConfig::setWeight(const int w) { - m_weightButton->setChecked(static_cast(w) == QFont::Bold); +void +TextConfig::setWeight(const int w) +{ + m_weightButton->setChecked(static_cast(w) == QFont::Bold); } -void TextConfig::setItalic(const bool i) { - m_italicButton->setChecked(i); +void +TextConfig::setItalic(const bool i) +{ + m_italicButton->setChecked(i); } -void TextConfig::weightButtonPressed(const bool w) { - if (w) { - emit fontWeightChanged(QFont::Bold); - } else { - emit fontWeightChanged(QFont::Normal); - } +void +TextConfig::weightButtonPressed(const bool w) +{ + if (w) { + emit fontWeightChanged(QFont::Bold); + } else { + emit fontWeightChanged(QFont::Normal); + } } diff --git a/src/tools/text/textconfig.h b/src/tools/text/textconfig.h index 13053265..2d4ed72a 100644 --- a/src/tools/text/textconfig.h +++ b/src/tools/text/textconfig.h @@ -22,32 +22,33 @@ class QVBoxLayout; class QPushButton; -class TextConfig : public QWidget { - Q_OBJECT +class TextConfig : public QWidget +{ + Q_OBJECT public: - explicit TextConfig(QWidget *parent = nullptr); + explicit TextConfig(QWidget* parent = nullptr); - void setUnderline(const bool u); - void setStrikeOut(const bool s); - void setWeight(const int w); - void setItalic(const bool i); + void setUnderline(const bool u); + void setStrikeOut(const bool s); + void setWeight(const int w); + void setItalic(const bool i); signals: - void fontFamilyChanged(const QString &f); - void fontUnderlineChanged(const bool underlined); - void fontStrikeOutChanged(const bool dashed); - void fontWeightChanged(const QFont::Weight w); - void fontItalicChanged(const bool italic); + void fontFamilyChanged(const QString& f); + void fontUnderlineChanged(const bool underlined); + void fontStrikeOutChanged(const bool dashed); + void fontWeightChanged(const QFont::Weight w); + void fontItalicChanged(const bool italic); public slots: private slots: - void weightButtonPressed(const bool w); + void weightButtonPressed(const bool w); private: - QVBoxLayout *m_layout; - QPushButton *m_strikeOutButton; - QPushButton *m_underlineButton; - QPushButton *m_weightButton; - QPushButton *m_italicButton; + QVBoxLayout* m_layout; + QPushButton* m_strikeOutButton; + QPushButton* m_underlineButton; + QPushButton* m_weightButton; + QPushButton* m_italicButton; }; diff --git a/src/tools/text/texttool.cpp b/src/tools/text/texttool.cpp index 0ee93b5c..153deab4 100644 --- a/src/tools/text/texttool.cpp +++ b/src/tools/text/texttool.cpp @@ -16,195 +16,256 @@ // along with Flameshot. If not, see . #include "texttool.h" -#include "textwidget.h" #include "textconfig.h" +#include "textwidget.h" #define BASE_POINT_SIZE 8 +TextTool::TextTool(QObject* parent) + : CaptureTool(parent) + , m_size(1) +{} -TextTool::TextTool(QObject *parent) : CaptureTool(parent), m_size(1) { +bool +TextTool::isValid() const +{ + return !m_text.isEmpty(); } -bool TextTool::isValid() const { - return !m_text.isEmpty(); +bool +TextTool::closeOnButtonPressed() const +{ + return false; } -bool TextTool::closeOnButtonPressed() const { - return false; +bool +TextTool::isSelectable() const +{ + return true; } -bool TextTool::isSelectable() const { - return true; +bool +TextTool::showMousePreview() const +{ + return false; } -bool TextTool::showMousePreview() const { - return false; +QIcon +TextTool::icon(const QColor& background, bool inEditor) const +{ + Q_UNUSED(inEditor); + return QIcon(iconPath(background) + "text.svg"); } -QIcon TextTool::icon(const QColor &background, bool inEditor) const { - Q_UNUSED(inEditor); - return QIcon(iconPath(background) + "text.svg"); +QString +TextTool::name() const +{ + return tr("Text"); } -QString TextTool::name() const { - return tr("Text"); +QString +TextTool::nameID() +{ + return QLatin1String(""); } -QString TextTool::nameID() { - return QLatin1String(""); +QString +TextTool::description() const +{ + return tr("Add text to your capture"); } -QString TextTool::description() const { - return tr("Add text to your capture"); +QWidget* +TextTool::widget() +{ + TextWidget* w = new TextWidget(); + w->setTextColor(m_color); + m_font.setPointSize(m_size + BASE_POINT_SIZE); + w->setFont(m_font); + connect(w, &TextWidget::textUpdated, this, &TextTool::updateText); + m_widget = w; + return w; } -QWidget *TextTool::widget() { - TextWidget *w = new TextWidget(); - w->setTextColor(m_color); - m_font.setPointSize(m_size + BASE_POINT_SIZE); - w->setFont(m_font); - connect(w, &TextWidget::textUpdated, - this, &TextTool::updateText); - m_widget = w; - return w; +QWidget* +TextTool::configurationWidget() +{ + m_confW = new TextConfig(); + connect( + m_confW, &TextConfig::fontFamilyChanged, this, &TextTool::updateFamily); + connect( + m_confW, &TextConfig::fontItalicChanged, this, &TextTool::updateFontItalic); + connect(m_confW, + &TextConfig::fontStrikeOutChanged, + this, + &TextTool::updateFontStrikeOut); + connect(m_confW, + &TextConfig::fontUnderlineChanged, + this, + &TextTool::updateFontUnderline); + connect( + m_confW, &TextConfig::fontWeightChanged, this, &TextTool::updateFontWeight); + m_confW->setItalic(m_font.italic()); + m_confW->setUnderline(m_font.underline()); + m_confW->setStrikeOut(m_font.strikeOut()); + m_confW->setWeight(m_font.weight()); + return m_confW; } -QWidget *TextTool::configurationWidget() { - m_confW = new TextConfig(); - connect(m_confW, &TextConfig::fontFamilyChanged, - this, &TextTool::updateFamily); - connect(m_confW, &TextConfig::fontItalicChanged, - this, &TextTool::updateFontItalic); - connect(m_confW, &TextConfig::fontStrikeOutChanged, - this, &TextTool::updateFontStrikeOut); - connect(m_confW, &TextConfig::fontUnderlineChanged, - this, &TextTool::updateFontUnderline); - connect(m_confW, &TextConfig::fontWeightChanged, - this, &TextTool::updateFontWeight); - m_confW->setItalic(m_font.italic()); - m_confW->setUnderline(m_font.underline()); - m_confW->setStrikeOut(m_font.strikeOut()); - m_confW->setWeight(m_font.weight()); - return m_confW; +CaptureTool* +TextTool::copy(QObject* parent) +{ + TextTool* tt = new TextTool(parent); + connect(m_confW, &TextConfig::fontFamilyChanged, tt, &TextTool::updateFamily); + connect( + m_confW, &TextConfig::fontItalicChanged, tt, &TextTool::updateFontItalic); + connect(m_confW, + &TextConfig::fontStrikeOutChanged, + tt, + &TextTool::updateFontStrikeOut); + connect(m_confW, + &TextConfig::fontUnderlineChanged, + tt, + &TextTool::updateFontUnderline); + connect( + m_confW, &TextConfig::fontWeightChanged, tt, &TextTool::updateFontWeight); + tt->m_font = m_font; + return tt; } -CaptureTool *TextTool::copy(QObject *parent) { - TextTool *tt = new TextTool(parent); - connect(m_confW, &TextConfig::fontFamilyChanged, - tt, &TextTool::updateFamily); - connect(m_confW, &TextConfig::fontItalicChanged, - tt, &TextTool::updateFontItalic); - connect(m_confW, &TextConfig::fontStrikeOutChanged, - tt, &TextTool::updateFontStrikeOut); - connect(m_confW, &TextConfig::fontUnderlineChanged, - tt, &TextTool::updateFontUnderline); - connect(m_confW, &TextConfig::fontWeightChanged, - tt, &TextTool::updateFontWeight); - tt->m_font = m_font; - return tt; +void +TextTool::undo(QPixmap& pixmap) +{ + QPainter p(&pixmap); + p.drawPixmap(m_backupArea.topLeft(), m_pixmapBackup); } -void TextTool::undo(QPixmap &pixmap) { - QPainter p(&pixmap); - p.drawPixmap(m_backupArea.topLeft(), m_pixmapBackup); +void +TextTool::process(QPainter& painter, const QPixmap& pixmap, bool recordUndo) +{ + if (m_text.isEmpty()) { + return; + } + QFontMetrics fm(m_font); + QSize size(fm.boundingRect(QRect(), 0, m_text).size()); + m_backupArea.setSize(size); + if (recordUndo) { + m_pixmapBackup = pixmap.copy(m_backupArea + QMargins(0, 0, 5, 5)); + } + // draw text + painter.setFont(m_font); + painter.setPen(m_color); + painter.drawText(m_backupArea + QMargins(-5, -5, 5, 5), m_text); } -void TextTool::process(QPainter &painter, const QPixmap &pixmap, bool recordUndo) { - if (m_text.isEmpty()) { - return; - } - QFontMetrics fm(m_font); - QSize size(fm.boundingRect(QRect(), 0, m_text).size()); - m_backupArea.setSize(size); - if (recordUndo) { - m_pixmapBackup = pixmap.copy(m_backupArea + QMargins(0, 0, 5, 5)); - } - // draw text - painter.setFont(m_font); - painter.setPen(m_color); - painter.drawText(m_backupArea + QMargins(-5, -5, 5, 5), m_text); +void +TextTool::paintMousePreview(QPainter& painter, const CaptureContext& context) +{ + Q_UNUSED(painter); + Q_UNUSED(context); } -void TextTool::paintMousePreview(QPainter &painter, const CaptureContext &context) { - Q_UNUSED(painter); - Q_UNUSED(context); +void +TextTool::drawEnd(const QPoint& p) +{ + m_backupArea.moveTo(p); } -void TextTool::drawEnd(const QPoint &p) { - m_backupArea.moveTo(p); +void +TextTool::drawMove(const QPoint& p) +{ + m_widget->move(p); } -void TextTool::drawMove(const QPoint &p) { - m_widget->move(p); +void +TextTool::drawStart(const CaptureContext& context) +{ + m_color = context.color; + m_size = context.thickness; + emit requestAction(REQ_ADD_CHILD_WIDGET); } -void TextTool::drawStart(const CaptureContext &context) { - m_color = context.color; - m_size = context.thickness; - emit requestAction(REQ_ADD_CHILD_WIDGET); +void +TextTool::pressed(const CaptureContext& context) +{ + Q_UNUSED(context); } -void TextTool::pressed(const CaptureContext &context) { - Q_UNUSED(context); +void +TextTool::colorChanged(const QColor& c) +{ + m_color = c; + if (m_widget) { + m_widget->setTextColor(c); + } } -void TextTool::colorChanged(const QColor &c) { - m_color = c; - if (m_widget) { - m_widget->setTextColor(c); - } +void +TextTool::thicknessChanged(const int th) +{ + m_size = th; + m_font.setPointSize(m_size + BASE_POINT_SIZE); + if (m_widget) { + m_widget->setFont(m_font); + } } -void TextTool::thicknessChanged(const int th) { - m_size = th; - m_font.setPointSize(m_size + BASE_POINT_SIZE); - if (m_widget) { - m_widget->setFont(m_font); - } +void +TextTool::updateText(const QString& s) +{ + m_text = s; } -void TextTool::updateText(const QString &s) { - m_text = s; +void +TextTool::setFont(const QFont& f) +{ + m_font = f; + if (m_widget) { + m_widget->setFont(f); + } } -void TextTool::setFont(const QFont &f) { - m_font = f; - if (m_widget) { - m_widget->setFont(f); - } +void +TextTool::updateFamily(const QString& s) +{ + m_font.setFamily(s); + if (m_widget) { + m_widget->setFont(m_font); + } } -void TextTool::updateFamily(const QString &s) { - m_font.setFamily(s); - if (m_widget) { - m_widget->setFont(m_font); - } +void +TextTool::updateFontUnderline(const bool underlined) +{ + m_font.setUnderline(underlined); + if (m_widget) { + m_widget->setFont(m_font); + } } -void TextTool::updateFontUnderline(const bool underlined) { - m_font.setUnderline(underlined); - if (m_widget) { - m_widget->setFont(m_font); - } +void +TextTool::updateFontStrikeOut(const bool s) +{ + m_font.setStrikeOut(s); + if (m_widget) { + m_widget->setFont(m_font); + } } -void TextTool::updateFontStrikeOut(const bool s) { - m_font.setStrikeOut(s); - if (m_widget) { - m_widget->setFont(m_font); - } +void +TextTool::updateFontWeight(const QFont::Weight w) +{ + m_font.setWeight(w); + if (m_widget) { + m_widget->setFont(m_font); + } } -void TextTool::updateFontWeight(const QFont::Weight w) { - m_font.setWeight(w); - if (m_widget) { - m_widget->setFont(m_font); - } -} - -void TextTool::updateFontItalic(const bool italic) { - m_font.setItalic(italic); - if (m_widget) { - m_widget->setFont(m_font); - } +void +TextTool::updateFontItalic(const bool italic) +{ + m_font.setItalic(italic); + if (m_widget) { + m_widget->setFont(m_font); + } } diff --git a/src/tools/text/texttool.h b/src/tools/text/texttool.h index b454daaf..29330888 100644 --- a/src/tools/text/texttool.h +++ b/src/tools/text/texttool.h @@ -23,55 +23,57 @@ class TextWidget; class TextConfig; -class TextTool : public CaptureTool { - Q_OBJECT +class TextTool : public CaptureTool +{ + Q_OBJECT public: - explicit TextTool(QObject *parent = nullptr); + explicit TextTool(QObject* parent = nullptr); - bool isValid() const override; - bool closeOnButtonPressed() const override; - bool isSelectable() const override; - bool showMousePreview() const override; + bool isValid() const override; + bool closeOnButtonPressed() const override; + bool isSelectable() const override; + bool showMousePreview() const override; - QIcon icon(const QColor &background, - bool inEditor) const override; - QString name() const override; - static QString nameID(); - QString description() const override; + QIcon icon(const QColor& background, bool inEditor) const override; + QString name() const override; + static QString nameID(); + QString description() const override; - QWidget* widget() override; - QWidget* configurationWidget() override; - CaptureTool* copy(QObject *parent = nullptr) override; + QWidget* widget() override; + QWidget* configurationWidget() override; + CaptureTool* copy(QObject* parent = nullptr) override; - void undo(QPixmap &pixmap) override; - void process( - QPainter &painter, const QPixmap &pixmap, bool recordUndo = false) override; - void paintMousePreview(QPainter &painter, const CaptureContext &context) override; + void undo(QPixmap& pixmap) override; + void process(QPainter& painter, + const QPixmap& pixmap, + bool recordUndo = false) override; + void paintMousePreview(QPainter& painter, + const CaptureContext& context) override; public slots: - void drawEnd(const QPoint &p) override; - void drawMove(const QPoint &p) override; - void drawStart(const CaptureContext &context) override; - void pressed(const CaptureContext &context) override; - void colorChanged(const QColor &c) override; - void thicknessChanged(const int th) override; + void drawEnd(const QPoint& p) override; + void drawMove(const QPoint& p) override; + void drawStart(const CaptureContext& context) override; + void pressed(const CaptureContext& context) override; + void colorChanged(const QColor& c) override; + void thicknessChanged(const int th) override; private slots: - void updateText(const QString &s); - void setFont(const QFont &f); - void updateFamily(const QString &s); - void updateFontUnderline(const bool underlined); - void updateFontStrikeOut(const bool s); - void updateFontWeight(const QFont::Weight w); - void updateFontItalic(const bool italic); + void updateText(const QString& s); + void setFont(const QFont& f); + void updateFamily(const QString& s); + void updateFontUnderline(const bool underlined); + void updateFontStrikeOut(const bool s); + void updateFontWeight(const QFont::Weight w); + void updateFontItalic(const bool italic); private: - QFont m_font; - QString m_text; - int m_size; - QColor m_color; - QPixmap m_pixmapBackup; - QRect m_backupArea; - QPointer m_widget; - QPointer m_confW; + QFont m_font; + QString m_text; + int m_size; + QColor m_color; + QPixmap m_pixmapBackup; + QRect m_backupArea; + QPointer m_widget; + QPointer m_confW; }; diff --git a/src/tools/text/textwidget.cpp b/src/tools/text/textwidget.cpp index 78586342..1edb8317 100644 --- a/src/tools/text/textwidget.cpp +++ b/src/tools/text/textwidget.cpp @@ -17,71 +17,88 @@ #include "textwidget.h" -TextWidget::TextWidget(QWidget *parent) : QTextEdit(parent) { - setStyleSheet(QStringLiteral("TextWidget { background: transparent; }")); - connect(this, &TextWidget::textChanged, - this, &TextWidget::adjustSize); - connect(this, &TextWidget::textChanged, - this, &TextWidget::emitTextUpdated); - setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); - setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); - setContextMenuPolicy(Qt::NoContextMenu); +TextWidget::TextWidget(QWidget* parent) + : QTextEdit(parent) +{ + setStyleSheet(QStringLiteral("TextWidget { background: transparent; }")); + connect(this, &TextWidget::textChanged, this, &TextWidget::adjustSize); + connect(this, &TextWidget::textChanged, this, &TextWidget::emitTextUpdated); + setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff); + setContextMenuPolicy(Qt::NoContextMenu); } -void TextWidget::showEvent(QShowEvent *e) { - QFont font; - QFontMetrics fm(font); - setFixedWidth(fm.lineSpacing() *6); - setFixedHeight(fm.lineSpacing() * 2.5); - m_baseSize = size(); - m_minSize = m_baseSize; - QTextEdit::showEvent(e); - adjustSize(); +void +TextWidget::showEvent(QShowEvent* e) +{ + QFont font; + QFontMetrics fm(font); + setFixedWidth(fm.lineSpacing() * 6); + setFixedHeight(fm.lineSpacing() * 2.5); + m_baseSize = size(); + m_minSize = m_baseSize; + QTextEdit::showEvent(e); + adjustSize(); } -void TextWidget::resizeEvent(QResizeEvent *e) { - m_minSize.setHeight(qMin(m_baseSize.height(), height())); - m_minSize.setWidth(qMin(m_baseSize.width(), width())); - QTextEdit::resizeEvent(e); +void +TextWidget::resizeEvent(QResizeEvent* e) +{ + m_minSize.setHeight(qMin(m_baseSize.height(), height())); + m_minSize.setWidth(qMin(m_baseSize.width(), width())); + QTextEdit::resizeEvent(e); } -void TextWidget::setFont(const QFont &f) { - QTextEdit::setFont(f); - adjustSize(); +void +TextWidget::setFont(const QFont& f) +{ + QTextEdit::setFont(f); + adjustSize(); } -void TextWidget::updateFont(const QFont &f) { - setFont(f); +void +TextWidget::updateFont(const QFont& f) +{ + setFont(f); } -void TextWidget::setFontPointSize(qreal s) { - QFont f = font(); - f.setPointSize(s); - setFont(f); +void +TextWidget::setFontPointSize(qreal s) +{ + QFont f = font(); + f.setPointSize(s); + setFont(f); } -void TextWidget::setTextColor(const QColor &c) { - QString s(QStringLiteral("TextWidget { background: transparent; color: %1; }")); - setStyleSheet(s.arg(c.name())); +void +TextWidget::setTextColor(const QColor& c) +{ + QString s( + QStringLiteral("TextWidget { background: transparent; color: %1; }")); + setStyleSheet(s.arg(c.name())); } -void TextWidget::adjustSize() { - QString &&text = this->toPlainText(); +void +TextWidget::adjustSize() +{ + QString&& text = this->toPlainText(); - QFontMetrics fm(font()); - QRect bounds = fm.boundingRect(QRect(), 0, text); - int pixelsWide = bounds.width() + fm.lineSpacing(); - int pixelsHigh = bounds.height() * 1.15 + fm.lineSpacing(); - if (pixelsWide < m_minSize.width()) { - pixelsWide = m_minSize.width(); - } - if (pixelsHigh < m_minSize.height()) { - pixelsHigh = m_minSize.height(); - } + QFontMetrics fm(font()); + QRect bounds = fm.boundingRect(QRect(), 0, text); + int pixelsWide = bounds.width() + fm.lineSpacing(); + int pixelsHigh = bounds.height() * 1.15 + fm.lineSpacing(); + if (pixelsWide < m_minSize.width()) { + pixelsWide = m_minSize.width(); + } + if (pixelsHigh < m_minSize.height()) { + pixelsHigh = m_minSize.height(); + } - this->setFixedSize(pixelsWide, pixelsHigh); + this->setFixedSize(pixelsWide, pixelsHigh); } -void TextWidget::emitTextUpdated() { - emit textUpdated(this->toPlainText()); +void +TextWidget::emitTextUpdated() +{ + emit textUpdated(this->toPlainText()); } diff --git a/src/tools/text/textwidget.h b/src/tools/text/textwidget.h index 6d947656..d3f2c9a1 100644 --- a/src/tools/text/textwidget.h +++ b/src/tools/text/textwidget.h @@ -21,29 +21,29 @@ class TextWidget : public QTextEdit { - Q_OBJECT + Q_OBJECT public: - explicit TextWidget(QWidget *parent = nullptr); + explicit TextWidget(QWidget* parent = nullptr); - void adjustSize(); - void setFont(const QFont &f); + void adjustSize(); + void setFont(const QFont& f); protected: - void showEvent(QShowEvent *e); - void resizeEvent(QResizeEvent *e); + void showEvent(QShowEvent* e); + void resizeEvent(QResizeEvent* e); signals: - void textUpdated(const QString &s); + void textUpdated(const QString& s); public slots: - void updateFont(const QFont &f); - void setTextColor(const QColor &c); - void setFontPointSize(qreal s); + void updateFont(const QFont& f); + void setTextColor(const QColor& c); + void setFontPointSize(qreal s); private slots: - void emitTextUpdated(); + void emitTextUpdated(); private: - QSize m_baseSize; - QSize m_minSize; + QSize m_baseSize; + QSize m_minSize; }; diff --git a/src/tools/toolfactory.cpp b/src/tools/toolfactory.cpp index 588df1b1..baac071e 100644 --- a/src/tools/toolfactory.cpp +++ b/src/tools/toolfactory.cpp @@ -17,100 +17,99 @@ #include "toolfactory.h" #include "arrow/arrowtool.h" +#include "blur/blurtool.h" #include "circle/circletool.h" #include "circlecount/circlecounttool.h" #include "copy/copytool.h" #include "exit/exittool.h" #include "imgur/imguruploadertool.h" +#include "launcher/applaunchertool.h" #include "line/linetool.h" #include "marker/markertool.h" #include "move/movetool.h" #include "pencil/penciltool.h" +#include "pin/pintool.h" #include "rectangle/rectangletool.h" +#include "redo/redotool.h" #include "save/savetool.h" #include "selection/selectiontool.h" #include "sizeindicator/sizeindicatortool.h" -#include "undo/undotool.h" -#include "launcher/applaunchertool.h" -#include "blur/blurtool.h" -#include "redo/redotool.h" -#include "pin/pintool.h" #include "text/texttool.h" +#include "undo/undotool.h" -ToolFactory::ToolFactory(QObject *parent) : QObject(parent) { +ToolFactory::ToolFactory(QObject* parent) + : QObject(parent) +{} -} - -CaptureTool* ToolFactory::CreateTool( - CaptureButton::ButtonType t, - QObject *parent) +CaptureTool* +ToolFactory::CreateTool(CaptureButton::ButtonType t, QObject* parent) { - CaptureTool *tool; - switch (t) { + CaptureTool* tool; + switch (t) { case CaptureButton::TYPE_ARROW: - tool = new ArrowTool(parent); - break; + tool = new ArrowTool(parent); + break; case CaptureButton::TYPE_CIRCLE: - tool = new CircleTool(parent); - break; + tool = new CircleTool(parent); + break; case CaptureButton::TYPE_COPY: - tool = new CopyTool(parent); - break; + tool = new CopyTool(parent); + break; case CaptureButton::TYPE_EXIT: - tool = new ExitTool(parent); - break; + tool = new ExitTool(parent); + break; case CaptureButton::TYPE_IMAGEUPLOADER: - tool = new ImgurUploaderTool(parent); - break; + tool = new ImgurUploaderTool(parent); + break; case CaptureButton::TYPE_DRAWER: - tool = new LineTool(parent); - break; + tool = new LineTool(parent); + break; case CaptureButton::TYPE_MARKER: - tool = new MarkerTool(parent); - break; + tool = new MarkerTool(parent); + break; case CaptureButton::TYPE_MOVESELECTION: - tool = new MoveTool(parent); - break; + tool = new MoveTool(parent); + break; case CaptureButton::TYPE_PENCIL: - tool = new PencilTool(parent); - break; + tool = new PencilTool(parent); + break; case CaptureButton::TYPE_RECTANGLE: - tool = new RectangleTool(parent); - break; + tool = new RectangleTool(parent); + break; case CaptureButton::TYPE_SAVE: - tool = new SaveTool(parent); - break; + tool = new SaveTool(parent); + break; case CaptureButton::TYPE_SELECTION: - tool = new SelectionTool(parent); - break; + tool = new SelectionTool(parent); + break; case CaptureButton::TYPE_SELECTIONINDICATOR: - tool = new SizeIndicatorTool(parent); - break; + tool = new SizeIndicatorTool(parent); + break; case CaptureButton::TYPE_UNDO: - tool = new UndoTool(parent); - break; + tool = new UndoTool(parent); + break; case CaptureButton::TYPE_REDO: - tool = new RedoTool(parent); - break; + tool = new RedoTool(parent); + break; case CaptureButton::TYPE_OPEN_APP: - tool = new AppLauncher(parent); - break; + tool = new AppLauncher(parent); + break; case CaptureButton::TYPE_BLUR: - tool = new BlurTool(parent); - break; + tool = new BlurTool(parent); + break; case CaptureButton::TYPE_PIN: - tool = new PinTool(parent); - break; + tool = new PinTool(parent); + break; case CaptureButton::TYPE_TEXT: - tool = new TextTool(parent); - break; + tool = new TextTool(parent); + break; case CaptureButton::TYPE_CIRCLECOUNT: - tool = new CircleCountTool(parent); - break; + tool = new CircleCountTool(parent); + break; default: - tool = nullptr; - break; - } - return tool; + tool = nullptr; + break; + } + return tool; } diff --git a/src/tools/toolfactory.h b/src/tools/toolfactory.h index 5ceaa224..6ccff1e1 100644 --- a/src/tools/toolfactory.h +++ b/src/tools/toolfactory.h @@ -17,23 +17,22 @@ #pragma once -#include "src/widgets/capture/capturebutton.h" #include "src/tools/capturetool.h" +#include "src/widgets/capture/capturebutton.h" #include class CaptureTool; -class ToolFactory : public QObject { - Q_OBJECT +class ToolFactory : public QObject +{ + Q_OBJECT public: + explicit ToolFactory(QObject* parent = nullptr); - explicit ToolFactory(QObject *parent = nullptr); + ToolFactory(const ToolFactory&) = delete; + ToolFactory& operator=(const ToolFactory&) = delete; - ToolFactory(const ToolFactory &) = delete; - ToolFactory & operator=(const ToolFactory &) = delete; - - CaptureTool* CreateTool( - CaptureButton::ButtonType t, - QObject *parent = nullptr); + CaptureTool* CreateTool(CaptureButton::ButtonType t, + QObject* parent = nullptr); }; diff --git a/src/tools/undo/undotool.cpp b/src/tools/undo/undotool.cpp index c17c6f45..9dde045f 100644 --- a/src/tools/undo/undotool.cpp +++ b/src/tools/undo/undotool.cpp @@ -18,35 +18,49 @@ #include "undotool.h" #include -UndoTool::UndoTool(QObject *parent) : AbstractActionTool(parent) { +UndoTool::UndoTool(QObject* parent) + : AbstractActionTool(parent) +{} +bool +UndoTool::closeOnButtonPressed() const +{ + return false; } -bool UndoTool::closeOnButtonPressed() const { - return false; +QIcon +UndoTool::icon(const QColor& background, bool inEditor) const +{ + Q_UNUSED(inEditor); + return QIcon(iconPath(background) + "undo-variant.svg"); +} +QString +UndoTool::name() const +{ + return tr("Undo"); } -QIcon UndoTool::icon(const QColor &background, bool inEditor) const { - Q_UNUSED(inEditor); - return QIcon(iconPath(background) + "undo-variant.svg"); -} -QString UndoTool::name() const { - return tr("Undo"); +QString +UndoTool::nameID() +{ + return QLatin1String(""); } -QString UndoTool::nameID() { - return QLatin1String(""); +QString +UndoTool::description() const +{ + return tr("Undo the last modification"); } -QString UndoTool::description() const { - return tr("Undo the last modification"); +CaptureTool* +UndoTool::copy(QObject* parent) +{ + return new UndoTool(parent); } -CaptureTool* UndoTool::copy(QObject *parent) { - return new UndoTool(parent); -} - -void UndoTool::pressed(const CaptureContext &context) { - Q_UNUSED(context); - emit requestAction(REQ_UNDO_MODIFICATION); +void +UndoTool::pressed(const CaptureContext& context) +{ + Q_UNUSED(context); + emit requestAction(REQ_UNDO_MODIFICATION); } diff --git a/src/tools/undo/undotool.h b/src/tools/undo/undotool.h index fae4e6ab..6aa3b983 100644 --- a/src/tools/undo/undotool.h +++ b/src/tools/undo/undotool.h @@ -19,21 +19,21 @@ #include "src/tools/abstractactiontool.h" -class UndoTool : public AbstractActionTool { - Q_OBJECT +class UndoTool : public AbstractActionTool +{ + Q_OBJECT public: - explicit UndoTool(QObject *parent = nullptr); + explicit UndoTool(QObject* parent = nullptr); - bool closeOnButtonPressed() const; + bool closeOnButtonPressed() const; - QIcon icon(const QColor &background, bool inEditor) const override; - QString name() const override; - static QString nameID(); - QString description() const override; + QIcon icon(const QColor& background, bool inEditor) const override; + QString name() const override; + static QString nameID(); + QString description() const override; - CaptureTool* copy(QObject *parent = nullptr) override; + CaptureTool* copy(QObject* parent = nullptr) override; public slots: - void pressed(const CaptureContext &context) override; - + void pressed(const CaptureContext& context) override; }; diff --git a/src/utils/colorutils.cpp b/src/utils/colorutils.cpp index 3af02ddc..febf3b4e 100644 --- a/src/utils/colorutils.cpp +++ b/src/utils/colorutils.cpp @@ -17,23 +17,28 @@ #include "colorutils.h" -inline qreal getColorLuma(const QColor &c) { - return 0.30 * c.redF() + 0.59 * c.greenF() + 0.11 * c.blueF(); +inline qreal +getColorLuma(const QColor& c) +{ + return 0.30 * c.redF() + 0.59 * c.greenF() + 0.11 * c.blueF(); } -bool ColorUtils::colorIsDark(const QColor &c) { - bool isWhite = false; - if (getColorLuma(c) <= 0.60) { - isWhite = true; - } - return isWhite; +bool +ColorUtils::colorIsDark(const QColor& c) +{ + bool isWhite = false; + if (getColorLuma(c) <= 0.60) { + isWhite = true; + } + return isWhite; } -QColor ColorUtils::contrastColor(const QColor &c) { - int change = colorIsDark(c) ? 30 : -45; +QColor +ColorUtils::contrastColor(const QColor& c) +{ + int change = colorIsDark(c) ? 30 : -45; - return QColor(qBound(0, c.red() + change, 255), - qBound(0, c.green() + change, 255), - qBound(0, c.blue() + change, 255)); + return QColor(qBound(0, c.red() + change, 255), + qBound(0, c.green() + change, 255), + qBound(0, c.blue() + change, 255)); } - diff --git a/src/utils/colorutils.h b/src/utils/colorutils.h index bb6d20aa..f587e7ad 100644 --- a/src/utils/colorutils.h +++ b/src/utils/colorutils.h @@ -21,8 +21,10 @@ namespace ColorUtils { // namespace -bool colorIsDark(const QColor &c); +bool +colorIsDark(const QColor& c); -QColor contrastColor(const QColor &c); +QColor +contrastColor(const QColor& c); } // namespace diff --git a/src/utils/confighandler.cpp b/src/utils/confighandler.cpp index 15c4194b..a7cf6631 100644 --- a/src/utils/confighandler.cpp +++ b/src/utils/confighandler.cpp @@ -16,372 +16,438 @@ // along with Flameshot. If not, see . #include "confighandler.h" -#include -#include -#include #include +#include +#include +#include -ConfigHandler::ConfigHandler(){ - m_settings.setDefaultFormat(QSettings::IniFormat); +ConfigHandler::ConfigHandler() +{ + m_settings.setDefaultFormat(QSettings::IniFormat); } -QVector ConfigHandler::getButtons() { - QVector buttons; - if (m_settings.contains(QStringLiteral("buttons"))) { - // TODO: remove toList in v1.0 - QVector buttonsInt = - m_settings.value(QStringLiteral("buttons")).value >().toVector(); - bool modified = normalizeButtons(buttonsInt); - if (modified) { - m_settings.setValue(QStringLiteral("buttons"), QVariant::fromValue(buttonsInt.toList())); - } - buttons = fromIntToButton(buttonsInt); - } else { - // Default tools - buttons << CaptureButton::TYPE_PENCIL - << CaptureButton::TYPE_DRAWER - << CaptureButton::TYPE_ARROW - << CaptureButton::TYPE_SELECTION - << CaptureButton::TYPE_RECTANGLE - << CaptureButton::TYPE_CIRCLE - << CaptureButton::TYPE_MARKER - << CaptureButton::TYPE_BLUR - << CaptureButton::TYPE_SELECTIONINDICATOR - << CaptureButton::TYPE_MOVESELECTION - << CaptureButton::TYPE_UNDO - << CaptureButton::TYPE_REDO - << CaptureButton::TYPE_COPY - << CaptureButton::TYPE_SAVE - << CaptureButton::TYPE_EXIT - << CaptureButton::TYPE_IMAGEUPLOADER - << CaptureButton::TYPE_OPEN_APP - << CaptureButton::TYPE_PIN - << CaptureButton::TYPE_TEXT - << CaptureButton::TYPE_CIRCLECOUNT; - } - - using bt = CaptureButton::ButtonType; - std::sort(buttons.begin(), buttons.end(), [](bt a, bt b){ - return CaptureButton::getPriorityByButton(a) < - CaptureButton::getPriorityByButton(b); - }); - return buttons; -} - -void ConfigHandler::setButtons(const QVector &buttons) { - QVector l = fromButtonToInt(buttons); - normalizeButtons(l); +QVector +ConfigHandler::getButtons() +{ + QVector buttons; + if (m_settings.contains(QStringLiteral("buttons"))) { // TODO: remove toList in v1.0 - m_settings.setValue(QStringLiteral("buttons"), QVariant::fromValue(l.toList())); + QVector buttonsInt = m_settings.value(QStringLiteral("buttons")) + .value>() + .toVector(); + bool modified = normalizeButtons(buttonsInt); + if (modified) { + m_settings.setValue(QStringLiteral("buttons"), + QVariant::fromValue(buttonsInt.toList())); + } + buttons = fromIntToButton(buttonsInt); + } else { + // Default tools + buttons << CaptureButton::TYPE_PENCIL << CaptureButton::TYPE_DRAWER + << CaptureButton::TYPE_ARROW << CaptureButton::TYPE_SELECTION + << CaptureButton::TYPE_RECTANGLE << CaptureButton::TYPE_CIRCLE + << CaptureButton::TYPE_MARKER << CaptureButton::TYPE_BLUR + << CaptureButton::TYPE_SELECTIONINDICATOR + << CaptureButton::TYPE_MOVESELECTION << CaptureButton::TYPE_UNDO + << CaptureButton::TYPE_REDO << CaptureButton::TYPE_COPY + << CaptureButton::TYPE_SAVE << CaptureButton::TYPE_EXIT + << CaptureButton::TYPE_IMAGEUPLOADER << CaptureButton::TYPE_OPEN_APP + << CaptureButton::TYPE_PIN << CaptureButton::TYPE_TEXT + << CaptureButton::TYPE_CIRCLECOUNT; + } + + using bt = CaptureButton::ButtonType; + std::sort(buttons.begin(), buttons.end(), [](bt a, bt b) { + return CaptureButton::getPriorityByButton(a) < + CaptureButton::getPriorityByButton(b); + }); + return buttons; } -QVector ConfigHandler::getUserColors() { - QVector colors; - const QVector &defaultColors = { - Qt::darkRed, - Qt::red, - Qt::yellow, - Qt::green, - Qt::darkGreen, - Qt::cyan, - Qt::blue, - Qt::magenta, - Qt::darkMagenta - }; +void +ConfigHandler::setButtons(const QVector& buttons) +{ + QVector l = fromButtonToInt(buttons); + normalizeButtons(l); + // TODO: remove toList in v1.0 + m_settings.setValue(QStringLiteral("buttons"), + QVariant::fromValue(l.toList())); +} - if (m_settings.contains(QStringLiteral("userColors"))) { - for (const QString &hex : m_settings.value(QStringLiteral("userColors")).toStringList()) { - if (QColor::isValidColor(hex)) { - colors.append(QColor(hex)); - } - } +QVector +ConfigHandler::getUserColors() +{ + QVector colors; + const QVector& defaultColors = { + Qt::darkRed, Qt::red, Qt::yellow, Qt::green, Qt::darkGreen, + Qt::cyan, Qt::blue, Qt::magenta, Qt::darkMagenta + }; - if (colors.isEmpty()) { - colors = defaultColors; - } - } else { - colors = defaultColors; + if (m_settings.contains(QStringLiteral("userColors"))) { + for (const QString& hex : + m_settings.value(QStringLiteral("userColors")).toStringList()) { + if (QColor::isValidColor(hex)) { + colors.append(QColor(hex)); + } } - return colors; -} - -void ConfigHandler::setUserColors(const QVector &l) { - QStringList hexColors; - - for (const QColor &color : l) { - hexColors.append(color.name()); + if (colors.isEmpty()) { + colors = defaultColors; } + } else { + colors = defaultColors; + } - m_settings.setValue(QStringLiteral("userColors"), QVariant::fromValue(hexColors)); + return colors; } -QString ConfigHandler::savePathValue() { - return m_settings.value(QStringLiteral("savePath")).toString(); +void +ConfigHandler::setUserColors(const QVector& l) +{ + QStringList hexColors; + + for (const QColor& color : l) { + hexColors.append(color.name()); + } + + m_settings.setValue(QStringLiteral("userColors"), + QVariant::fromValue(hexColors)); } -void ConfigHandler::setSavePath(const QString &savePath) { - m_settings.setValue(QStringLiteral("savePath"), savePath); +QString +ConfigHandler::savePathValue() +{ + return m_settings.value(QStringLiteral("savePath")).toString(); } -QColor ConfigHandler::uiMainColorValue() { - QColor res = QColor(116, 0, 150); +void +ConfigHandler::setSavePath(const QString& savePath) +{ + m_settings.setValue(QStringLiteral("savePath"), savePath); +} - if (m_settings.contains(QStringLiteral("uiColor"))) { - QString hex = m_settings.value(QStringLiteral("uiColor")).toString(); +QColor +ConfigHandler::uiMainColorValue() +{ + QColor res = QColor(116, 0, 150); - if (QColor::isValidColor(hex)) { - res = QColor(hex); - } + if (m_settings.contains(QStringLiteral("uiColor"))) { + QString hex = m_settings.value(QStringLiteral("uiColor")).toString(); + + if (QColor::isValidColor(hex)) { + res = QColor(hex); } - return res; + } + return res; } -void ConfigHandler::setUIMainColor(const QColor &c) { - m_settings.setValue(QStringLiteral("uiColor"), c.name()); +void +ConfigHandler::setUIMainColor(const QColor& c) +{ + m_settings.setValue(QStringLiteral("uiColor"), c.name()); } -QColor ConfigHandler::uiContrastColorValue() { - QColor res = QColor(86, 0, 120); +QColor +ConfigHandler::uiContrastColorValue() +{ + QColor res = QColor(86, 0, 120); - if (m_settings.contains(QStringLiteral("contastUiColor"))) { - QString hex = m_settings.value(QStringLiteral("contastUiColor")).toString(); + if (m_settings.contains(QStringLiteral("contastUiColor"))) { + QString hex = m_settings.value(QStringLiteral("contastUiColor")).toString(); - if (QColor::isValidColor(hex)) { - res = QColor(hex); - } + if (QColor::isValidColor(hex)) { + res = QColor(hex); } + } - return res; + return res; } -void ConfigHandler::setUIContrastColor(const QColor &c) { - m_settings.setValue(QStringLiteral("contastUiColor"), c.name()); +void +ConfigHandler::setUIContrastColor(const QColor& c) +{ + m_settings.setValue(QStringLiteral("contastUiColor"), c.name()); } -QColor ConfigHandler::drawColorValue() { - QColor res(Qt::red); +QColor +ConfigHandler::drawColorValue() +{ + QColor res(Qt::red); - if (m_settings.contains(QStringLiteral("drawColor"))) { - QString hex = m_settings.value(QStringLiteral("drawColor")).toString(); + if (m_settings.contains(QStringLiteral("drawColor"))) { + QString hex = m_settings.value(QStringLiteral("drawColor")).toString(); - if (QColor::isValidColor(hex)) { - res = QColor(hex); - } + if (QColor::isValidColor(hex)) { + res = QColor(hex); } + } - return res; + return res; } -void ConfigHandler::setDrawColor(const QColor &c) { - m_settings.setValue(QStringLiteral("drawColor"), c.name()); +void +ConfigHandler::setDrawColor(const QColor& c) +{ + m_settings.setValue(QStringLiteral("drawColor"), c.name()); } -bool ConfigHandler::showHelpValue() { - bool res = true; - if (m_settings.contains(QStringLiteral("showHelp"))) { - res = m_settings.value(QStringLiteral("showHelp")).toBool(); - } - return res; +bool +ConfigHandler::showHelpValue() +{ + bool res = true; + if (m_settings.contains(QStringLiteral("showHelp"))) { + res = m_settings.value(QStringLiteral("showHelp")).toBool(); + } + return res; } -void ConfigHandler::setShowHelp(const bool showHelp) { - m_settings.setValue(QStringLiteral("showHelp"), showHelp); +void +ConfigHandler::setShowHelp(const bool showHelp) +{ + m_settings.setValue(QStringLiteral("showHelp"), showHelp); } -bool ConfigHandler::desktopNotificationValue() { - bool res = true; - if (m_settings.contains(QStringLiteral("showDesktopNotification"))) { - res = m_settings.value(QStringLiteral("showDesktopNotification")).toBool(); - } - return res; +bool +ConfigHandler::desktopNotificationValue() +{ + bool res = true; + if (m_settings.contains(QStringLiteral("showDesktopNotification"))) { + res = m_settings.value(QStringLiteral("showDesktopNotification")).toBool(); + } + return res; } -void ConfigHandler::setDesktopNotification(const bool showDesktopNotification) { - m_settings.setValue(QStringLiteral("showDesktopNotification"), showDesktopNotification); +void +ConfigHandler::setDesktopNotification(const bool showDesktopNotification) +{ + m_settings.setValue(QStringLiteral("showDesktopNotification"), + showDesktopNotification); } -QString ConfigHandler::filenamePatternValue() { - return m_settings.value(QStringLiteral("filenamePattern")).toString(); +QString +ConfigHandler::filenamePatternValue() +{ + return m_settings.value(QStringLiteral("filenamePattern")).toString(); } -void ConfigHandler::setFilenamePattern(const QString &pattern) { - return m_settings.setValue(QStringLiteral("filenamePattern"), pattern); +void +ConfigHandler::setFilenamePattern(const QString& pattern) +{ + return m_settings.setValue(QStringLiteral("filenamePattern"), pattern); } -bool ConfigHandler::disabledTrayIconValue() { - bool res = false; - if (m_settings.contains(QStringLiteral("disabledTrayIcon"))) { - res = m_settings.value(QStringLiteral("disabledTrayIcon")).toBool(); - } - return res; +bool +ConfigHandler::disabledTrayIconValue() +{ + bool res = false; + if (m_settings.contains(QStringLiteral("disabledTrayIcon"))) { + res = m_settings.value(QStringLiteral("disabledTrayIcon")).toBool(); + } + return res; } -void ConfigHandler::setDisabledTrayIcon(const bool disabledTrayIcon) { - m_settings.setValue(QStringLiteral("disabledTrayIcon"), disabledTrayIcon); +void +ConfigHandler::setDisabledTrayIcon(const bool disabledTrayIcon) +{ + m_settings.setValue(QStringLiteral("disabledTrayIcon"), disabledTrayIcon); } -int ConfigHandler::drawThicknessValue() { - int res = 0; - if (m_settings.contains(QStringLiteral("drawThickness"))) { - res = m_settings.value(QStringLiteral("drawThickness")).toInt(); - } - return res; +int +ConfigHandler::drawThicknessValue() +{ + int res = 0; + if (m_settings.contains(QStringLiteral("drawThickness"))) { + res = m_settings.value(QStringLiteral("drawThickness")).toInt(); + } + return res; } -void ConfigHandler::setdrawThickness(const int thickness) { - m_settings.setValue(QStringLiteral("drawThickness"), thickness); +void +ConfigHandler::setdrawThickness(const int thickness) +{ + m_settings.setValue(QStringLiteral("drawThickness"), thickness); } -bool ConfigHandler::keepOpenAppLauncherValue() { - return m_settings.value(QStringLiteral("keepOpenAppLauncher")).toBool(); +bool +ConfigHandler::keepOpenAppLauncherValue() +{ + return m_settings.value(QStringLiteral("keepOpenAppLauncher")).toBool(); } -void ConfigHandler::setKeepOpenAppLauncher(const bool keepOpen) { - m_settings.setValue(QStringLiteral("keepOpenAppLauncher"), keepOpen); +void +ConfigHandler::setKeepOpenAppLauncher(const bool keepOpen) +{ + m_settings.setValue(QStringLiteral("keepOpenAppLauncher"), keepOpen); } -bool ConfigHandler::startupLaunchValue() { - bool res = false; +bool +ConfigHandler::startupLaunchValue() +{ + bool res = false; - if (m_settings.contains(QStringLiteral("startupLaunch"))) { - res = m_settings.value(QStringLiteral("startupLaunch")).toBool(); - } + if (m_settings.contains(QStringLiteral("startupLaunch"))) { + res = m_settings.value(QStringLiteral("startupLaunch")).toBool(); + } - if (res != verifyLaunchFile()) { - setStartupLaunch(res); - } + if (res != verifyLaunchFile()) { + setStartupLaunch(res); + } - return res; + return res; } -bool ConfigHandler::verifyLaunchFile() { - bool res = false; +bool +ConfigHandler::verifyLaunchFile() +{ + bool res = false; #if defined(Q_OS_LINUX) || defined(Q_OS_UNIX) - QString path = QDir::homePath() + "/.config/autostart/Flameshot.desktop"; - res = QFile(path).exists(); + QString path = QDir::homePath() + "/.config/autostart/Flameshot.desktop"; + res = QFile(path).exists(); #elif defined(Q_OS_WIN) - QSettings bootUpSettings( - "HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", - QSettings::NativeFormat); - res = bootUpSettings.value("Flameshot").toString() == - QDir::toNativeSeparators(QCoreApplication::applicationFilePath()); + QSettings bootUpSettings( + "HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", + QSettings::NativeFormat); + res = bootUpSettings.value("Flameshot").toString() == + QDir::toNativeSeparators(QCoreApplication::applicationFilePath()); #endif - return res; + return res; } -void ConfigHandler::setStartupLaunch(const bool start) { +void +ConfigHandler::setStartupLaunch(const bool start) +{ #if defined(Q_OS_LINUX) || defined(Q_OS_UNIX) - QString path = QDir::homePath() + "/.config/autostart/"; - QDir autostartDir(path); - if (!autostartDir.exists()) { - autostartDir.mkpath("."); - } + QString path = QDir::homePath() + "/.config/autostart/"; + QDir autostartDir(path); + if (!autostartDir.exists()) { + autostartDir.mkpath("."); + } - QFile file(path + "Flameshot.desktop"); - if (start) { - if (file.open(QIODevice::WriteOnly)) { - QByteArray data("[Desktop Entry]\nName=flameshot\nIcon=flameshot" - "\nExec=flameshot\nTerminal=false\nType=Application" - "\nX-GNOME-Autostart-enabled=true\n"); - file.write(data); - } - } else { - file.remove(); + QFile file(path + "Flameshot.desktop"); + if (start) { + if (file.open(QIODevice::WriteOnly)) { + QByteArray data("[Desktop Entry]\nName=flameshot\nIcon=flameshot" + "\nExec=flameshot\nTerminal=false\nType=Application" + "\nX-GNOME-Autostart-enabled=true\n"); + file.write(data); } + } else { + file.remove(); + } #elif defined(Q_OS_WIN) - QSettings bootUpSettings( - "HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", - QSettings::NativeFormat); - if (start) { - QString app_path = - QDir::toNativeSeparators(QCoreApplication::applicationFilePath()); - bootUpSettings.setValue("Flameshot", app_path); - } else { - bootUpSettings.remove("Flameshot"); - } + QSettings bootUpSettings( + "HKEY_CURRENT_USER\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", + QSettings::NativeFormat); + if (start) { + QString app_path = + QDir::toNativeSeparators(QCoreApplication::applicationFilePath()); + bootUpSettings.setValue("Flameshot", app_path); + } else { + bootUpSettings.remove("Flameshot"); + } #endif - m_settings.setValue(QStringLiteral("startupLaunch"), start); + m_settings.setValue(QStringLiteral("startupLaunch"), start); } -int ConfigHandler::contrastOpacityValue() { - int opacity = 190; - if (m_settings.contains(QStringLiteral("contrastOpacity"))) { - opacity = m_settings.value(QStringLiteral("contrastOpacity")).toInt(); - opacity = qBound(0, opacity, 255); - } - return opacity; -} - -void ConfigHandler::setContrastOpacity(const int transparency) { - m_settings.setValue(QStringLiteral("contrastOpacity"), transparency); -} - -bool ConfigHandler::closeAfterScreenshotValue() { - return m_settings.value(QStringLiteral("closeAfterScreenshot")).toBool(); -} - -void ConfigHandler::setCloseAfterScreenshot(const bool close) { - m_settings.setValue(QStringLiteral("closeAfterScreenshot"), close); -} - -bool ConfigHandler::copyAndCloseAfterUploadEnabled() { - return m_settings.value(QStringLiteral("copyAndCloseAfterUpload")).toBool(); -} - -void ConfigHandler::setCopyAndCloseAfterUploadEnabled(const bool value) { - m_settings.setValue(QStringLiteral("copyAndCloseAfterUpload"), value); -} - -void ConfigHandler::setDefaults() { - m_settings.clear(); -} - -void ConfigHandler::setAllTheButtons() { - QVector buttons; - auto listTypes = CaptureButton::getIterableButtonTypes(); - for (const CaptureButton::ButtonType t: listTypes) { - buttons << static_cast(t); - } - // TODO: remove toList in v1.0 - m_settings.setValue(QStringLiteral("buttons"), QVariant::fromValue(buttons.toList())); -} - -QString ConfigHandler::configFilePath() const { - return m_settings.fileName(); -} - -bool ConfigHandler::normalizeButtons(QVector &buttons) { - auto listTypes = CaptureButton::getIterableButtonTypes(); - QVector listTypesInt; - for(auto i: listTypes) - listTypesInt << static_cast(i); - - bool hasChanged = false; - for (int i = 0; i < buttons.size(); i++) { - if (!listTypesInt.contains(buttons.at(i))) { - buttons.remove(i); - hasChanged = true; - } - } - return hasChanged; -} - -QVector ConfigHandler::fromIntToButton( - const QVector &l) +int +ConfigHandler::contrastOpacityValue() { - QVector buttons; - for (auto const i: l) - buttons << static_cast(i); - return buttons; + int opacity = 190; + if (m_settings.contains(QStringLiteral("contrastOpacity"))) { + opacity = m_settings.value(QStringLiteral("contrastOpacity")).toInt(); + opacity = qBound(0, opacity, 255); + } + return opacity; } -QVector ConfigHandler::fromButtonToInt( - const QVector &l) +void +ConfigHandler::setContrastOpacity(const int transparency) { - QVector buttons; - for (auto const i: l) - buttons << static_cast(i); - return buttons; + m_settings.setValue(QStringLiteral("contrastOpacity"), transparency); +} + +bool +ConfigHandler::closeAfterScreenshotValue() +{ + return m_settings.value(QStringLiteral("closeAfterScreenshot")).toBool(); +} + +void +ConfigHandler::setCloseAfterScreenshot(const bool close) +{ + m_settings.setValue(QStringLiteral("closeAfterScreenshot"), close); +} + +bool +ConfigHandler::copyAndCloseAfterUploadEnabled() +{ + return m_settings.value(QStringLiteral("copyAndCloseAfterUpload")).toBool(); +} + +void +ConfigHandler::setCopyAndCloseAfterUploadEnabled(const bool value) +{ + m_settings.setValue(QStringLiteral("copyAndCloseAfterUpload"), value); +} + +void +ConfigHandler::setDefaults() +{ + m_settings.clear(); +} + +void +ConfigHandler::setAllTheButtons() +{ + QVector buttons; + auto listTypes = CaptureButton::getIterableButtonTypes(); + for (const CaptureButton::ButtonType t : listTypes) { + buttons << static_cast(t); + } + // TODO: remove toList in v1.0 + m_settings.setValue(QStringLiteral("buttons"), + QVariant::fromValue(buttons.toList())); +} + +QString +ConfigHandler::configFilePath() const +{ + return m_settings.fileName(); +} + +bool +ConfigHandler::normalizeButtons(QVector& buttons) +{ + auto listTypes = CaptureButton::getIterableButtonTypes(); + QVector listTypesInt; + for (auto i : listTypes) + listTypesInt << static_cast(i); + + bool hasChanged = false; + for (int i = 0; i < buttons.size(); i++) { + if (!listTypesInt.contains(buttons.at(i))) { + buttons.remove(i); + hasChanged = true; + } + } + return hasChanged; +} + +QVector +ConfigHandler::fromIntToButton(const QVector& l) +{ + QVector buttons; + for (auto const i : l) + buttons << static_cast(i); + return buttons; +} + +QVector +ConfigHandler::fromButtonToInt(const QVector& l) +{ + QVector buttons; + for (auto const i : l) + buttons << static_cast(i); + return buttons; } diff --git a/src/utils/confighandler.h b/src/utils/confighandler.h index 1886882c..dc995762 100644 --- a/src/utils/confighandler.h +++ b/src/utils/confighandler.h @@ -18,73 +18,73 @@ #pragma once #include "src/widgets/capture/capturebutton.h" -#include #include +#include -class ConfigHandler { +class ConfigHandler +{ public: - explicit ConfigHandler(); + explicit ConfigHandler(); - QVector getButtons(); - void setButtons(const QVector &); + QVector getButtons(); + void setButtons(const QVector&); - QVector getUserColors(); - void setUserColors(const QVector &); + QVector getUserColors(); + void setUserColors(const QVector&); - QString savePathValue(); - void setSavePath(const QString &); + QString savePathValue(); + void setSavePath(const QString&); - QColor uiMainColorValue(); - void setUIMainColor(const QColor &); + QColor uiMainColorValue(); + void setUIMainColor(const QColor&); - QColor uiContrastColorValue(); - void setUIContrastColor(const QColor &); + QColor uiContrastColorValue(); + void setUIContrastColor(const QColor&); - QColor drawColorValue(); - void setDrawColor(const QColor &); + QColor drawColorValue(); + void setDrawColor(const QColor&); - bool showHelpValue(); - void setShowHelp(const bool); + bool showHelpValue(); + void setShowHelp(const bool); - bool desktopNotificationValue(); - void setDesktopNotification(const bool); + bool desktopNotificationValue(); + void setDesktopNotification(const bool); - QString filenamePatternValue(); - void setFilenamePattern(const QString &); + QString filenamePatternValue(); + void setFilenamePattern(const QString&); - bool disabledTrayIconValue(); - void setDisabledTrayIcon(const bool); + bool disabledTrayIconValue(); + void setDisabledTrayIcon(const bool); - int drawThicknessValue(); - void setdrawThickness(const int); + int drawThicknessValue(); + void setdrawThickness(const int); - bool keepOpenAppLauncherValue(); - void setKeepOpenAppLauncher(const bool); + bool keepOpenAppLauncherValue(); + void setKeepOpenAppLauncher(const bool); - bool verifyLaunchFile(); - bool startupLaunchValue(); - void setStartupLaunch(const bool); + bool verifyLaunchFile(); + bool startupLaunchValue(); + void setStartupLaunch(const bool); - int contrastOpacityValue(); - void setContrastOpacity(const int); + int contrastOpacityValue(); + void setContrastOpacity(const int); - bool closeAfterScreenshotValue(); - void setCloseAfterScreenshot(const bool); + bool closeAfterScreenshotValue(); + void setCloseAfterScreenshot(const bool); - bool copyAndCloseAfterUploadEnabled(); - void setCopyAndCloseAfterUploadEnabled(const bool); + bool copyAndCloseAfterUploadEnabled(); + void setCopyAndCloseAfterUploadEnabled(const bool); + void setDefaults(); + void setAllTheButtons(); - void setDefaults(); - void setAllTheButtons(); - - QString configFilePath() const; + QString configFilePath() const; private: - QSettings m_settings; + QSettings m_settings; - bool normalizeButtons(QVector &); + bool normalizeButtons(QVector&); - QVector fromIntToButton(const QVector &l); - QVector fromButtonToInt(const QVector &l); + QVector fromIntToButton(const QVector& l); + QVector fromButtonToInt(const QVector& l); }; diff --git a/src/utils/dbusutils.cpp b/src/utils/dbusutils.cpp index 3a254f30..82fcc6a9 100644 --- a/src/utils/dbusutils.cpp +++ b/src/utils/dbusutils.cpp @@ -18,46 +18,59 @@ #include "dbusutils.h" #include "src/utils/systemnotification.h" #include -#include #include +#include -DBusUtils::DBusUtils(QObject *parent) : QObject(parent) { +DBusUtils::DBusUtils(QObject* parent) + : QObject(parent) +{} + +void +DBusUtils::connectPrintCapture(QDBusConnection& session, uint id) +{ + m_id = id; + // captureTaken + session.connect(QStringLiteral("org.dharkael.Flameshot"), + QStringLiteral("/"), + QLatin1String(""), + QStringLiteral("captureTaken"), + this, + SLOT(captureTaken(uint, QByteArray))); + // captureFailed + session.connect(QStringLiteral("org.dharkael.Flameshot"), + QStringLiteral("/"), + QLatin1String(""), + QStringLiteral("captureFailed"), + this, + SLOT(captureFailed(uint))); } -void DBusUtils::connectPrintCapture(QDBusConnection &session, uint id) { - m_id = id; - // captureTaken - session.connect(QStringLiteral("org.dharkael.Flameshot"), - QStringLiteral("/"), QLatin1String(""), QStringLiteral("captureTaken"), - this, - SLOT(captureTaken(uint, QByteArray))); - // captureFailed - session.connect(QStringLiteral("org.dharkael.Flameshot"), - QStringLiteral("/"), QLatin1String(""), QStringLiteral("captureFailed"), - this, - SLOT(captureFailed(uint))); +void +DBusUtils::checkDBusConnection(const QDBusConnection& connection) +{ + if (!connection.isConnected()) { + SystemNotification().sendMessage(tr("Unable to connect via DBus")); + qApp->exit(1); + } } -void DBusUtils::checkDBusConnection(const QDBusConnection &connection) { - if (!connection.isConnected()) { - SystemNotification().sendMessage(tr("Unable to connect via DBus")); - qApp->exit(1); - } +void +DBusUtils::captureTaken(uint id, QByteArray rawImage) +{ + if (m_id == id) { + QFile file; + file.open(stdout, QIODevice::WriteOnly); + file.write(rawImage); + file.close(); + qApp->exit(); + } } -void DBusUtils::captureTaken(uint id, QByteArray rawImage) { - if (m_id == id) { - QFile file; - file.open(stdout, QIODevice::WriteOnly); - file.write(rawImage); - file.close(); - qApp->exit(); - } -} - -void DBusUtils::captureFailed(uint id) { - if (m_id == id) { - QTextStream(stdout) << "screenshot aborted\n"; - qApp->exit(1); - } +void +DBusUtils::captureFailed(uint id) +{ + if (m_id == id) { + QTextStream(stdout) << "screenshot aborted\n"; + qApp->exit(1); + } } diff --git a/src/utils/dbusutils.h b/src/utils/dbusutils.h index b7e7951c..82de1b95 100644 --- a/src/utils/dbusutils.h +++ b/src/utils/dbusutils.h @@ -21,19 +21,19 @@ #include #include -class DBusUtils : public QObject { - Q_OBJECT +class DBusUtils : public QObject +{ + Q_OBJECT public: - explicit DBusUtils(QObject *parent = nullptr); + explicit DBusUtils(QObject* parent = nullptr); - void connectPrintCapture(QDBusConnection &session, uint id); - void checkDBusConnection(const QDBusConnection &connection); + void connectPrintCapture(QDBusConnection& session, uint id); + void checkDBusConnection(const QDBusConnection& connection); public slots: - void captureTaken(uint id, QByteArray rawImage); - void captureFailed(uint id); + void captureTaken(uint id, QByteArray rawImage); + void captureFailed(uint id); private: - - uint m_id; + uint m_id; }; diff --git a/src/utils/desktopfileparse.cpp b/src/utils/desktopfileparse.cpp index 0079db1b..88171d62 100644 --- a/src/utils/desktopfileparse.cpp +++ b/src/utils/desktopfileparse.cpp @@ -16,137 +16,134 @@ // along with Flameshot. If not, see . #include "desktopfileparse.h" -#include #include +#include +#include #include #include -#include -DesktopFileParser::DesktopFileParser() { - QString locale = QLocale().name(); - QString localeShort = QLocale().name().left(2); - m_localeName = QStringLiteral("Name[%1]").arg(locale); - m_localeDescription = QStringLiteral("Comment[%1]").arg(locale); - m_localeNameShort = QStringLiteral("Name[%1]").arg(localeShort); - m_localeDescriptionShort = QStringLiteral("Comment[%1]") - .arg(localeShort); - m_defaultIcon = QIcon::fromTheme(QStringLiteral("application-x-executable")); -} - -DesktopAppData DesktopFileParser::parseDesktopFile( - const QString &fileName, bool &ok) const +DesktopFileParser::DesktopFileParser() { - DesktopAppData res; - ok = true; - QFile file(fileName); - if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { - ok = false; - return res; - } - bool nameLocaleSet = false; - bool descriptionLocaleSet = false; - bool isApplication = false; - QTextStream in(&file); - // enter the desktop entry definition - while (!in.atEnd() && in.readLine() != QLatin1String("[Desktop Entry]")) { - } - // start parsing - while (!in.atEnd()) { - QString line = in.readLine(); - if (line.startsWith(QLatin1String("Icon"))) { - res.icon = QIcon::fromTheme( - line.mid(line.indexOf(QLatin1String("="))+1).trimmed(), - m_defaultIcon); - } - else if (!nameLocaleSet && line.startsWith(QLatin1String("Name"))) { - if (line.startsWith(m_localeName) || - line.startsWith(m_localeNameShort)) - { - res.name = line.mid(line.indexOf(QLatin1String("="))+1).trimmed(); - nameLocaleSet = true; - } else if (line.startsWith(QLatin1String("Name="))) { - res.name = line.mid(line.indexOf(QLatin1String("="))+1).trimmed(); - } - } - else if (!descriptionLocaleSet && line.startsWith(QLatin1String("Comment"))) { - if (line.startsWith(m_localeDescription) || - line.startsWith(m_localeDescriptionShort)) - { - res.description = line.mid(line.indexOf(QLatin1String("="))+1).trimmed(); - descriptionLocaleSet = true; - } else if (line.startsWith(QLatin1String("Comment="))) { - res.description = line.mid(line.indexOf(QLatin1String("="))+1).trimmed(); - } - } - else if (line.startsWith(QLatin1String("Exec"))) { - if (line.contains(QLatin1String("%"))) { - res.exec = line.mid(line.indexOf(QLatin1String("="))+1) - .trimmed(); - } else { - ok = false; - break; - } - } - else if (line.startsWith(QLatin1String("Type"))) { - if (line.contains(QLatin1String("Application"))) { - isApplication = true; - } - } - else if (line.startsWith(QLatin1String("Categories"))) { - res.categories = line.mid(line.indexOf(QLatin1String("="))+1).split(QStringLiteral(";")); - } - else if (line == QLatin1String("NoDisplay=true")) { - ok = false; - break; - } - else if (line == QLatin1String("Terminal=true")) { - res.showInTerminal = true; - } - // ignore the other entries - else if (line.startsWith(QLatin1String("["))) { - break; - } - } - file.close(); - if (res.exec.isEmpty() || res.name.isEmpty() || !isApplication) { - ok = false; - } - return res; + QString locale = QLocale().name(); + QString localeShort = QLocale().name().left(2); + m_localeName = QStringLiteral("Name[%1]").arg(locale); + m_localeDescription = QStringLiteral("Comment[%1]").arg(locale); + m_localeNameShort = QStringLiteral("Name[%1]").arg(localeShort); + m_localeDescriptionShort = QStringLiteral("Comment[%1]").arg(localeShort); + m_defaultIcon = QIcon::fromTheme(QStringLiteral("application-x-executable")); } -int DesktopFileParser::processDirectory(const QDir &dir) { - QStringList entries = dir.entryList(QDir::NoDotAndDotDot | QDir::Files); - bool ok; - int length = m_appList.length(); - for (QString file: entries){ - DesktopAppData app = parseDesktopFile(dir.absoluteFilePath(file), ok); - if (ok) { - m_appList.append(app); - } - } - return m_appList.length() - length; -} - -QVector DesktopFileParser::getAppsByCategory(const QString &category) { - QVector res; - for (const DesktopAppData &app : m_appList) { - if (app.categories.contains(category)) { - res.append(app); - } - } - return res; -} - -QMap> DesktopFileParser::getAppsByCategory( - const QStringList &categories) +DesktopAppData +DesktopFileParser::parseDesktopFile(const QString& fileName, bool& ok) const { - QMap> res; - for (const DesktopAppData &app : m_appList) { - for (const QString &category: categories) { - if (app.categories.contains(category)) { - res[category].append(app); - } - } - } + DesktopAppData res; + ok = true; + QFile file(fileName); + if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) { + ok = false; return res; + } + bool nameLocaleSet = false; + bool descriptionLocaleSet = false; + bool isApplication = false; + QTextStream in(&file); + // enter the desktop entry definition + while (!in.atEnd() && in.readLine() != QLatin1String("[Desktop Entry]")) { + } + // start parsing + while (!in.atEnd()) { + QString line = in.readLine(); + if (line.startsWith(QLatin1String("Icon"))) { + res.icon = QIcon::fromTheme( + line.mid(line.indexOf(QLatin1String("=")) + 1).trimmed(), + m_defaultIcon); + } else if (!nameLocaleSet && line.startsWith(QLatin1String("Name"))) { + if (line.startsWith(m_localeName) || line.startsWith(m_localeNameShort)) { + res.name = line.mid(line.indexOf(QLatin1String("=")) + 1).trimmed(); + nameLocaleSet = true; + } else if (line.startsWith(QLatin1String("Name="))) { + res.name = line.mid(line.indexOf(QLatin1String("=")) + 1).trimmed(); + } + } else if (!descriptionLocaleSet && + line.startsWith(QLatin1String("Comment"))) { + if (line.startsWith(m_localeDescription) || + line.startsWith(m_localeDescriptionShort)) { + res.description = + line.mid(line.indexOf(QLatin1String("=")) + 1).trimmed(); + descriptionLocaleSet = true; + } else if (line.startsWith(QLatin1String("Comment="))) { + res.description = + line.mid(line.indexOf(QLatin1String("=")) + 1).trimmed(); + } + } else if (line.startsWith(QLatin1String("Exec"))) { + if (line.contains(QLatin1String("%"))) { + res.exec = line.mid(line.indexOf(QLatin1String("=")) + 1).trimmed(); + } else { + ok = false; + break; + } + } else if (line.startsWith(QLatin1String("Type"))) { + if (line.contains(QLatin1String("Application"))) { + isApplication = true; + } + } else if (line.startsWith(QLatin1String("Categories"))) { + res.categories = line.mid(line.indexOf(QLatin1String("=")) + 1) + .split(QStringLiteral(";")); + } else if (line == QLatin1String("NoDisplay=true")) { + ok = false; + break; + } else if (line == QLatin1String("Terminal=true")) { + res.showInTerminal = true; + } + // ignore the other entries + else if (line.startsWith(QLatin1String("["))) { + break; + } + } + file.close(); + if (res.exec.isEmpty() || res.name.isEmpty() || !isApplication) { + ok = false; + } + return res; +} + +int +DesktopFileParser::processDirectory(const QDir& dir) +{ + QStringList entries = dir.entryList(QDir::NoDotAndDotDot | QDir::Files); + bool ok; + int length = m_appList.length(); + for (QString file : entries) { + DesktopAppData app = parseDesktopFile(dir.absoluteFilePath(file), ok); + if (ok) { + m_appList.append(app); + } + } + return m_appList.length() - length; +} + +QVector +DesktopFileParser::getAppsByCategory(const QString& category) +{ + QVector res; + for (const DesktopAppData& app : m_appList) { + if (app.categories.contains(category)) { + res.append(app); + } + } + return res; +} + +QMap> +DesktopFileParser::getAppsByCategory(const QStringList& categories) +{ + QMap> res; + for (const DesktopAppData& app : m_appList) { + for (const QString& category : categories) { + if (app.categories.contains(category)) { + res[category].append(app); + } + } + } + return res; } diff --git a/src/utils/desktopfileparse.h b/src/utils/desktopfileparse.h index c00a53cf..79e74509 100644 --- a/src/utils/desktopfileparse.h +++ b/src/utils/desktopfileparse.h @@ -18,55 +18,59 @@ #pragma once #include -#include #include +#include class QDir; class QString; class QTextStream; -struct DesktopAppData { - DesktopAppData() : showInTerminal() {} +struct DesktopAppData +{ + DesktopAppData() + : showInTerminal() + {} - DesktopAppData( - const QString &name, - const QString &description, - const QString &exec, - QIcon icon) : - name(name), - description(description), - exec(exec), - icon(icon), - showInTerminal(false) - {} + DesktopAppData(const QString& name, + const QString& description, + const QString& exec, + QIcon icon) + : name(name) + , description(description) + , exec(exec) + , icon(icon) + , showInTerminal(false) + {} - bool operator==(const DesktopAppData &other) const { - return name == other.name; - } + bool operator==(const DesktopAppData& other) const + { + return name == other.name; + } - QString name; - QString description; - QString exec; - QStringList categories; - QIcon icon; - bool showInTerminal; + QString name; + QString description; + QString exec; + QStringList categories; + QIcon icon; + bool showInTerminal; }; -struct DesktopFileParser { - DesktopFileParser(); - DesktopAppData parseDesktopFile(const QString &fileName, bool &ok) const; - int processDirectory(const QDir &dir); +struct DesktopFileParser +{ + DesktopFileParser(); + DesktopAppData parseDesktopFile(const QString& fileName, bool& ok) const; + int processDirectory(const QDir& dir); - QVector getAppsByCategory(const QString &category); - QMap> getAppsByCategory( - const QStringList &categories); + QVector getAppsByCategory(const QString& category); + QMap> getAppsByCategory( + const QStringList& categories); private: - QString m_localeName; - QString m_localeDescription; - QString m_localeNameShort; - QString m_localeDescriptionShort; + QString m_localeName; + QString m_localeDescription; + QString m_localeNameShort; + QString m_localeDescriptionShort; - QIcon m_defaultIcon; - QVector m_appList; + QIcon m_defaultIcon; + QVector m_appList; }; diff --git a/src/utils/desktopinfo.cpp b/src/utils/desktopinfo.cpp index 9c4b1e1f..57bfdd16 100644 --- a/src/utils/desktopinfo.cpp +++ b/src/utils/desktopinfo.cpp @@ -18,29 +18,37 @@ #include "desktopinfo.h" #include -DesktopInfo::DesktopInfo() { - auto e = QProcessEnvironment::systemEnvironment(); - XDG_CURRENT_DESKTOP = e.value(QStringLiteral("XDG_CURRENT_DESKTOP")); - XDG_SESSION_TYPE = e.value(QStringLiteral("XDG_SESSION_TYPE")); - WAYLAND_DISPLAY = e.value(QStringLiteral("WAYLAND_DISPLAY")); - KDE_FULL_SESSION = e.value(QStringLiteral("KDE_FULL_SESSION")); - GNOME_DESKTOP_SESSION_ID = e.value(QStringLiteral("GNOME_DESKTOP_SESSION_ID")); - DESKTOP_SESSION = e.value(QStringLiteral("DESKTOP_SESSION")); +DesktopInfo::DesktopInfo() +{ + auto e = QProcessEnvironment::systemEnvironment(); + XDG_CURRENT_DESKTOP = e.value(QStringLiteral("XDG_CURRENT_DESKTOP")); + XDG_SESSION_TYPE = e.value(QStringLiteral("XDG_SESSION_TYPE")); + WAYLAND_DISPLAY = e.value(QStringLiteral("WAYLAND_DISPLAY")); + KDE_FULL_SESSION = e.value(QStringLiteral("KDE_FULL_SESSION")); + GNOME_DESKTOP_SESSION_ID = + e.value(QStringLiteral("GNOME_DESKTOP_SESSION_ID")); + DESKTOP_SESSION = e.value(QStringLiteral("DESKTOP_SESSION")); } -bool DesktopInfo::waylandDectected() { - return XDG_SESSION_TYPE == QLatin1String("wayland") || - WAYLAND_DISPLAY.contains(QLatin1String("wayland"), Qt::CaseInsensitive); +bool +DesktopInfo::waylandDectected() +{ + return XDG_SESSION_TYPE == QLatin1String("wayland") || + WAYLAND_DISPLAY.contains(QLatin1String("wayland"), + Qt::CaseInsensitive); } -DesktopInfo::WM DesktopInfo::windowManager() { - DesktopInfo::WM res = DesktopInfo::OTHER; - if (XDG_CURRENT_DESKTOP.contains(QLatin1String("GNOME"), Qt::CaseInsensitive) || - !GNOME_DESKTOP_SESSION_ID.isEmpty()) - { - res = DesktopInfo::GNOME; - } else if (!KDE_FULL_SESSION.isEmpty() || DESKTOP_SESSION == QLatin1String("kde-plasma")) { - res = DesktopInfo::KDE; - } - return res; +DesktopInfo::WM +DesktopInfo::windowManager() +{ + DesktopInfo::WM res = DesktopInfo::OTHER; + if (XDG_CURRENT_DESKTOP.contains(QLatin1String("GNOME"), + Qt::CaseInsensitive) || + !GNOME_DESKTOP_SESSION_ID.isEmpty()) { + res = DesktopInfo::GNOME; + } else if (!KDE_FULL_SESSION.isEmpty() || + DESKTOP_SESSION == QLatin1String("kde-plasma")) { + res = DesktopInfo::KDE; + } + return res; } diff --git a/src/utils/desktopinfo.h b/src/utils/desktopinfo.h index 06220f4a..8eff6acc 100644 --- a/src/utils/desktopinfo.h +++ b/src/utils/desktopinfo.h @@ -19,25 +19,27 @@ #include -class DesktopInfo { +class DesktopInfo +{ public: - DesktopInfo(); + DesktopInfo(); - enum WM { - GNOME, - KDE, - OTHER - }; + enum WM + { + GNOME, + KDE, + OTHER + }; - bool waylandDectected(); - WM windowManager(); + bool waylandDectected(); + WM windowManager(); private: - QString XDG_CURRENT_DESKTOP; - QString XDG_SESSION_TYPE; - QString WAYLAND_DISPLAY; - QString KDE_FULL_SESSION; - QString GNOME_DESKTOP_SESSION_ID; - QString GDMSESSION; - QString DESKTOP_SESSION; + QString XDG_CURRENT_DESKTOP; + QString XDG_SESSION_TYPE; + QString WAYLAND_DISPLAY; + QString KDE_FULL_SESSION; + QString GNOME_DESKTOP_SESSION_ID; + QString GDMSESSION; + QString DESKTOP_SESSION; }; diff --git a/src/utils/filenamehandler.cpp b/src/utils/filenamehandler.cpp index 9c65579d..2b51c458 100644 --- a/src/utils/filenamehandler.cpp +++ b/src/utils/filenamehandler.cpp @@ -17,93 +17,114 @@ #include "filenamehandler.h" #include "src/utils/confighandler.h" +#include +#include #include #include -#include -#include -FileNameHandler::FileNameHandler(QObject *parent) : QObject(parent) { - std::locale::global(std::locale("")); +FileNameHandler::FileNameHandler(QObject* parent) + : QObject(parent) +{ + std::locale::global(std::locale("")); } -QString FileNameHandler::parsedPattern() { - return parseFilename(ConfigHandler().filenamePatternValue()); +QString +FileNameHandler::parsedPattern() +{ + return parseFilename(ConfigHandler().filenamePatternValue()); } -QString FileNameHandler::parseFilename(const QString &name) { - QString res = name; - if (name.isEmpty()) { - res = QLatin1String("%F_%H-%M"); - } - std::time_t t = std::time(NULL); +QString +FileNameHandler::parseFilename(const QString& name) +{ + QString res = name; + if (name.isEmpty()) { + res = QLatin1String("%F_%H-%M"); + } + std::time_t t = std::time(NULL); - char *tempData = QStringTocharArr(res); - char data[MAX_CHARACTERS] = {0}; - std::strftime(data, sizeof(data), - tempData, std::localtime(&t)); - res = QString::fromLocal8Bit(data, (int)strlen(data)); - free(tempData); + char* tempData = QStringTocharArr(res); + char data[MAX_CHARACTERS] = { 0 }; + std::strftime(data, sizeof(data), tempData, std::localtime(&t)); + res = QString::fromLocal8Bit(data, (int)strlen(data)); + free(tempData); - // add the parsed pattern in a correct format for the filesystem - res = res.replace(QLatin1String("/"), QStringLiteral("⁄")).replace(QLatin1String(":"), QLatin1String("-")); - return res; + // add the parsed pattern in a correct format for the filesystem + res = res.replace(QLatin1String("/"), QStringLiteral("⁄")) + .replace(QLatin1String(":"), QLatin1String("-")); + return res; } -QString FileNameHandler::generateAbsolutePath(const QString &path) { - QString directory = path; - QString filename = parsedPattern(); - fixPath(directory, filename); - return directory + filename; +QString +FileNameHandler::generateAbsolutePath(const QString& path) +{ + QString directory = path; + QString filename = parsedPattern(); + fixPath(directory, filename); + return directory + filename; } // path a images si no existe, add numeration -void FileNameHandler::setPattern(const QString &pattern) { - ConfigHandler().setFilenamePattern(pattern); +void +FileNameHandler::setPattern(const QString& pattern) +{ + ConfigHandler().setFilenamePattern(pattern); } -QString FileNameHandler::absoluteSavePath(QString &directory, QString &filename) { - ConfigHandler config; - directory = config.savePathValue(); - if (directory.isEmpty() || !QDir(directory).exists() || !QFileInfo(directory).isWritable()) { - directory = QStandardPaths::writableLocation(QStandardPaths::PicturesLocation); - } - filename = parsedPattern(); - fixPath(directory, filename); - return directory + filename; -} - -QString FileNameHandler::absoluteSavePath() { - QString dir, file; - return absoluteSavePath(dir, file); -} - -QString FileNameHandler::charArrToQString(const char *c) { - return QString::fromLocal8Bit(c, MAX_CHARACTERS); -} - -char * FileNameHandler::QStringTocharArr(const QString &s) { - QByteArray ba = s.toLocal8Bit(); - return const_cast(strdup(ba.constData())); -} - -void FileNameHandler::fixPath(QString &directory, QString &filename) { - // add '/' at the end of the directory - if (!directory.endsWith(QLatin1String("/"))) { - directory += QLatin1String("/"); - } - // add numeration in case of repeated filename in the directory - // find unused name adding _n where n is a number - QFileInfo checkFile(directory + filename + ".png"); - if (checkFile.exists()) { - filename += QLatin1String("_"); - int i = 1; - while (true) { - checkFile.setFile( - directory + filename + QString::number(i) + ".png"); - if (!checkFile.exists()) { - filename += QString::number(i); - break; - } - ++i; - } +QString +FileNameHandler::absoluteSavePath(QString& directory, QString& filename) +{ + ConfigHandler config; + directory = config.savePathValue(); + if (directory.isEmpty() || !QDir(directory).exists() || + !QFileInfo(directory).isWritable()) { + directory = + QStandardPaths::writableLocation(QStandardPaths::PicturesLocation); + } + filename = parsedPattern(); + fixPath(directory, filename); + return directory + filename; +} + +QString +FileNameHandler::absoluteSavePath() +{ + QString dir, file; + return absoluteSavePath(dir, file); +} + +QString +FileNameHandler::charArrToQString(const char* c) +{ + return QString::fromLocal8Bit(c, MAX_CHARACTERS); +} + +char* +FileNameHandler::QStringTocharArr(const QString& s) +{ + QByteArray ba = s.toLocal8Bit(); + return const_cast(strdup(ba.constData())); +} + +void +FileNameHandler::fixPath(QString& directory, QString& filename) +{ + // add '/' at the end of the directory + if (!directory.endsWith(QLatin1String("/"))) { + directory += QLatin1String("/"); + } + // add numeration in case of repeated filename in the directory + // find unused name adding _n where n is a number + QFileInfo checkFile(directory + filename + ".png"); + if (checkFile.exists()) { + filename += QLatin1String("_"); + int i = 1; + while (true) { + checkFile.setFile(directory + filename + QString::number(i) + ".png"); + if (!checkFile.exists()) { + filename += QString::number(i); + break; + } + ++i; } + } } diff --git a/src/utils/filenamehandler.h b/src/utils/filenamehandler.h index 5d379064..74d5e875 100644 --- a/src/utils/filenamehandler.h +++ b/src/utils/filenamehandler.h @@ -19,27 +19,27 @@ #include -class FileNameHandler : public QObject { - Q_OBJECT +class FileNameHandler : public QObject +{ + Q_OBJECT public: - explicit FileNameHandler(QObject *parent = nullptr); + explicit FileNameHandler(QObject* parent = nullptr); - QString parsedPattern(); - QString parseFilename(const QString &name); - QString generateAbsolutePath(const QString &path); - QString absoluteSavePath(QString &directory, QString &filename); - QString absoluteSavePath(); + QString parsedPattern(); + QString parseFilename(const QString& name); + QString generateAbsolutePath(const QString& path); + QString absoluteSavePath(QString& directory, QString& filename); + QString absoluteSavePath(); - - static const int MAX_CHARACTERS = 70; + static const int MAX_CHARACTERS = 70; public slots: - void setPattern(const QString &pattern); + void setPattern(const QString& pattern); private: - //using charArr = char[MAX_CHARACTERS]; - QString charArrToQString(const char *c); - char * QStringTocharArr(const QString &s); + // using charArr = char[MAX_CHARACTERS]; + QString charArrToQString(const char* c); + char* QStringTocharArr(const QString& s); - void fixPath(QString &directory, QString &filename); + void fixPath(QString& directory, QString& filename); }; diff --git a/src/utils/globalvalues.cpp b/src/utils/globalvalues.cpp index fde27e1e..de394136 100644 --- a/src/utils/globalvalues.cpp +++ b/src/utils/globalvalues.cpp @@ -16,9 +16,11 @@ // along with Flameshot. If not, see . #include "globalvalues.h" -#include #include +#include -int GlobalValues::buttonBaseSize() { - return QApplication::fontMetrics().lineSpacing() * 2.2; +int +GlobalValues::buttonBaseSize() +{ + return QApplication::fontMetrics().lineSpacing() * 2.2; } diff --git a/src/utils/globalvalues.h b/src/utils/globalvalues.h index 656306bd..64478036 100644 --- a/src/utils/globalvalues.h +++ b/src/utils/globalvalues.h @@ -19,6 +19,7 @@ namespace GlobalValues { -int buttonBaseSize(); +int +buttonBaseSize(); } diff --git a/src/utils/pathinfo.cpp b/src/utils/pathinfo.cpp index 8e51d47d..366b9d07 100644 --- a/src/utils/pathinfo.cpp +++ b/src/utils/pathinfo.cpp @@ -17,29 +17,32 @@ #include "pathinfo.h" #include -#include #include +#include -const QString PathInfo::whiteIconPath() { - return QStringLiteral(":/img/material/white/"); +const QString +PathInfo::whiteIconPath() +{ + return QStringLiteral(":/img/material/white/"); } -const QString PathInfo::blackIconPath() { - return QStringLiteral(":/img/material/black/"); +const QString +PathInfo::blackIconPath() +{ + return QStringLiteral(":/img/material/black/"); } -QStringList PathInfo::translationsPaths() { - QString binaryPath = QFileInfo(qApp->applicationDirPath()) - .absoluteFilePath(); - QString trPath = QDir::toNativeSeparators(binaryPath + "/translations") ; +QStringList +PathInfo::translationsPaths() +{ + QString binaryPath = QFileInfo(qApp->applicationDirPath()).absoluteFilePath(); + QString trPath = QDir::toNativeSeparators(binaryPath + "/translations"); #if defined(Q_OS_LINUX) || defined(Q_OS_UNIX) - return QStringList() - << QStringLiteral(APP_PREFIX) + "/share/flameshot/translations" - << trPath - << QStringLiteral("/usr/share/flameshot/translations") - << QStringLiteral("/usr/local/share/flameshot/translations"); + return QStringList() + << QStringLiteral(APP_PREFIX) + "/share/flameshot/translations" + << trPath << QStringLiteral("/usr/share/flameshot/translations") + << QStringLiteral("/usr/local/share/flameshot/translations"); #elif defined(Q_OS_WIN) - return QStringList() - << trPath; + return QStringList() << trPath; #endif } diff --git a/src/utils/pathinfo.h b/src/utils/pathinfo.h index d7d57ddd..28004fd7 100644 --- a/src/utils/pathinfo.h +++ b/src/utils/pathinfo.h @@ -21,10 +21,13 @@ namespace PathInfo { // namespace -const QString whiteIconPath(); +const QString +whiteIconPath(); -const QString blackIconPath(); +const QString +blackIconPath(); -QStringList translationsPaths(); +QStringList +translationsPaths(); } // namespace diff --git a/src/utils/screengrabber.cpp b/src/utils/screengrabber.cpp index 8b535bd0..c2a9ae67 100644 --- a/src/utils/screengrabber.cpp +++ b/src/utils/screengrabber.cpp @@ -18,11 +18,11 @@ #include "screengrabber.h" #include "src/utils/filenamehandler.h" #include "src/utils/systemnotification.h" -#include -#include -#include #include #include +#include +#include +#include #if defined(Q_OS_LINUX) || defined(Q_OS_UNIX) #include @@ -30,97 +30,105 @@ #include #endif -ScreenGrabber::ScreenGrabber(QObject *parent) : QObject(parent) { +ScreenGrabber::ScreenGrabber(QObject* parent) + : QObject(parent) +{} -} - -QPixmap ScreenGrabber::grabEntireDesktop(bool &ok) { - ok = true; +QPixmap +ScreenGrabber::grabEntireDesktop(bool& ok) +{ + ok = true; #if defined(Q_OS_LINUX) || defined(Q_OS_UNIX) - if(m_info.waylandDectected()) { - QPixmap res; - // handle screenshot based on DE - switch (m_info.windowManager()) { - case DesktopInfo::GNOME: { - // https://github.com/GNOME/gnome-shell/blob/695bfb96160033be55cfb5ac41c121998f98c328/data/org.gnome.Shell.Screenshot.xml - QString path = FileNameHandler().generateAbsolutePath(QDir::tempPath()) + ".png"; - QDBusInterface gnomeInterface(QStringLiteral("org.gnome.Shell"), - QStringLiteral("/org/gnome/Shell/Screenshot"), - QStringLiteral("org.gnome.Shell.Screenshot")); - QDBusReply reply = gnomeInterface.call(QStringLiteral("Screenshot"), false, false, path); - if (reply.value()) { - res = QPixmap(path); - QFile dbusResult(path); - dbusResult.remove(); - } else { - ok = false; - } - break; - } case DesktopInfo::KDE: { - // https://github.com/KDE/spectacle/blob/517a7baf46a4ca0a45f32fd3f2b1b7210b180134/src/PlatformBackends/KWinWaylandImageGrabber.cpp#L145 - QDBusInterface kwinInterface(QStringLiteral("org.kde.KWin"), - QStringLiteral("/Screenshot"), - QStringLiteral("org.kde.kwin.Screenshot")); - QDBusReply reply = kwinInterface.call(QStringLiteral("screenshotFullscreen")); - res = QPixmap(reply.value()); - if (!res.isNull()) { - QFile dbusResult(reply.value()); - dbusResult.remove(); - } - break; - } default: - ok = false; - break; + if (m_info.waylandDectected()) { + QPixmap res; + // handle screenshot based on DE + switch (m_info.windowManager()) { + case DesktopInfo::GNOME: { + // https://github.com/GNOME/gnome-shell/blob/695bfb96160033be55cfb5ac41c121998f98c328/data/org.gnome.Shell.Screenshot.xml + QString path = + FileNameHandler().generateAbsolutePath(QDir::tempPath()) + ".png"; + QDBusInterface gnomeInterface( + QStringLiteral("org.gnome.Shell"), + QStringLiteral("/org/gnome/Shell/Screenshot"), + QStringLiteral("org.gnome.Shell.Screenshot")); + QDBusReply reply = + gnomeInterface.call(QStringLiteral("Screenshot"), false, false, path); + if (reply.value()) { + res = QPixmap(path); + QFile dbusResult(path); + dbusResult.remove(); + } else { + ok = false; } - if (!ok) { - SystemNotification().sendMessage(tr("Unable to capture screen")); + break; + } + case DesktopInfo::KDE: { + // https://github.com/KDE/spectacle/blob/517a7baf46a4ca0a45f32fd3f2b1b7210b180134/src/PlatformBackends/KWinWaylandImageGrabber.cpp#L145 + QDBusInterface kwinInterface(QStringLiteral("org.kde.KWin"), + QStringLiteral("/Screenshot"), + QStringLiteral("org.kde.kwin.Screenshot")); + QDBusReply reply = + kwinInterface.call(QStringLiteral("screenshotFullscreen")); + res = QPixmap(reply.value()); + if (!res.isNull()) { + QFile dbusResult(reply.value()); + dbusResult.remove(); } - return res; + break; + } + default: + ok = false; + break; } + if (!ok) { + SystemNotification().sendMessage(tr("Unable to capture screen")); + } + return res; + } #endif - QRect geometry; - for (QScreen *const screen : QGuiApplication::screens()) { - geometry = geometry.united(screen->geometry()); - } + QRect geometry; + for (QScreen* const screen : QGuiApplication::screens()) { + geometry = geometry.united(screen->geometry()); + } - QPixmap p(QApplication::primaryScreen()->grabWindow( - QApplication::desktop()->winId(), - geometry.x(), - geometry.y(), - geometry.width(), - geometry.height()) - ); - auto screenNumber = QApplication::desktop()->screenNumber(); - QScreen *screen = QApplication::screens()[screenNumber]; - p.setDevicePixelRatio(screen->devicePixelRatio()); - return p; + QPixmap p( + QApplication::primaryScreen()->grabWindow(QApplication::desktop()->winId(), + geometry.x(), + geometry.y(), + geometry.width(), + geometry.height())); + auto screenNumber = QApplication::desktop()->screenNumber(); + QScreen* screen = QApplication::screens()[screenNumber]; + p.setDevicePixelRatio(screen->devicePixelRatio()); + return p; } -QPixmap ScreenGrabber::grabScreen(int screenNumber, bool &ok) { - QPixmap p; - bool isVirtual = QApplication::desktop()->isVirtualDesktop(); - if (isVirtual || m_info.waylandDectected()) { - p = grabEntireDesktop(ok); - if (ok) { - QPoint topLeft(0, 0); +QPixmap +ScreenGrabber::grabScreen(int screenNumber, bool& ok) +{ + QPixmap p; + bool isVirtual = QApplication::desktop()->isVirtualDesktop(); + if (isVirtual || m_info.waylandDectected()) { + p = grabEntireDesktop(ok); + if (ok) { + QPoint topLeft(0, 0); #ifdef Q_OS_WIN - for (QScreen *const screen : QGuiApplication::screens()) { - QPoint topLeftScreen = screen->geometry().topLeft(); - if (topLeft.x() > topLeftScreen.x() || - topLeft.y() > topLeftScreen.y()) { - topLeft = topLeftScreen; - } - } -#endif - QRect geometry = QApplication::desktop()-> - screenGeometry(screenNumber); - geometry.moveTo(geometry.topLeft() - topLeft); - p = p.copy(geometry); + for (QScreen* const screen : QGuiApplication::screens()) { + QPoint topLeftScreen = screen->geometry().topLeft(); + if (topLeft.x() > topLeftScreen.x() || + topLeft.y() > topLeftScreen.y()) { + topLeft = topLeftScreen; } - } else { - p = QApplication::desktop()->screen(screenNumber)->grab(); - ok = true; + } +#endif + QRect geometry = QApplication::desktop()->screenGeometry(screenNumber); + geometry.moveTo(geometry.topLeft() - topLeft); + p = p.copy(geometry); } - return p; + } else { + p = QApplication::desktop()->screen(screenNumber)->grab(); + ok = true; + } + return p; } diff --git a/src/utils/screengrabber.h b/src/utils/screengrabber.h index eb40ee6d..dd0f116b 100644 --- a/src/utils/screengrabber.h +++ b/src/utils/screengrabber.h @@ -20,13 +20,14 @@ #include "src/utils/desktopinfo.h" #include -class ScreenGrabber : public QObject { - Q_OBJECT +class ScreenGrabber : public QObject +{ + Q_OBJECT public: - explicit ScreenGrabber(QObject *parent = nullptr); - QPixmap grabEntireDesktop(bool &ok); - QPixmap grabScreen(int screenNumber, bool &ok); + explicit ScreenGrabber(QObject* parent = nullptr); + QPixmap grabEntireDesktop(bool& ok); + QPixmap grabScreen(int screenNumber, bool& ok); private: - DesktopInfo m_info; + DesktopInfo m_info; }; diff --git a/src/utils/screenshotsaver.cpp b/src/utils/screenshotsaver.cpp index 6c9bd989..41615071 100644 --- a/src/utils/screenshotsaver.cpp +++ b/src/utils/screenshotsaver.cpp @@ -16,82 +16,84 @@ // along with Flameshot. If not, see . #include "screenshotsaver.h" -#include "src/utils/systemnotification.h" -#include "src/utils/filenamehandler.h" #include "src/utils/confighandler.h" -#include +#include "src/utils/filenamehandler.h" +#include "src/utils/systemnotification.h" #include -#include +#include #include #include +#include -ScreenshotSaver::ScreenshotSaver() { -} +ScreenshotSaver::ScreenshotSaver() {} -void ScreenshotSaver::saveToClipboard(const QPixmap &capture) { - SystemNotification().sendMessage( - QObject::tr("Capture saved to clipboard")); - QApplication::clipboard()->setPixmap(capture); -} - -bool ScreenshotSaver::saveToFilesystem(const QPixmap &capture, - const QString &path) +void +ScreenshotSaver::saveToClipboard(const QPixmap& capture) { - QString completePath = FileNameHandler().generateAbsolutePath(path); - completePath += QLatin1String(".png"); - bool ok = capture.save(completePath); - QString saveMessage; - QString notificationPath = completePath; + SystemNotification().sendMessage(QObject::tr("Capture saved to clipboard")); + QApplication::clipboard()->setPixmap(capture); +} + +bool +ScreenshotSaver::saveToFilesystem(const QPixmap& capture, const QString& path) +{ + QString completePath = FileNameHandler().generateAbsolutePath(path); + completePath += QLatin1String(".png"); + bool ok = capture.save(completePath); + QString saveMessage; + QString notificationPath = completePath; + + if (ok) { + ConfigHandler().setSavePath(path); + saveMessage = QObject::tr("Capture saved as ") + completePath; + } else { + saveMessage = QObject::tr("Error trying to save as ") + completePath; + notificationPath = ""; + } + + SystemNotification().sendMessage(saveMessage, notificationPath); + return ok; +} + +bool +ScreenshotSaver::saveToFilesystemGUI(const QPixmap& capture) +{ + bool ok = false; + + while (!ok) { + QString savePath = QFileDialog::getSaveFileName( + nullptr, + QString(), + FileNameHandler().absoluteSavePath() + ".png", + QLatin1String("Portable Network Graphic file (PNG) (*.png);;BMP file " + "(*.bmp);;JPEG file (*.jpg)")); + + if (savePath.isNull()) { + break; + } + + if (!savePath.endsWith(QLatin1String(".png"), Qt::CaseInsensitive) && + !savePath.endsWith(QLatin1String(".bmp"), Qt::CaseInsensitive) && + !savePath.endsWith(QLatin1String(".jpg"), Qt::CaseInsensitive)) { + + savePath += QLatin1String(".png"); + } + + ok = capture.save(savePath); if (ok) { - ConfigHandler().setSavePath(path); - saveMessage = QObject::tr("Capture saved as ") + completePath; + QString pathNoFile = + savePath.left(savePath.lastIndexOf(QLatin1String("/"))); + ConfigHandler().setSavePath(pathNoFile); + QString msg = QObject::tr("Capture saved as ") + savePath; + SystemNotification().sendMessage(msg, savePath); } else { - saveMessage = QObject::tr("Error trying to save as ") + completePath; - notificationPath = ""; + QString msg = QObject::tr("Error trying to save as ") + savePath; + QMessageBox saveErrBox( + QMessageBox::Warning, QObject::tr("Save Error"), msg); + saveErrBox.setWindowIcon(QIcon(":img/app/flameshot.svg")); + saveErrBox.exec(); } - - SystemNotification().sendMessage(saveMessage, notificationPath); - return ok; -} - -bool ScreenshotSaver::saveToFilesystemGUI(const QPixmap &capture) { - bool ok = false; - - while (!ok) { - QString savePath = QFileDialog::getSaveFileName( - nullptr, - QString(), - FileNameHandler().absoluteSavePath() + ".png", - QLatin1String("Portable Network Graphic file (PNG) (*.png);;BMP file (*.bmp);;JPEG file (*.jpg)")); - - if (savePath.isNull()) { - break; - } - - if (!savePath.endsWith(QLatin1String(".png"), Qt::CaseInsensitive) && - !savePath.endsWith(QLatin1String(".bmp"), Qt::CaseInsensitive) && - !savePath.endsWith(QLatin1String(".jpg"), Qt::CaseInsensitive)) { - - savePath += QLatin1String(".png"); - } - - ok = capture.save(savePath); - - if (ok) { - QString pathNoFile = savePath.left(savePath.lastIndexOf(QLatin1String("/"))); - ConfigHandler().setSavePath(pathNoFile); - QString msg = QObject::tr("Capture saved as ") + savePath; - SystemNotification().sendMessage(msg, savePath); - } else { - QString msg = QObject::tr("Error trying to save as ") + savePath; - QMessageBox saveErrBox( - QMessageBox::Warning, - QObject::tr("Save Error"), - msg); - saveErrBox.setWindowIcon(QIcon(":img/app/flameshot.svg")); - saveErrBox.exec(); - } - } - return ok; + } + return ok; } diff --git a/src/utils/screenshotsaver.h b/src/utils/screenshotsaver.h index 0455cde3..fdab15de 100644 --- a/src/utils/screenshotsaver.h +++ b/src/utils/screenshotsaver.h @@ -20,12 +20,12 @@ class QPixmap; class QString; -class ScreenshotSaver { +class ScreenshotSaver +{ public: - ScreenshotSaver(); - - void saveToClipboard(const QPixmap &capture); - bool saveToFilesystem(const QPixmap &capture, const QString &path); - bool saveToFilesystemGUI(const QPixmap &capture); + ScreenshotSaver(); + void saveToClipboard(const QPixmap& capture); + bool saveToFilesystem(const QPixmap& capture, const QString& path); + bool saveToFilesystemGUI(const QPixmap& capture); }; diff --git a/src/utils/systemnotification.cpp b/src/utils/systemnotification.cpp index 41a549d2..d583f438 100644 --- a/src/utils/systemnotification.cpp +++ b/src/utils/systemnotification.cpp @@ -5,59 +5,68 @@ #ifndef Q_OS_WIN #include -#include #include +#include #else #endif #include "src/core/controller.h" #if defined(Q_OS_LINUX) || defined(Q_OS_UNIX) -SystemNotification::SystemNotification(QObject *parent) : QObject(parent) { - m_interface = new QDBusInterface(QStringLiteral("org.freedesktop.Notifications"), - QStringLiteral("/org/freedesktop/Notifications"), - QStringLiteral("org.freedesktop.Notifications"), - QDBusConnection::sessionBus(), - this); +SystemNotification::SystemNotification(QObject* parent) + : QObject(parent) +{ + m_interface = + new QDBusInterface(QStringLiteral("org.freedesktop.Notifications"), + QStringLiteral("/org/freedesktop/Notifications"), + QStringLiteral("org.freedesktop.Notifications"), + QDBusConnection::sessionBus(), + this); } #else -SystemNotification::SystemNotification(QObject *parent) : QObject(parent) { - m_interface = nullptr; +SystemNotification::SystemNotification(QObject* parent) + : QObject(parent) +{ + m_interface = nullptr; } #endif -void SystemNotification::sendMessage(const QString &text, const QString &savePath) { - sendMessage(text, tr("Flameshot Info"), savePath); +void +SystemNotification::sendMessage(const QString& text, const QString& savePath) +{ + sendMessage(text, tr("Flameshot Info"), savePath); } -void SystemNotification::sendMessage( - const QString &text, - const QString &title, - const QString &savePath, - const int timeout) +void +SystemNotification::sendMessage(const QString& text, + const QString& title, + const QString& savePath, + const int timeout) { - if(!ConfigHandler().desktopNotificationValue()) { - return; - } + if (!ConfigHandler().desktopNotificationValue()) { + return; + } #ifndef Q_OS_WIN - QList args; - QVariantMap hintsMap; - if (!savePath.isEmpty()) { - QUrl fullPath = QUrl::fromLocalFile(savePath); - // allows the notification to be dragged and dropped - hintsMap[QStringLiteral("x-kde-urls")] = QStringList({fullPath.toString()}); - } - args << (qAppName()) //appname - << static_cast(0) //id - << "flameshot" //icon - << title //summary - << text //body - << QStringList() //actions - << hintsMap //hints - << timeout; //timeout - m_interface->callWithArgumentList(QDBus::AutoDetect, QStringLiteral("Notify"), args); + QList args; + QVariantMap hintsMap; + if (!savePath.isEmpty()) { + QUrl fullPath = QUrl::fromLocalFile(savePath); + // allows the notification to be dragged and dropped + hintsMap[QStringLiteral("x-kde-urls")] = + QStringList({ fullPath.toString() }); + } + args << (qAppName()) // appname + << static_cast(0) // id + << "flameshot" // icon + << title // summary + << text // body + << QStringList() // actions + << hintsMap // hints + << timeout; // timeout + m_interface->callWithArgumentList( + QDBus::AutoDetect, QStringLiteral("Notify"), args); #else - auto c = Controller::getInstance(); - c->sendTrayNotification(text, title, timeout); + auto c = Controller::getInstance(); + c->sendTrayNotification(text, title, timeout); #endif } diff --git a/src/utils/systemnotification.h b/src/utils/systemnotification.h index b018246b..171c1349 100644 --- a/src/utils/systemnotification.h +++ b/src/utils/systemnotification.h @@ -21,19 +21,19 @@ class QDBusInterface; -class SystemNotification : public QObject { - Q_OBJECT +class SystemNotification : public QObject +{ + Q_OBJECT public: - explicit SystemNotification(QObject *parent = nullptr); + explicit SystemNotification(QObject* parent = nullptr); - void sendMessage(const QString &text, - const QString &savePath = {}); + void sendMessage(const QString& text, const QString& savePath = {}); - void sendMessage(const QString &text, - const QString &title, - const QString &savePath, - const int timeout = 5000); + void sendMessage(const QString& text, + const QString& title, + const QString& savePath, + const int timeout = 5000); private: - QDBusInterface *m_interface; + QDBusInterface* m_interface; }; diff --git a/src/utils/waylandutils.cpp b/src/utils/waylandutils.cpp index d06f5479..f0932472 100644 --- a/src/utils/waylandutils.cpp +++ b/src/utils/waylandutils.cpp @@ -1,10 +1,7 @@ #include "waylandutils.h" -WaylandUtils::WaylandUtils() -{ +WaylandUtils::WaylandUtils() {} -} - -bool WaylandUtils::waylandDetected() { - -} +bool +WaylandUtils::waylandDetected() +{} diff --git a/src/utils/waylandutils.h b/src/utils/waylandutils.h index 2811759c..f6e77658 100644 --- a/src/utils/waylandutils.h +++ b/src/utils/waylandutils.h @@ -1,16 +1,14 @@ #ifndef WAYLANDUTILS_H #define WAYLANDUTILS_H - class WaylandUtils { public: - WaylandUtils(); + WaylandUtils(); - static bool waylandDetected(); + static bool waylandDetected(); private: - }; #endif // WAYLANDUTILS_H diff --git a/src/widgets/capture/buttonhandler.cpp b/src/widgets/capture/buttonhandler.cpp index 95a37e32..916e029a 100644 --- a/src/widgets/capture/buttonhandler.cpp +++ b/src/widgets/capture/buttonhandler.cpp @@ -17,357 +17,396 @@ #include "buttonhandler.h" #include "src/utils/globalvalues.h" -#include #include +#include #include // ButtonHandler is a habdler for every active button. It makes easier to // manipulate the buttons as a unit. -ButtonHandler::ButtonHandler(const QVector &v, - QObject *parent) : - QObject(parent) +ButtonHandler::ButtonHandler(const QVector& v, QObject* parent) + : QObject(parent) { - setButtons(v); - init(); + setButtons(v); + init(); } -ButtonHandler::ButtonHandler(QObject *parent) : - QObject(parent) +ButtonHandler::ButtonHandler(QObject* parent) + : QObject(parent) { - init(); + init(); } -void ButtonHandler::hide() { - for (CaptureButton *b: m_vectorButtons) - b->hide(); +void +ButtonHandler::hide() +{ + for (CaptureButton* b : m_vectorButtons) + b->hide(); } -void ButtonHandler::show() { - if (m_vectorButtons.isEmpty() || m_vectorButtons.first()->isVisible()) { - return; +void +ButtonHandler::show() +{ + if (m_vectorButtons.isEmpty() || m_vectorButtons.first()->isVisible()) { + return; + } + for (CaptureButton* b : m_vectorButtons) + b->animatedShow(); +} + +bool +ButtonHandler::isVisible() const +{ + bool ret = true; + for (const CaptureButton* b : m_vectorButtons) { + if (!b->isVisible()) { + ret = false; + break; } - for (CaptureButton *b: m_vectorButtons) - b->animatedShow(); + } + return ret; } -bool ButtonHandler::isVisible() const { - bool ret = true; - for (const CaptureButton *b: m_vectorButtons) { - if (!b->isVisible()) { - ret = false; - break; - } - } - return ret; +bool +ButtonHandler::buttonsAreInside() const +{ + return m_buttonsAreInside; } -bool ButtonHandler::buttonsAreInside() const { - return m_buttonsAreInside; -} - -size_t ButtonHandler::size() const { - return m_vectorButtons.size(); +size_t +ButtonHandler::size() const +{ + return m_vectorButtons.size(); } // updatePosition updates the position of the buttons around the // selection area. Ignores the sides blocked by the end of the screen. // When the selection is too small it works on a virtual selection with // the original in the center. -void ButtonHandler::updatePosition(const QRect &selection) { - resetRegionTrack(); - const int vecLength = m_vectorButtons.size(); - if (vecLength == 0) { - return; +void +ButtonHandler::updatePosition(const QRect& selection) +{ + resetRegionTrack(); + const int vecLength = m_vectorButtons.size(); + if (vecLength == 0) { + return; + } + // Copy of the selection area for internal modifications + m_selection = intersectWithAreas(selection); + updateBlockedSides(); + ensureSelectionMinimunSize(); + // Indicates the actual button to be moved + int elemIndicator = 0; + + while (elemIndicator < vecLength) { + + // Add them inside the area when there is no more space + if (m_allSidesBlocked) { + m_selection = selection; + positionButtonsInside(elemIndicator); + break; // the while + } + // Number of buttons per row column + int buttonsPerRow = + (m_selection.width() + m_separator) / (m_buttonExtendedSize); + int buttonsPerCol = + (m_selection.height() + m_separator) / (m_buttonExtendedSize); + // Buttons to be placed in the corners + int extraButtons = + (vecLength - elemIndicator) - (buttonsPerRow + buttonsPerCol) * 2; + int elemsAtCorners = extraButtons > 4 ? 4 : extraButtons; + int maxExtra = 2; + if (m_oneHorizontalBlocked) { + maxExtra = 1; + } else if (m_horizontalyBlocked) { + maxExtra = 0; + } + int elemCornersTop = qBound(0, elemsAtCorners, maxExtra); + elemsAtCorners -= elemCornersTop; + int elemCornersBotton = qBound(0, elemsAtCorners, maxExtra); + + // Add buttons at the button of the seletion + if (!m_blockedBotton) { + int addCounter = buttonsPerRow + elemCornersBotton; + // Don't add more than we have + addCounter = qBound(0, addCounter, vecLength - elemIndicator); + QPoint center = + QPoint(m_selection.center().x(), m_selection.bottom() + m_separator); + if (addCounter > buttonsPerRow) { + adjustHorizontalCenter(center); + } + // ElemIndicator, elemsAtCorners + QVector positions = horizontalPoints(center, addCounter, true); + moveButtonsToPoints(positions, elemIndicator); + } + // Add buttons at the right side of the seletion + if (!m_blockedRight && elemIndicator < vecLength) { + int addCounter = buttonsPerCol; + addCounter = qBound(0, addCounter, vecLength - elemIndicator); + + QPoint center = + QPoint(m_selection.right() + m_separator, m_selection.center().y()); + QVector positions = verticalPoints(center, addCounter, false); + moveButtonsToPoints(positions, elemIndicator); + } + // Add buttons at the top of the seletion + if (!m_blockedTop && elemIndicator < vecLength) { + int addCounter = buttonsPerRow + elemCornersTop; + addCounter = qBound(0, addCounter, vecLength - elemIndicator); + QPoint center = QPoint(m_selection.center().x(), + m_selection.top() - m_buttonExtendedSize); + if (addCounter == 1 + buttonsPerRow) { + adjustHorizontalCenter(center); + } + QVector positions = horizontalPoints(center, addCounter, false); + moveButtonsToPoints(positions, elemIndicator); + } + // Add buttons at the left side of the seletion + if (!m_blockedLeft && elemIndicator < vecLength) { + int addCounter = buttonsPerCol; + addCounter = qBound(0, addCounter, vecLength - elemIndicator); + + QPoint center = QPoint(m_selection.left() - m_buttonExtendedSize, + m_selection.center().y()); + QVector positions = verticalPoints(center, addCounter, true); + moveButtonsToPoints(positions, elemIndicator); + } + // If there are elements for the next cycle, increase the size of the + // base area + if (elemIndicator < vecLength && !(m_allSidesBlocked)) { + expandSelection(); } - // Copy of the selection area for internal modifications - m_selection = intersectWithAreas(selection); updateBlockedSides(); - ensureSelectionMinimunSize(); - // Indicates the actual button to be moved - int elemIndicator = 0; - - while (elemIndicator < vecLength) { - - // Add them inside the area when there is no more space - if (m_allSidesBlocked) { - m_selection = selection; - positionButtonsInside(elemIndicator); - break; // the while - } - // Number of buttons per row column - int buttonsPerRow = (m_selection.width() + m_separator) / (m_buttonExtendedSize); - int buttonsPerCol = (m_selection.height() + m_separator) / (m_buttonExtendedSize); - // Buttons to be placed in the corners - int extraButtons = (vecLength - elemIndicator) - - (buttonsPerRow + buttonsPerCol) * 2; - int elemsAtCorners = extraButtons > 4 ? 4 : extraButtons; - int maxExtra = 2; - if (m_oneHorizontalBlocked) { - maxExtra = 1; - } else if (m_horizontalyBlocked) { - maxExtra = 0; - } - int elemCornersTop = qBound(0, elemsAtCorners, maxExtra); - elemsAtCorners -= elemCornersTop; - int elemCornersBotton = qBound(0, elemsAtCorners, maxExtra); - - // Add buttons at the button of the seletion - if (!m_blockedBotton) { - int addCounter = buttonsPerRow + elemCornersBotton; - // Don't add more than we have - addCounter = qBound(0, addCounter, vecLength - elemIndicator); - QPoint center = QPoint(m_selection.center().x(), - m_selection.bottom() + m_separator); - if (addCounter > buttonsPerRow) { - adjustHorizontalCenter(center); - } - // ElemIndicator, elemsAtCorners - QVector positions = horizontalPoints(center, addCounter, true); - moveButtonsToPoints(positions, elemIndicator); - } - // Add buttons at the right side of the seletion - if (!m_blockedRight && elemIndicator < vecLength) { - int addCounter = buttonsPerCol; - addCounter = qBound(0, addCounter, vecLength - elemIndicator); - - QPoint center = QPoint(m_selection.right() + m_separator, - m_selection.center().y()); - QVector positions = verticalPoints(center, addCounter, false); - moveButtonsToPoints(positions, elemIndicator); - } - // Add buttons at the top of the seletion - if (!m_blockedTop && elemIndicator < vecLength) { - int addCounter = buttonsPerRow + elemCornersTop; - addCounter = qBound(0, addCounter, vecLength - elemIndicator); - QPoint center = QPoint(m_selection.center().x(), - m_selection.top() - m_buttonExtendedSize); - if (addCounter == 1 + buttonsPerRow) { - adjustHorizontalCenter(center); - } - QVector positions = horizontalPoints(center, addCounter, false); - moveButtonsToPoints(positions, elemIndicator); - } - // Add buttons at the left side of the seletion - if (!m_blockedLeft && elemIndicator < vecLength) { - int addCounter = buttonsPerCol; - addCounter = qBound(0, addCounter, vecLength - elemIndicator); - - QPoint center = QPoint(m_selection.left() - m_buttonExtendedSize, - m_selection.center().y()); - QVector positions = verticalPoints(center, addCounter, true); - moveButtonsToPoints(positions, elemIndicator); - } - // If there are elements for the next cycle, increase the size of the - // base area - if (elemIndicator < vecLength && !(m_allSidesBlocked)) { - expandSelection(); - } - updateBlockedSides(); - } + } } // horizontalPoints is an auxiliary method for the button position computation. // starts from a known center and keeps adding elements horizontally // and returns the computed positions. -QVector ButtonHandler::horizontalPoints( - const QPoint ¢er, const int elements, const bool leftToRight) const +QVector +ButtonHandler::horizontalPoints(const QPoint& center, + const int elements, + const bool leftToRight) const { - QVector res; - // Distance from the center to start adding buttons - int shift = 0; - if (elements % 2 == 0) { - shift = m_buttonExtendedSize * (elements / 2) - (m_separator / 2); - } else { - shift = m_buttonExtendedSize * ((elements-1) / 2) + m_buttonBaseSize / 2; - } - if (!leftToRight) { shift -= m_buttonBaseSize; } - int x = leftToRight ? center.x() - shift : - center.x() + shift; - QPoint i(x, center.y()); - while (elements > res.length()) { - res.append(i); - leftToRight ? i.setX(i.x() + m_buttonExtendedSize) : - i.setX(i.x() - m_buttonExtendedSize); - } - return res; + QVector res; + // Distance from the center to start adding buttons + int shift = 0; + if (elements % 2 == 0) { + shift = m_buttonExtendedSize * (elements / 2) - (m_separator / 2); + } else { + shift = m_buttonExtendedSize * ((elements - 1) / 2) + m_buttonBaseSize / 2; + } + if (!leftToRight) { + shift -= m_buttonBaseSize; + } + int x = leftToRight ? center.x() - shift : center.x() + shift; + QPoint i(x, center.y()); + while (elements > res.length()) { + res.append(i); + leftToRight ? i.setX(i.x() + m_buttonExtendedSize) + : i.setX(i.x() - m_buttonExtendedSize); + } + return res; } // verticalPoints is an auxiliary method for the button position computation. // starts from a known center and keeps adding elements vertically // and returns the computed positions. -QVector ButtonHandler::verticalPoints( - const QPoint ¢er, const int elements, const bool upToDown) const +QVector +ButtonHandler::verticalPoints(const QPoint& center, + const int elements, + const bool upToDown) const { - QVector res; - // Distance from the center to start adding buttons - int shift = 0; - if (elements % 2 == 0) { - shift = m_buttonExtendedSize * (elements / 2) - (m_separator / 2); - } else { - shift = m_buttonExtendedSize * ((elements-1) / 2) + m_buttonBaseSize / 2; - } - if (!upToDown) { shift -= m_buttonBaseSize; } - int y = upToDown ? center.y() - shift : - center.y() + shift; - QPoint i(center.x(), y); - while (elements > res.length()) { - res.append(i); - upToDown ? i.setY(i.y() + m_buttonExtendedSize) : - i.setY(i.y() - m_buttonExtendedSize); - } - return res; + QVector res; + // Distance from the center to start adding buttons + int shift = 0; + if (elements % 2 == 0) { + shift = m_buttonExtendedSize * (elements / 2) - (m_separator / 2); + } else { + shift = m_buttonExtendedSize * ((elements - 1) / 2) + m_buttonBaseSize / 2; + } + if (!upToDown) { + shift -= m_buttonBaseSize; + } + int y = upToDown ? center.y() - shift : center.y() + shift; + QPoint i(center.x(), y); + while (elements > res.length()) { + res.append(i); + upToDown ? i.setY(i.y() + m_buttonExtendedSize) + : i.setY(i.y() - m_buttonExtendedSize); + } + return res; } -QRect ButtonHandler::intersectWithAreas(const QRect &rect) { - QRect res; - for(const QRect &r : m_screenRegions) { - QRect temp = rect.intersected(r); - if (temp.height() * temp.width() > res.height() * res.width()) { - res = temp; - } - } - return res; -} - -void ButtonHandler::init() { - m_separator = GlobalValues::buttonBaseSize() / 4; -} - -void ButtonHandler::resetRegionTrack() { - m_buttonsAreInside = false; -} - -void ButtonHandler::updateBlockedSides() { - const int EXTENSION = m_separator * 2 + m_buttonBaseSize; - // Right - QPoint pointA(m_selection.right() + EXTENSION, - m_selection.bottom()); - QPoint pointB(pointA.x(), - m_selection.top()); - m_blockedRight = !(m_screenRegions.contains(pointA) && - m_screenRegions.contains(pointB)); - // Left - pointA.setX(m_selection.left() - EXTENSION); - pointB.setX(pointA.x()); - m_blockedLeft = !(m_screenRegions.contains(pointA) && - m_screenRegions.contains(pointB)); - // Bottom - pointA = QPoint(m_selection.left(), - m_selection.bottom() + EXTENSION); - pointB = QPoint(m_selection.right(), - pointA.y()); - m_blockedBotton = !(m_screenRegions.contains(pointA) && - m_screenRegions.contains(pointB)); - // Top - pointA.setY(m_selection.top() - EXTENSION); - pointB.setY(pointA.y()); - m_blockedTop = !(m_screenRegions.contains(pointA) && - m_screenRegions.contains(pointB)); - // Auxiliary - m_oneHorizontalBlocked = (!m_blockedRight && m_blockedLeft) || - (m_blockedRight && !m_blockedLeft); - m_horizontalyBlocked = (m_blockedRight && m_blockedLeft); - m_allSidesBlocked = (m_blockedBotton && m_horizontalyBlocked && m_blockedTop); -} - -void ButtonHandler::expandSelection() { - int &s = m_buttonExtendedSize; - m_selection = m_selection + QMargins(s, s, s, s); - m_selection = intersectWithAreas(m_selection); -} - -void ButtonHandler::positionButtonsInside(int index) { - // Position the buttons in the botton-center of the main but inside of the - // selection. - QRect mainArea = m_selection; - mainArea = intersectWithAreas(mainArea); - const int buttonsPerRow = (mainArea.width()) / (m_buttonExtendedSize); - if (buttonsPerRow == 0) { - return; - } - QPoint center = QPoint(mainArea.center().x(), - mainArea.bottom() - m_buttonExtendedSize); - - while (m_vectorButtons.size() > index) { - int addCounter = buttonsPerRow; - addCounter = qBound(0, addCounter, m_vectorButtons.size() - index); - QVector positions = horizontalPoints(center, addCounter, true); - moveButtonsToPoints(positions, index); - center.setY(center.y() - m_buttonExtendedSize); - } - - m_buttonsAreInside = true; -} - -void ButtonHandler::ensureSelectionMinimunSize() { - // Detect if a side is smaller than a button in order to prevent collision - // and redimension the base area the the base size of a single button per side - if (m_selection.width() < m_buttonBaseSize) { - if (!m_blockedLeft) { - m_selection.setX(m_selection.x() - - (m_buttonBaseSize-m_selection.width()) / 2); - } - m_selection.setWidth(m_buttonBaseSize); - } - if (m_selection.height() < m_buttonBaseSize) { - if (!m_blockedTop) { - m_selection.setY(m_selection.y() - - (m_buttonBaseSize-m_selection.height()) / 2); - } - m_selection.setHeight(m_buttonBaseSize); - } -} - -void ButtonHandler::moveButtonsToPoints( - const QVector &points, int &index) +QRect +ButtonHandler::intersectWithAreas(const QRect& rect) { - for (const QPoint &p: points) { - auto button = m_vectorButtons[index]; - button->move(p); - ++index; + QRect res; + for (const QRect& r : m_screenRegions) { + QRect temp = rect.intersected(r); + if (temp.height() * temp.width() > res.height() * res.width()) { + res = temp; } + } + return res; } -void ButtonHandler::adjustHorizontalCenter(QPoint ¢er) { - if (m_blockedLeft) { - center.setX(center.x() + m_buttonExtendedSize/2); - } else if (m_blockedRight) { - center.setX(center.x() - m_buttonExtendedSize/2); +void +ButtonHandler::init() +{ + m_separator = GlobalValues::buttonBaseSize() / 4; +} + +void +ButtonHandler::resetRegionTrack() +{ + m_buttonsAreInside = false; +} + +void +ButtonHandler::updateBlockedSides() +{ + const int EXTENSION = m_separator * 2 + m_buttonBaseSize; + // Right + QPoint pointA(m_selection.right() + EXTENSION, m_selection.bottom()); + QPoint pointB(pointA.x(), m_selection.top()); + m_blockedRight = + !(m_screenRegions.contains(pointA) && m_screenRegions.contains(pointB)); + // Left + pointA.setX(m_selection.left() - EXTENSION); + pointB.setX(pointA.x()); + m_blockedLeft = + !(m_screenRegions.contains(pointA) && m_screenRegions.contains(pointB)); + // Bottom + pointA = QPoint(m_selection.left(), m_selection.bottom() + EXTENSION); + pointB = QPoint(m_selection.right(), pointA.y()); + m_blockedBotton = + !(m_screenRegions.contains(pointA) && m_screenRegions.contains(pointB)); + // Top + pointA.setY(m_selection.top() - EXTENSION); + pointB.setY(pointA.y()); + m_blockedTop = + !(m_screenRegions.contains(pointA) && m_screenRegions.contains(pointB)); + // Auxiliary + m_oneHorizontalBlocked = + (!m_blockedRight && m_blockedLeft) || (m_blockedRight && !m_blockedLeft); + m_horizontalyBlocked = (m_blockedRight && m_blockedLeft); + m_allSidesBlocked = (m_blockedBotton && m_horizontalyBlocked && m_blockedTop); +} + +void +ButtonHandler::expandSelection() +{ + int& s = m_buttonExtendedSize; + m_selection = m_selection + QMargins(s, s, s, s); + m_selection = intersectWithAreas(m_selection); +} + +void +ButtonHandler::positionButtonsInside(int index) +{ + // Position the buttons in the botton-center of the main but inside of the + // selection. + QRect mainArea = m_selection; + mainArea = intersectWithAreas(mainArea); + const int buttonsPerRow = (mainArea.width()) / (m_buttonExtendedSize); + if (buttonsPerRow == 0) { + return; + } + QPoint center = + QPoint(mainArea.center().x(), mainArea.bottom() - m_buttonExtendedSize); + + while (m_vectorButtons.size() > index) { + int addCounter = buttonsPerRow; + addCounter = qBound(0, addCounter, m_vectorButtons.size() - index); + QVector positions = horizontalPoints(center, addCounter, true); + moveButtonsToPoints(positions, index); + center.setY(center.y() - m_buttonExtendedSize); + } + + m_buttonsAreInside = true; +} + +void +ButtonHandler::ensureSelectionMinimunSize() +{ + // Detect if a side is smaller than a button in order to prevent collision + // and redimension the base area the the base size of a single button per side + if (m_selection.width() < m_buttonBaseSize) { + if (!m_blockedLeft) { + m_selection.setX(m_selection.x() - + (m_buttonBaseSize - m_selection.width()) / 2); } + m_selection.setWidth(m_buttonBaseSize); + } + if (m_selection.height() < m_buttonBaseSize) { + if (!m_blockedTop) { + m_selection.setY(m_selection.y() - + (m_buttonBaseSize - m_selection.height()) / 2); + } + m_selection.setHeight(m_buttonBaseSize); + } +} + +void +ButtonHandler::moveButtonsToPoints(const QVector& points, int& index) +{ + for (const QPoint& p : points) { + auto button = m_vectorButtons[index]; + button->move(p); + ++index; + } +} + +void +ButtonHandler::adjustHorizontalCenter(QPoint& center) +{ + if (m_blockedLeft) { + center.setX(center.x() + m_buttonExtendedSize / 2); + } else if (m_blockedRight) { + center.setX(center.x() - m_buttonExtendedSize / 2); + } } // setButtons redefines the buttons of the button handler -void ButtonHandler::setButtons(const QVector v) { - if (v.isEmpty()) - return; +void +ButtonHandler::setButtons(const QVector v) +{ + if (v.isEmpty()) + return; - for (CaptureButton *b: m_vectorButtons) - delete(b); - m_vectorButtons = v; - m_buttonBaseSize = GlobalValues::buttonBaseSize(); - m_buttonExtendedSize = m_buttonBaseSize + m_separator; + for (CaptureButton* b : m_vectorButtons) + delete (b); + m_vectorButtons = v; + m_buttonBaseSize = GlobalValues::buttonBaseSize(); + m_buttonExtendedSize = m_buttonBaseSize + m_separator; } -bool ButtonHandler::contains(const QPoint &p) const { - QPoint first(m_vectorButtons.first()->pos()); - QPoint last(m_vectorButtons.last()->pos()); - bool firstIsTopLeft = (first.x() <= last.x() && first.y() <= last.y()); - QPoint topLeft = firstIsTopLeft ? first : last; - QPoint bottonRight = firstIsTopLeft ? last : first; - topLeft += QPoint(-m_separator, -m_separator); - bottonRight += QPoint(m_buttonExtendedSize, m_buttonExtendedSize); - QRegion r(QRect(topLeft, bottonRight).normalized()); - return r.contains(p); +bool +ButtonHandler::contains(const QPoint& p) const +{ + QPoint first(m_vectorButtons.first()->pos()); + QPoint last(m_vectorButtons.last()->pos()); + bool firstIsTopLeft = (first.x() <= last.x() && first.y() <= last.y()); + QPoint topLeft = firstIsTopLeft ? first : last; + QPoint bottonRight = firstIsTopLeft ? last : first; + topLeft += QPoint(-m_separator, -m_separator); + bottonRight += QPoint(m_buttonExtendedSize, m_buttonExtendedSize); + QRegion r(QRect(topLeft, bottonRight).normalized()); + return r.contains(p); } -void ButtonHandler::updateScreenRegions(const QVector &rects) { - m_screenRegions = QRegion(); - for (const QRect &rect: rects) { - m_screenRegions += rect; - } +void +ButtonHandler::updateScreenRegions(const QVector& rects) +{ + m_screenRegions = QRegion(); + for (const QRect& rect : rects) { + m_screenRegions += rect; + } } -void ButtonHandler::updateScreenRegions(const QRect &rect) { - m_screenRegions = QRegion(rect); +void +ButtonHandler::updateScreenRegions(const QRect& rect) +{ + m_screenRegions = QRegion(rect); } diff --git a/src/widgets/capture/buttonhandler.h b/src/widgets/capture/buttonhandler.h index 9efd8bdb..48c15e06 100644 --- a/src/widgets/capture/buttonhandler.h +++ b/src/widgets/capture/buttonhandler.h @@ -18,70 +18,73 @@ #pragma once #include "capturebutton.h" -#include #include #include +#include class CaptureButton; class QRect; class QPoint; -class ButtonHandler : public QObject { - Q_OBJECT +class ButtonHandler : public QObject +{ + Q_OBJECT public: - ButtonHandler(const QVector&, QObject *parent = nullptr); - explicit ButtonHandler(QObject *parent = nullptr); + ButtonHandler(const QVector&, QObject* parent = nullptr); + explicit ButtonHandler(QObject* parent = nullptr); - void hideSectionUnderMouse(const QPoint &p); + void hideSectionUnderMouse(const QPoint& p); - bool isVisible() const; - bool buttonsAreInside() const; - size_t size() const; + bool isVisible() const; + bool buttonsAreInside() const; + size_t size() const; - void setButtons(const QVector); - bool contains(const QPoint &p) const; - void updateScreenRegions(const QVector &rects); - void updateScreenRegions(const QRect &rect); + void setButtons(const QVector); + bool contains(const QPoint& p) const; + void updateScreenRegions(const QVector& rects); + void updateScreenRegions(const QRect& rect); public slots: - void updatePosition(const QRect &selection); - void hide(); - void show(); + void updatePosition(const QRect& selection); + void hide(); + void show(); private: - QVector horizontalPoints(const QPoint ¢er, const int elements, - const bool leftToRight) const; - QVector verticalPoints(const QPoint ¢er, const int elements, - const bool upToDown) const; + QVector horizontalPoints(const QPoint& center, + const int elements, + const bool leftToRight) const; + QVector verticalPoints(const QPoint& center, + const int elements, + const bool upToDown) const; - QRect intersectWithAreas(const QRect &rect); + QRect intersectWithAreas(const QRect& rect); - QVector m_vectorButtons; + QVector m_vectorButtons; - QRegion m_screenRegions; + QRegion m_screenRegions; - QRect m_selection; + QRect m_selection; - int m_separator; - int m_buttonExtendedSize; - int m_buttonBaseSize; + int m_separator; + int m_buttonExtendedSize; + int m_buttonBaseSize; - bool m_buttonsAreInside; - bool m_blockedRight; - bool m_blockedLeft; - bool m_blockedBotton; - bool m_blockedTop; - bool m_oneHorizontalBlocked; - bool m_horizontalyBlocked; - bool m_allSidesBlocked; + bool m_buttonsAreInside; + bool m_blockedRight; + bool m_blockedLeft; + bool m_blockedBotton; + bool m_blockedTop; + bool m_oneHorizontalBlocked; + bool m_horizontalyBlocked; + bool m_allSidesBlocked; - // aux methods - void init(); - void resetRegionTrack(); - void updateBlockedSides(); - void expandSelection(); - void positionButtonsInside(int index); - void ensureSelectionMinimunSize(); - void moveButtonsToPoints(const QVector &points, int &index); - void adjustHorizontalCenter(QPoint ¢er); + // aux methods + void init(); + void resetRegionTrack(); + void updateBlockedSides(); + void expandSelection(); + void positionButtonsInside(int index); + void ensureSelectionMinimunSize(); + void moveButtonsToPoints(const QVector& points, int& index); + void adjustHorizontalCenter(QPoint& center); }; diff --git a/src/widgets/capture/capturebutton.cpp b/src/widgets/capture/capturebutton.cpp index 8dde6768..4f550b5b 100644 --- a/src/widgets/capture/capturebutton.cpp +++ b/src/widgets/capture/capturebutton.cpp @@ -16,183 +16,201 @@ // along with Flameshot. If not, see . #include "capturebutton.h" -#include "src/widgets/capture/capturewidget.h" -#include "src/utils/confighandler.h" #include "src/tools/capturetool.h" #include "src/tools/toolfactory.h" -#include "src/utils/globalvalues.h" #include "src/utils/colorutils.h" +#include "src/utils/confighandler.h" +#include "src/utils/globalvalues.h" +#include "src/widgets/capture/capturewidget.h" +#include +#include #include +#include #include #include -#include -#include -#include // Button represents a single button of the capture widget, it can enable // multiple functionality. -CaptureButton::CaptureButton(const ButtonType t, QWidget *parent) : QPushButton(parent), - m_buttonType(t) +CaptureButton::CaptureButton(const ButtonType t, QWidget* parent) + : QPushButton(parent) + , m_buttonType(t) { - initButton(); - if (t == TYPE_SELECTIONINDICATOR) { - QFont f = this->font(); - setFont(QFont(f.family(), 7, QFont::Bold)); - } else { - updateIcon(); - } - setCursor(Qt::ArrowCursor); + initButton(); + if (t == TYPE_SELECTIONINDICATOR) { + QFont f = this->font(); + setFont(QFont(f.family(), 7, QFont::Bold)); + } else { + updateIcon(); + } + setCursor(Qt::ArrowCursor); } -void CaptureButton::initButton() { - m_tool = ToolFactory().CreateTool(m_buttonType, this); +void +CaptureButton::initButton() +{ + m_tool = ToolFactory().CreateTool(m_buttonType, this); - setFocusPolicy(Qt::NoFocus); - resize(GlobalValues::buttonBaseSize(), GlobalValues::buttonBaseSize()); - setMask(QRegion(QRect(-1,-1, GlobalValues::buttonBaseSize()+2, - GlobalValues::buttonBaseSize()+2), - QRegion::Ellipse)); + setFocusPolicy(Qt::NoFocus); + resize(GlobalValues::buttonBaseSize(), GlobalValues::buttonBaseSize()); + setMask(QRegion(QRect(-1, + -1, + GlobalValues::buttonBaseSize() + 2, + GlobalValues::buttonBaseSize() + 2), + QRegion::Ellipse)); - setToolTip(m_tool->description()); + setToolTip(m_tool->description()); - m_emergeAnimation = new QPropertyAnimation(this, "size", this); - m_emergeAnimation->setEasingCurve(QEasingCurve::InOutQuad); - m_emergeAnimation->setDuration(80); - m_emergeAnimation->setStartValue(QSize(0, 0)); - m_emergeAnimation->setEndValue( - QSize(GlobalValues::buttonBaseSize(), GlobalValues::buttonBaseSize())); + m_emergeAnimation = new QPropertyAnimation(this, "size", this); + m_emergeAnimation->setEasingCurve(QEasingCurve::InOutQuad); + m_emergeAnimation->setDuration(80); + m_emergeAnimation->setStartValue(QSize(0, 0)); + m_emergeAnimation->setEndValue( + QSize(GlobalValues::buttonBaseSize(), GlobalValues::buttonBaseSize())); - auto dsEffect = new QGraphicsDropShadowEffect(this); - dsEffect->setBlurRadius(5); - dsEffect->setOffset(0); - dsEffect->setColor(QColor(Qt::black)); - - setGraphicsEffect(dsEffect); + auto dsEffect = new QGraphicsDropShadowEffect(this); + dsEffect->setBlurRadius(5); + dsEffect->setOffset(0); + dsEffect->setColor(QColor(Qt::black)); + setGraphicsEffect(dsEffect); } -void CaptureButton::updateIcon() { - setIcon(icon()); - setIconSize(size()*0.6); +void +CaptureButton::updateIcon() +{ + setIcon(icon()); + setIconSize(size() * 0.6); } -QVector CaptureButton::getIterableButtonTypes() { - return iterableButtonTypes; +QVector +CaptureButton::getIterableButtonTypes() +{ + return iterableButtonTypes; } -QString CaptureButton::globalStyleSheet() { - QColor mainColor = ConfigHandler().uiMainColorValue(); - QString baseSheet = "CaptureButton { border-radius: %3;" - "background-color: %1; color: %4 }" - "CaptureButton:hover { background-color: %2; }" - "CaptureButton:pressed:!hover { " - "background-color: %1; }"; - // define color when mouse is hovering - QColor contrast = ColorUtils::contrastColor(m_mainColor); +QString +CaptureButton::globalStyleSheet() +{ + QColor mainColor = ConfigHandler().uiMainColorValue(); + QString baseSheet = "CaptureButton { border-radius: %3;" + "background-color: %1; color: %4 }" + "CaptureButton:hover { background-color: %2; }" + "CaptureButton:pressed:!hover { " + "background-color: %1; }"; + // define color when mouse is hovering + QColor contrast = ColorUtils::contrastColor(m_mainColor); - // foreground color - QString color = ColorUtils::colorIsDark(mainColor) ? "white" : "black"; + // foreground color + QString color = ColorUtils::colorIsDark(mainColor) ? "white" : "black"; - return baseSheet.arg(mainColor.name()).arg(contrast.name()) - .arg(GlobalValues::buttonBaseSize()/2).arg(color); + return baseSheet.arg(mainColor.name()) + .arg(contrast.name()) + .arg(GlobalValues::buttonBaseSize() / 2) + .arg(color); } -QString CaptureButton::styleSheet() const { - QString baseSheet = "CaptureButton { border-radius: %3;" - "background-color: %1; color: %4 }" - "CaptureButton:hover { background-color: %2; }" - "CaptureButton:pressed:!hover { " - "background-color: %1; }"; - // define color when mouse is hovering - QColor contrast = ColorUtils::contrastColor(m_mainColor); - // foreground color - QString color = ColorUtils::colorIsDark(m_mainColor) ? "white" : "black"; +QString +CaptureButton::styleSheet() const +{ + QString baseSheet = "CaptureButton { border-radius: %3;" + "background-color: %1; color: %4 }" + "CaptureButton:hover { background-color: %2; }" + "CaptureButton:pressed:!hover { " + "background-color: %1; }"; + // define color when mouse is hovering + QColor contrast = ColorUtils::contrastColor(m_mainColor); + // foreground color + QString color = ColorUtils::colorIsDark(m_mainColor) ? "white" : "black"; - return baseSheet.arg(m_mainColor.name()).arg(contrast.name()) - .arg(GlobalValues::buttonBaseSize()/2).arg(color); + return baseSheet.arg(m_mainColor.name()) + .arg(contrast.name()) + .arg(GlobalValues::buttonBaseSize() / 2) + .arg(color); } // get icon returns the icon for the type of button -QIcon CaptureButton::icon() const { - return m_tool->icon(m_mainColor, true); +QIcon +CaptureButton::icon() const +{ + return m_tool->icon(m_mainColor, true); } -void CaptureButton::mousePressEvent(QMouseEvent *e) { - if (e->button() == Qt::LeftButton) { - emit pressedButton(this); - emit pressed(); - } +void +CaptureButton::mousePressEvent(QMouseEvent* e) +{ + if (e->button() == Qt::LeftButton) { + emit pressedButton(this); + emit pressed(); + } } -void CaptureButton::animatedShow() { - if(!isVisible()) { - show(); - m_emergeAnimation->start(); - connect(m_emergeAnimation, &QPropertyAnimation::finished, this, [](){ - }); - } +void +CaptureButton::animatedShow() +{ + if (!isVisible()) { + show(); + m_emergeAnimation->start(); + connect(m_emergeAnimation, &QPropertyAnimation::finished, this, []() {}); + } } -CaptureTool *CaptureButton::tool() const { - return m_tool; +CaptureTool* +CaptureButton::tool() const +{ + return m_tool; } -void CaptureButton::setColor(const QColor &c) { - m_mainColor = c; - setStyleSheet(styleSheet()); - updateIcon(); +void +CaptureButton::setColor(const QColor& c) +{ + m_mainColor = c; + setStyleSheet(styleSheet()); + updateIcon(); } QColor CaptureButton::m_mainColor = ConfigHandler().uiMainColorValue(); -static std::map buttonTypeOrder { - { CaptureButton::TYPE_PENCIL, 0 }, - { CaptureButton::TYPE_DRAWER, 1 }, - { CaptureButton::TYPE_ARROW, 2 }, - { CaptureButton::TYPE_SELECTION, 3 }, - { CaptureButton::TYPE_RECTANGLE, 4 }, - { CaptureButton::TYPE_CIRCLE, 5 }, - { CaptureButton::TYPE_MARKER, 6 }, - { CaptureButton::TYPE_TEXT, 7 }, - { CaptureButton::TYPE_BLUR, 8 }, - { CaptureButton::TYPE_SELECTIONINDICATOR, 9 }, - { CaptureButton::TYPE_MOVESELECTION, 10 }, - { CaptureButton::TYPE_UNDO, 11 }, - { CaptureButton::TYPE_REDO, 12 }, - { CaptureButton::TYPE_COPY, 13 }, - { CaptureButton::TYPE_SAVE, 14 }, - { CaptureButton::TYPE_EXIT, 15 }, - { CaptureButton::TYPE_IMAGEUPLOADER, 16 }, - { CaptureButton::TYPE_OPEN_APP, 17 }, - { CaptureButton::TYPE_PIN, 18 }, - { CaptureButton::TYPE_CIRCLECOUNT, 19 }, +static std::map buttonTypeOrder{ + { CaptureButton::TYPE_PENCIL, 0 }, + { CaptureButton::TYPE_DRAWER, 1 }, + { CaptureButton::TYPE_ARROW, 2 }, + { CaptureButton::TYPE_SELECTION, 3 }, + { CaptureButton::TYPE_RECTANGLE, 4 }, + { CaptureButton::TYPE_CIRCLE, 5 }, + { CaptureButton::TYPE_MARKER, 6 }, + { CaptureButton::TYPE_TEXT, 7 }, + { CaptureButton::TYPE_BLUR, 8 }, + { CaptureButton::TYPE_SELECTIONINDICATOR, 9 }, + { CaptureButton::TYPE_MOVESELECTION, 10 }, + { CaptureButton::TYPE_UNDO, 11 }, + { CaptureButton::TYPE_REDO, 12 }, + { CaptureButton::TYPE_COPY, 13 }, + { CaptureButton::TYPE_SAVE, 14 }, + { CaptureButton::TYPE_EXIT, 15 }, + { CaptureButton::TYPE_IMAGEUPLOADER, 16 }, + { CaptureButton::TYPE_OPEN_APP, 17 }, + { CaptureButton::TYPE_PIN, 18 }, + { CaptureButton::TYPE_CIRCLECOUNT, 19 }, }; -int CaptureButton::getPriorityByButton(CaptureButton::ButtonType b) { - auto it = buttonTypeOrder.find(b); - return it == buttonTypeOrder.cend() ? (int)buttonTypeOrder.size() : it->second; +int +CaptureButton::getPriorityByButton(CaptureButton::ButtonType b) +{ + auto it = buttonTypeOrder.find(b); + return it == buttonTypeOrder.cend() ? (int)buttonTypeOrder.size() + : it->second; } QVector CaptureButton::iterableButtonTypes = { - CaptureButton::TYPE_PENCIL, - CaptureButton::TYPE_DRAWER, - CaptureButton::TYPE_ARROW, - CaptureButton::TYPE_SELECTION, - CaptureButton::TYPE_RECTANGLE, - CaptureButton::TYPE_CIRCLE, - CaptureButton::TYPE_MARKER, - CaptureButton::TYPE_TEXT, - CaptureButton::TYPE_BLUR, - CaptureButton::TYPE_SELECTIONINDICATOR, - CaptureButton::TYPE_MOVESELECTION, - CaptureButton::TYPE_UNDO, - CaptureButton::TYPE_REDO, - CaptureButton::TYPE_COPY, - CaptureButton::TYPE_SAVE, - CaptureButton::TYPE_EXIT, - CaptureButton::TYPE_IMAGEUPLOADER, - CaptureButton::TYPE_OPEN_APP, - CaptureButton::TYPE_PIN, - CaptureButton::TYPE_CIRCLECOUNT, + CaptureButton::TYPE_PENCIL, CaptureButton::TYPE_DRAWER, + CaptureButton::TYPE_ARROW, CaptureButton::TYPE_SELECTION, + CaptureButton::TYPE_RECTANGLE, CaptureButton::TYPE_CIRCLE, + CaptureButton::TYPE_MARKER, CaptureButton::TYPE_TEXT, + CaptureButton::TYPE_BLUR, CaptureButton::TYPE_SELECTIONINDICATOR, + CaptureButton::TYPE_MOVESELECTION, CaptureButton::TYPE_UNDO, + CaptureButton::TYPE_REDO, CaptureButton::TYPE_COPY, + CaptureButton::TYPE_SAVE, CaptureButton::TYPE_EXIT, + CaptureButton::TYPE_IMAGEUPLOADER, CaptureButton::TYPE_OPEN_APP, + CaptureButton::TYPE_PIN, CaptureButton::TYPE_CIRCLECOUNT, }; diff --git a/src/widgets/capture/capturebutton.h b/src/widgets/capture/capturebutton.h index 4bc9f96e..550130e1 100644 --- a/src/widgets/capture/capturebutton.h +++ b/src/widgets/capture/capturebutton.h @@ -17,83 +17,85 @@ #pragma once -#include #include +#include #include class QWidget; class QPropertyAnimation; class CaptureTool; -class CaptureButton : public QPushButton { - Q_OBJECT +class CaptureButton : public QPushButton +{ + Q_OBJECT public: - // Don't forget to add the new types to CaptureButton::iterableButtonTypes - // in the .cpp and the order value in the private array buttonTypeOrder - enum ButtonType { - TYPE_PENCIL = 0, - TYPE_DRAWER = 1, - TYPE_ARROW = 2, - TYPE_SELECTION = 3, - TYPE_RECTANGLE = 4, - TYPE_CIRCLE = 5, - TYPE_MARKER = 6, - TYPE_SELECTIONINDICATOR = 7, - TYPE_MOVESELECTION = 8, - TYPE_UNDO = 9, - TYPE_COPY = 10, - TYPE_SAVE = 11, - TYPE_EXIT = 12, - TYPE_IMAGEUPLOADER = 13, - TYPE_OPEN_APP = 14, - TYPE_BLUR = 15, - TYPE_REDO = 16, - TYPE_PIN = 17, - TYPE_TEXT = 18, - TYPE_CIRCLECOUNT = 19, + // Don't forget to add the new types to CaptureButton::iterableButtonTypes + // in the .cpp and the order value in the private array buttonTypeOrder + enum ButtonType + { + TYPE_PENCIL = 0, + TYPE_DRAWER = 1, + TYPE_ARROW = 2, + TYPE_SELECTION = 3, + TYPE_RECTANGLE = 4, + TYPE_CIRCLE = 5, + TYPE_MARKER = 6, + TYPE_SELECTIONINDICATOR = 7, + TYPE_MOVESELECTION = 8, + TYPE_UNDO = 9, + TYPE_COPY = 10, + TYPE_SAVE = 11, + TYPE_EXIT = 12, + TYPE_IMAGEUPLOADER = 13, + TYPE_OPEN_APP = 14, + TYPE_BLUR = 15, + TYPE_REDO = 16, + TYPE_PIN = 17, + TYPE_TEXT = 18, + TYPE_CIRCLECOUNT = 19, - }; + }; #if QT_VERSION < QT_VERSION_CHECK(5, 5, 0) - Q_ENUMS(ButtonType) + Q_ENUMS(ButtonType) #else - Q_ENUM(ButtonType) + Q_ENUM(ButtonType) #endif - CaptureButton() = delete; - explicit CaptureButton(const ButtonType, QWidget *parent = nullptr); + CaptureButton() = delete; + explicit CaptureButton(const ButtonType, QWidget* parent = nullptr); - static QString globalStyleSheet(); - static QVector getIterableButtonTypes(); - static int getPriorityByButton(CaptureButton::ButtonType); + static QString globalStyleSheet(); + static QVector getIterableButtonTypes(); + static int getPriorityByButton(CaptureButton::ButtonType); - QString name() const; - QString description() const; - QIcon icon() const; - QString styleSheet() const; - CaptureTool* tool() const; + QString name() const; + QString description() const; + QIcon icon() const; + QString styleSheet() const; + CaptureTool* tool() const; - void setColor(const QColor &c); - void animatedShow(); + void setColor(const QColor& c); + void animatedShow(); protected: - virtual void mousePressEvent(QMouseEvent *); - static QVector iterableButtonTypes; + virtual void mousePressEvent(QMouseEvent*); + static QVector iterableButtonTypes; - CaptureTool *m_tool; + CaptureTool* m_tool; signals: - void pressedButton(CaptureButton *); + void pressedButton(CaptureButton*); private: - CaptureButton(QWidget *parent = nullptr); - ButtonType m_buttonType; + CaptureButton(QWidget* parent = nullptr); + ButtonType m_buttonType; - QPropertyAnimation *m_emergeAnimation; + QPropertyAnimation* m_emergeAnimation; - static QColor m_mainColor; + static QColor m_mainColor; - void initButton(); - void updateIcon(); + void initButton(); + void updateIcon(); }; diff --git a/src/widgets/capture/capturewidget.cpp b/src/widgets/capture/capturewidget.cpp index e7eab3c7..cc138d83 100644 --- a/src/widgets/capture/capturewidget.cpp +++ b/src/widgets/capture/capturewidget.cpp @@ -15,898 +15,1021 @@ // You should have received a copy of the GNU General Public License // along with Flameshot. If not, see . -// Based on Lightscreen areadialog.cpp, Copyright 2017 Christian Kaiser -// released under the GNU GPL2 +// Based on Lightscreen areadialog.cpp, Copyright 2017 Christian Kaiser +// released under the GNU GPL2 +// -// Based on KDE's KSnapshot regiongrabber.cpp, revision 796531, Copyright 2007 Luca Gugelmann -// released under the GNU LGPL +// Based on KDE's KSnapshot regiongrabber.cpp, revision 796531, Copyright 2007 +// Luca Gugelmann released under the GNU LGPL +// #include "capturewidget.h" -#include "src/widgets/capture/hovereventfilter.h" -#include "src/widgets/panel/sidepanelwidget.h" +#include "src/core/controller.h" #include "src/utils/colorutils.h" #include "src/utils/globalvalues.h" -#include "src/widgets/capture/notifierbox.h" -#include "src/widgets/capture/colorpicker.h" #include "src/utils/screengrabber.h" -#include "src/utils/systemnotification.h" #include "src/utils/screenshotsaver.h" -#include "src/core/controller.h" +#include "src/utils/systemnotification.h" +#include "src/widgets/capture/colorpicker.h" +#include "src/widgets/capture/hovereventfilter.h" #include "src/widgets/capture/modificationcommand.h" -#include -#include -#include +#include "src/widgets/capture/notifierbox.h" +#include "src/widgets/panel/sidepanelwidget.h" #include -#include -#include -#include -#include #include #include +#include +#include +#include +#include +#include +#include +#include -// CaptureWidget is the main component used to capture the screen. It contains an -// are of selection with its respective buttons. +// CaptureWidget is the main component used to capture the screen. It contains +// an are of selection with its respective buttons. // enableSaveWIndow -CaptureWidget::CaptureWidget(const uint id, const QString &savePath, - bool fullScreen, QWidget *parent) : - QWidget(parent), m_mouseIsClicked(false), m_rightClick(false), - m_newSelection(false), m_grabbing(false), m_captureDone(false), - m_previewEnabled(true), m_adjustmentButtonPressed(false), m_activeButton(nullptr), - m_activeTool(nullptr), m_toolWidget(nullptr), - m_mouseOverHandle(SelectionWidget::NO_SIDE), m_id(id) +CaptureWidget::CaptureWidget(const uint id, + const QString& savePath, + bool fullScreen, + QWidget* parent) + : QWidget(parent) + , m_mouseIsClicked(false) + , m_rightClick(false) + , m_newSelection(false) + , m_grabbing(false) + , m_captureDone(false) + , m_previewEnabled(true) + , m_adjustmentButtonPressed(false) + , m_activeButton(nullptr) + , m_activeTool(nullptr) + , m_toolWidget(nullptr) + , m_mouseOverHandle(SelectionWidget::NO_SIDE) + , m_id(id) { - // Base config of the widget - m_eventFilter = new HoverEventFilter(this); - connect(m_eventFilter, &HoverEventFilter::hoverIn, - this, &CaptureWidget::childEnter); - connect(m_eventFilter, &HoverEventFilter::hoverOut, - this, &CaptureWidget::childLeave); - setAttribute(Qt::WA_DeleteOnClose); - m_showInitialMsg = m_config.showHelpValue(); - m_opacity = m_config.contrastOpacityValue(); - setMouseTracking(true); - initContext(savePath, fullScreen); - initShortcuts(); - m_context.circleCount=1; + // Base config of the widget + m_eventFilter = new HoverEventFilter(this); + connect(m_eventFilter, + &HoverEventFilter::hoverIn, + this, + &CaptureWidget::childEnter); + connect(m_eventFilter, + &HoverEventFilter::hoverOut, + this, + &CaptureWidget::childLeave); + setAttribute(Qt::WA_DeleteOnClose); + m_showInitialMsg = m_config.showHelpValue(); + m_opacity = m_config.contrastOpacityValue(); + setMouseTracking(true); + initContext(savePath, fullScreen); + initShortcuts(); + m_context.circleCount = 1; #ifdef Q_OS_WIN - // Top left of the whole set of screens - QPoint topLeft(0,0); + // Top left of the whole set of screens + QPoint topLeft(0, 0); #endif - if (fullScreen) { - // Grab Screenshot - bool ok = true; - m_context.screenshot = ScreenGrabber().grabEntireDesktop(ok); - if(!ok) { - SystemNotification().sendMessage(tr("Unable to capture screen")); - this->close(); - } - m_context.origScreenshot = m_context.screenshot; + if (fullScreen) { + // Grab Screenshot + bool ok = true; + m_context.screenshot = ScreenGrabber().grabEntireDesktop(ok); + if (!ok) { + SystemNotification().sendMessage(tr("Unable to capture screen")); + this->close(); + } + m_context.origScreenshot = m_context.screenshot; #ifdef Q_OS_WIN - setWindowFlags(Qt::WindowStaysOnTopHint - | Qt::FramelessWindowHint - | Qt::Popup); + setWindowFlags(Qt::WindowStaysOnTopHint | Qt::FramelessWindowHint | + Qt::Popup); - for (QScreen *const screen : QGuiApplication::screens()) { - QPoint topLeftScreen = screen->geometry().topLeft(); - if (topLeft.x() > topLeftScreen.x() || - topLeft.y() > topLeftScreen.y()) { - topLeft = topLeftScreen; - } - } - move(topLeft); + for (QScreen* const screen : QGuiApplication::screens()) { + QPoint topLeftScreen = screen->geometry().topLeft(); + if (topLeft.x() > topLeftScreen.x() || topLeft.y() > topLeftScreen.y()) { + topLeft = topLeftScreen; + } + } + move(topLeft); #else - setWindowFlags(Qt::BypassWindowManagerHint - | Qt::WindowStaysOnTopHint - | Qt::FramelessWindowHint - | Qt::Tool); + setWindowFlags(Qt::BypassWindowManagerHint | Qt::WindowStaysOnTopHint | + Qt::FramelessWindowHint | Qt::Tool); #endif - resize(pixmap().size()); - } - // Create buttons - m_buttonHandler = new ButtonHandler(this); - updateButtons(); - QVector areas; - if (m_context.fullscreen) { - for (QScreen *const screen : QGuiApplication::screens()) { - QRect r = screen->geometry(); + resize(pixmap().size()); + } + // Create buttons + m_buttonHandler = new ButtonHandler(this); + updateButtons(); + QVector areas; + if (m_context.fullscreen) { + for (QScreen* const screen : QGuiApplication::screens()) { + QRect r = screen->geometry(); #ifdef Q_OS_WIN - r.moveTo(r.topLeft() - topLeft); + r.moveTo(r.topLeft() - topLeft); #endif - areas.append(r); - } - } else { - areas.append(rect()); + areas.append(r); } - m_buttonHandler->updateScreenRegions(areas); - m_buttonHandler->hide(); + } else { + areas.append(rect()); + } + m_buttonHandler->updateScreenRegions(areas); + m_buttonHandler->hide(); - initSelection(); - updateCursor(); + initSelection(); + updateCursor(); - // Init color picker - m_colorPicker = new ColorPicker(this); - connect(m_colorPicker, &ColorPicker::colorSelected, - this, &CaptureWidget::setDrawColor); - m_colorPicker->hide(); + // Init color picker + m_colorPicker = new ColorPicker(this); + connect(m_colorPicker, + &ColorPicker::colorSelected, + this, + &CaptureWidget::setDrawColor); + m_colorPicker->hide(); - // Init notification widget - m_notifierBox = new NotifierBox(this); - m_notifierBox->hide(); + // Init notification widget + m_notifierBox = new NotifierBox(this); + m_notifierBox->hide(); - connect(&m_undoStack, &QUndoStack::indexChanged, - this, [this](int){ this->update(); }); - initPanel(); + connect(&m_undoStack, &QUndoStack::indexChanged, this, [this](int) { + this->update(); + }); + initPanel(); } -CaptureWidget::~CaptureWidget() { - if (m_captureDone) { - emit captureTaken(m_id, this->pixmap()); - } else { - emit captureFailed(m_id); - } - m_config.setdrawThickness(m_context.thickness); +CaptureWidget::~CaptureWidget() +{ + if (m_captureDone) { + emit captureTaken(m_id, this->pixmap()); + } else { + emit captureFailed(m_id); + } + m_config.setdrawThickness(m_context.thickness); } // redefineButtons retrieves the buttons configured to be shown with the // selection in the capture -void CaptureWidget::updateButtons() { - m_uiColor = m_config.uiMainColorValue(); - m_contrastUiColor = m_config.uiContrastColorValue(); +void +CaptureWidget::updateButtons() +{ + m_uiColor = m_config.uiMainColorValue(); + m_contrastUiColor = m_config.uiContrastColorValue(); - auto buttons = m_config.getButtons(); - QVector vectorButtons; + auto buttons = m_config.getButtons(); + QVector vectorButtons; - for (const CaptureButton::ButtonType &t: buttons) { - CaptureButton *b = new CaptureButton(t, this); - if (t == CaptureButton::TYPE_SELECTIONINDICATOR) { - m_sizeIndButton = b; - } - b->setColor(m_uiColor); - makeChild(b); - - connect(b, &CaptureButton::pressedButton, this, &CaptureWidget::setState); - connect(b->tool(), &CaptureTool::requestAction, - this, &CaptureWidget::handleButtonSignal); - vectorButtons << b; + for (const CaptureButton::ButtonType& t : buttons) { + CaptureButton* b = new CaptureButton(t, this); + if (t == CaptureButton::TYPE_SELECTIONINDICATOR) { + m_sizeIndButton = b; } - m_buttonHandler->setButtons(vectorButtons); + b->setColor(m_uiColor); + makeChild(b); + + connect(b, &CaptureButton::pressedButton, this, &CaptureWidget::setState); + connect(b->tool(), + &CaptureTool::requestAction, + this, + &CaptureWidget::handleButtonSignal); + vectorButtons << b; + } + m_buttonHandler->setButtons(vectorButtons); } -QPixmap CaptureWidget::pixmap() { - QPixmap p; - if (m_toolWidget && m_activeTool) { - p = m_context.selectedScreenshotArea().copy(); - QPainter painter(&p); - m_activeTool->process(painter, p); - } else { - p = m_context.selectedScreenshotArea(); - } - return m_context.selectedScreenshotArea(); +QPixmap +CaptureWidget::pixmap() +{ + QPixmap p; + if (m_toolWidget && m_activeTool) { + p = m_context.selectedScreenshotArea().copy(); + QPainter painter(&p); + m_activeTool->process(painter, p); + } else { + p = m_context.selectedScreenshotArea(); + } + return m_context.selectedScreenshotArea(); } -void CaptureWidget::deleteToolwidgetOrClose() { - if (m_toolWidget) { - m_toolWidget->deleteLater(); - m_toolWidget = nullptr; - } else { - close(); - } +void +CaptureWidget::deleteToolwidgetOrClose() +{ + if (m_toolWidget) { + m_toolWidget->deleteLater(); + m_toolWidget = nullptr; + } else { + close(); + } } -void CaptureWidget::paintEvent(QPaintEvent *) { - QPainter painter(this); - painter.drawPixmap(0, 0, m_context.screenshot); +void +CaptureWidget::paintEvent(QPaintEvent*) +{ + QPainter painter(this); + painter.drawPixmap(0, 0, m_context.screenshot); - if (m_activeTool && m_mouseIsClicked) { - painter.save(); - m_activeTool->process(painter, m_context.screenshot); - painter.restore(); - } else if (m_activeButton && m_activeButton->tool()->showMousePreview() && - m_previewEnabled) - { - painter.save(); - m_activeButton->tool()->paintMousePreview(painter, m_context); - painter.restore(); - } - - QColor overlayColor(0, 0, 0, m_opacity); - painter.setBrush(overlayColor); - QRect r; - if (m_selection->isVisible()) { - r = m_selection->geometry().normalized().adjusted(0, 0, -1, -1); - } - QRegion grey(rect()); - grey = grey.subtracted(r); - - painter.setClipRegion(grey); - painter.drawRect(-1, -1, rect().width() + 1, rect().height() + 1); - painter.setClipRect(rect()); - - if (m_showInitialMsg) { - QRect helpRect = QGuiApplication::primaryScreen()->geometry(); - helpRect.moveTo(mapFromGlobal(helpRect.topLeft())); - - QString helpTxt = tr("Select an area with the mouse, or press Esc to exit." - "\nPress Enter to capture the screen." - "\nPress Right Click to show the color picker." - "\nUse the Mouse Wheel to change the thickness of your tool." - "\nPress Space to open the side panel."); - - // We draw the white contrasting background for the text, using the - //same text and options to get the boundingRect that the text will have. - QRectF bRect = painter.boundingRect(helpRect, Qt::AlignCenter, helpTxt); - - // These four calls provide padding for the rect - const int margin = QApplication::fontMetrics().height() / 2; - bRect.setWidth(bRect.width() + margin); - bRect.setHeight(bRect.height() + margin); - bRect.setX(bRect.x() - margin); - bRect.setY(bRect.y() - margin); - - QColor rectColor(m_uiColor); - rectColor.setAlpha(180); - QColor textColor((ColorUtils::colorIsDark(rectColor) ? - Qt::white : Qt::black)); - - painter.setBrush(QBrush(rectColor, Qt::SolidPattern)); - painter.setPen(QPen(textColor)); - - painter.drawRect(bRect); - painter.drawText(helpRect, Qt::AlignCenter, helpTxt); - } - - if (m_selection->isVisible()) { - // paint handlers - painter.setPen(m_uiColor); - painter.setRenderHint(QPainter::Antialiasing); - painter.setBrush(m_uiColor); - for(auto r: m_selection->handlerAreas()) { - painter.drawRoundedRect(r, 100, 100); - } + if (m_activeTool && m_mouseIsClicked) { + painter.save(); + m_activeTool->process(painter, m_context.screenshot); + painter.restore(); + } else if (m_activeButton && m_activeButton->tool()->showMousePreview() && + m_previewEnabled) { + painter.save(); + m_activeButton->tool()->paintMousePreview(painter, m_context); + painter.restore(); + } + + QColor overlayColor(0, 0, 0, m_opacity); + painter.setBrush(overlayColor); + QRect r; + if (m_selection->isVisible()) { + r = m_selection->geometry().normalized().adjusted(0, 0, -1, -1); + } + QRegion grey(rect()); + grey = grey.subtracted(r); + + painter.setClipRegion(grey); + painter.drawRect(-1, -1, rect().width() + 1, rect().height() + 1); + painter.setClipRect(rect()); + + if (m_showInitialMsg) { + QRect helpRect = QGuiApplication::primaryScreen()->geometry(); + helpRect.moveTo(mapFromGlobal(helpRect.topLeft())); + + QString helpTxt = + tr("Select an area with the mouse, or press Esc to exit." + "\nPress Enter to capture the screen." + "\nPress Right Click to show the color picker." + "\nUse the Mouse Wheel to change the thickness of your tool." + "\nPress Space to open the side panel."); + + // We draw the white contrasting background for the text, using the + // same text and options to get the boundingRect that the text will have. + QRectF bRect = painter.boundingRect(helpRect, Qt::AlignCenter, helpTxt); + + // These four calls provide padding for the rect + const int margin = QApplication::fontMetrics().height() / 2; + bRect.setWidth(bRect.width() + margin); + bRect.setHeight(bRect.height() + margin); + bRect.setX(bRect.x() - margin); + bRect.setY(bRect.y() - margin); + + QColor rectColor(m_uiColor); + rectColor.setAlpha(180); + QColor textColor( + (ColorUtils::colorIsDark(rectColor) ? Qt::white : Qt::black)); + + painter.setBrush(QBrush(rectColor, Qt::SolidPattern)); + painter.setPen(QPen(textColor)); + + painter.drawRect(bRect); + painter.drawText(helpRect, Qt::AlignCenter, helpTxt); + } + + if (m_selection->isVisible()) { + // paint handlers + painter.setPen(m_uiColor); + painter.setRenderHint(QPainter::Antialiasing); + painter.setBrush(m_uiColor); + for (auto r : m_selection->handlerAreas()) { + painter.drawRoundedRect(r, 100, 100); } + } } -void CaptureWidget::mousePressEvent(QMouseEvent *e) { - if (e->button() == Qt::RightButton) { - m_rightClick = true; - m_colorPicker->move(e->pos().x()-m_colorPicker->width()/2, - e->pos().y()-m_colorPicker->height()/2); - m_colorPicker->show(); - } else if (e->button() == Qt::LeftButton) { - m_showInitialMsg = false; - m_mouseIsClicked = true; - // Click using a tool - if (m_activeButton) { - if (m_activeTool) { - if (m_activeTool->isValid() && m_toolWidget) { - pushToolToStack(); - } else { - m_activeTool->deleteLater(); - } - if (m_toolWidget) { - m_toolWidget->deleteLater(); - return; - } - } - m_activeTool = m_activeButton->tool()->copy(this); - - connect(this, &CaptureWidget::colorChanged, - m_activeTool, &CaptureTool::colorChanged); - connect(this, &CaptureWidget::thicknessChanged, - m_activeTool, &CaptureTool::thicknessChanged); - connect(m_activeTool, &CaptureTool::requestAction, - this, &CaptureWidget::handleButtonSignal); - m_activeTool->drawStart(m_context); - return; - } - - m_dragStartPoint = e->pos(); - m_selection->saveGeometry(); - // New selection - if (!m_selection->geometry().contains(e->pos()) && - m_mouseOverHandle == SelectionWidget::NO_SIDE) - { - m_selection->setGeometry(QRect(e->pos(), e->pos())); - m_selection->setVisible(false); - m_newSelection = true; - m_buttonHandler->hide(); - update(); +void +CaptureWidget::mousePressEvent(QMouseEvent* e) +{ + if (e->button() == Qt::RightButton) { + m_rightClick = true; + m_colorPicker->move(e->pos().x() - m_colorPicker->width() / 2, + e->pos().y() - m_colorPicker->height() / 2); + m_colorPicker->show(); + } else if (e->button() == Qt::LeftButton) { + m_showInitialMsg = false; + m_mouseIsClicked = true; + // Click using a tool + if (m_activeButton) { + if (m_activeTool) { + if (m_activeTool->isValid() && m_toolWidget) { + pushToolToStack(); } else { - m_grabbing = true; + m_activeTool->deleteLater(); } + if (m_toolWidget) { + m_toolWidget->deleteLater(); + return; + } + } + m_activeTool = m_activeButton->tool()->copy(this); + + connect(this, + &CaptureWidget::colorChanged, + m_activeTool, + &CaptureTool::colorChanged); + connect(this, + &CaptureWidget::thicknessChanged, + m_activeTool, + &CaptureTool::thicknessChanged); + connect(m_activeTool, + &CaptureTool::requestAction, + this, + &CaptureWidget::handleButtonSignal); + m_activeTool->drawStart(m_context); + return; } - updateCursor(); -} -void CaptureWidget::mouseMoveEvent(QMouseEvent *e) { - m_context.mousePos = e->pos(); - - if (m_mouseIsClicked && !m_activeButton) { - if (m_buttonHandler->isVisible()) { - m_buttonHandler->hide(); - } - if (m_newSelection) { - m_selection->setVisible(true); - m_selection->setGeometry( - QRect(m_dragStartPoint, m_context.mousePos).normalized()); - update(); - } else if (m_mouseOverHandle == SelectionWidget::NO_SIDE) { - // Moving the whole selection - QRect initialRect = m_selection->savedGeometry().normalized(); - QPoint newTopLeft = initialRect.topLeft() + (e->pos() - m_dragStartPoint); - QRect finalRect(newTopLeft, initialRect.size()); - - if (finalRect.left() < rect().left()) { - finalRect.setLeft(rect().left()); - } else if (finalRect.right() > rect().right()) { - finalRect.setRight(rect().right()); - } - if (finalRect.top() < rect().top()) { - finalRect.setTop(rect().top()); - } else if (finalRect.bottom() > rect().bottom()) { - finalRect.setBottom(rect().bottom()); - } - m_selection->setGeometry(finalRect.normalized().intersected(rect())); - update(); - } else { - // Dragging a handle - QRect r = m_selection->savedGeometry(); - QPoint offset = e->pos() - m_dragStartPoint; - bool symmetryMod = qApp->keyboardModifiers() & Qt::ShiftModifier; - - using sw = SelectionWidget; - if (m_mouseOverHandle == sw::TOPLEFT_SIDE - || m_mouseOverHandle == sw::TOP_SIDE - || m_mouseOverHandle == sw::TOPRIGHT_SIDE) - { // dragging one of the top handles - r.setTop(r.top() + offset.y()); - if (symmetryMod) { - r.setBottom(r.bottom() - offset.y()); - } - } - if (m_mouseOverHandle == sw::TOPLEFT_SIDE - || m_mouseOverHandle == sw::LEFT_SIDE - || m_mouseOverHandle == sw::BOTTONLEFT_SIDE) - { // dragging one of the left handles - r.setLeft(r.left() + offset.x()); - if (symmetryMod) { - r.setRight(r.right() - offset.x()); - } - } - if (m_mouseOverHandle == sw::BOTTONLEFT_SIDE - || m_mouseOverHandle == sw::BOTTON_SIDE - || m_mouseOverHandle == sw::BOTTONRIGHT_SIDE) - { // dragging one of the bottom handles - r.setBottom(r.bottom() + offset.y()); - if (symmetryMod) { - r.setTop(r.top() - offset.y()); - } - } - if (m_mouseOverHandle == sw::TOPRIGHT_SIDE - || m_mouseOverHandle == sw::RIGHT_SIDE - || m_mouseOverHandle == sw::BOTTONRIGHT_SIDE) - { // dragging one of the right handles - r.setRight(r.right() + offset.x()); - if (symmetryMod) { - r.setLeft(r.left() - offset.x()); - } - } - m_selection->setGeometry(r.intersected(rect()).normalized()); - update(); - } - } else if (m_mouseIsClicked && m_activeTool) { - // drawing with a tool - if (m_adjustmentButtonPressed) { - m_activeTool->drawMoveWithAdjustment(e->pos()); - } else { - m_activeTool->drawMove(e->pos()); - } - update(); - // Hides the buttons under the mouse. If the mouse leaves, it shows them. - if (m_buttonHandler->buttonsAreInside()) { - const bool containsMouse = m_buttonHandler->contains(m_context.mousePos); - if (containsMouse) { - m_buttonHandler->hide(); - } else { - m_buttonHandler->show(); - } - } - } else if (m_activeButton && m_activeButton->tool()->showMousePreview()) { - update(); + m_dragStartPoint = e->pos(); + m_selection->saveGeometry(); + // New selection + if (!m_selection->geometry().contains(e->pos()) && + m_mouseOverHandle == SelectionWidget::NO_SIDE) { + m_selection->setGeometry(QRect(e->pos(), e->pos())); + m_selection->setVisible(false); + m_newSelection = true; + m_buttonHandler->hide(); + update(); } else { - if (!m_selection->isVisible()) { - return; - } - m_mouseOverHandle = m_selection->getMouseSide(m_context.mousePos); - updateCursor(); + m_grabbing = true; } + } + updateCursor(); } -void CaptureWidget::mouseReleaseEvent(QMouseEvent *e) { - if (e->button() == Qt::RightButton) { - m_colorPicker->hide(); - m_rightClick = false; - // when we end the drawing we have to register the last point and - //add the temp modification to the list of modifications - } else if (m_mouseIsClicked && m_activeTool) { - m_activeTool->drawEnd(m_context.mousePos); - if (m_activeTool->isValid()) { - pushToolToStack(); - } else if (!m_toolWidget){ - m_activeTool->deleteLater(); - m_activeTool = nullptr; - } - } +void +CaptureWidget::mouseMoveEvent(QMouseEvent* e) +{ + m_context.mousePos = e->pos(); - // Show the buttons after the resize of the selection or the creation - // of a new one. - if (!m_buttonHandler->isVisible() && m_selection->isVisible()) { - // Don't go outside - QRect newGeometry = m_selection->geometry().intersected(rect()); - // normalize - if (newGeometry.width() <= 0) { - int left = newGeometry.left(); - newGeometry.setLeft(newGeometry.right()); - newGeometry.setRight(left); + if (m_mouseIsClicked && !m_activeButton) { + if (m_buttonHandler->isVisible()) { + m_buttonHandler->hide(); + } + if (m_newSelection) { + m_selection->setVisible(true); + m_selection->setGeometry( + QRect(m_dragStartPoint, m_context.mousePos).normalized()); + update(); + } else if (m_mouseOverHandle == SelectionWidget::NO_SIDE) { + // Moving the whole selection + QRect initialRect = m_selection->savedGeometry().normalized(); + QPoint newTopLeft = initialRect.topLeft() + (e->pos() - m_dragStartPoint); + QRect finalRect(newTopLeft, initialRect.size()); + + if (finalRect.left() < rect().left()) { + finalRect.setLeft(rect().left()); + } else if (finalRect.right() > rect().right()) { + finalRect.setRight(rect().right()); + } + if (finalRect.top() < rect().top()) { + finalRect.setTop(rect().top()); + } else if (finalRect.bottom() > rect().bottom()) { + finalRect.setBottom(rect().bottom()); + } + m_selection->setGeometry(finalRect.normalized().intersected(rect())); + update(); + } else { + // Dragging a handle + QRect r = m_selection->savedGeometry(); + QPoint offset = e->pos() - m_dragStartPoint; + bool symmetryMod = qApp->keyboardModifiers() & Qt::ShiftModifier; + + using sw = SelectionWidget; + if (m_mouseOverHandle == sw::TOPLEFT_SIDE || + m_mouseOverHandle == sw::TOP_SIDE || + m_mouseOverHandle == + sw::TOPRIGHT_SIDE) { // dragging one of the top handles + r.setTop(r.top() + offset.y()); + if (symmetryMod) { + r.setBottom(r.bottom() - offset.y()); } - if (newGeometry.height() <= 0) { - int top = newGeometry.top(); - newGeometry.setTop(newGeometry.bottom()); - newGeometry.setBottom(top); + } + if (m_mouseOverHandle == sw::TOPLEFT_SIDE || + m_mouseOverHandle == sw::LEFT_SIDE || + m_mouseOverHandle == + sw::BOTTONLEFT_SIDE) { // dragging one of the left handles + r.setLeft(r.left() + offset.x()); + if (symmetryMod) { + r.setRight(r.right() - offset.x()); } - m_selection->setGeometry(newGeometry); - m_context.selection = extendedRect(&newGeometry); - updateSizeIndicator(); - m_buttonHandler->updatePosition(newGeometry); + } + if (m_mouseOverHandle == sw::BOTTONLEFT_SIDE || + m_mouseOverHandle == sw::BOTTON_SIDE || + m_mouseOverHandle == + sw::BOTTONRIGHT_SIDE) { // dragging one of the bottom handles + r.setBottom(r.bottom() + offset.y()); + if (symmetryMod) { + r.setTop(r.top() - offset.y()); + } + } + if (m_mouseOverHandle == sw::TOPRIGHT_SIDE || + m_mouseOverHandle == sw::RIGHT_SIDE || + m_mouseOverHandle == + sw::BOTTONRIGHT_SIDE) { // dragging one of the right handles + r.setRight(r.right() + offset.x()); + if (symmetryMod) { + r.setLeft(r.left() - offset.x()); + } + } + m_selection->setGeometry(r.intersected(rect()).normalized()); + update(); + } + } else if (m_mouseIsClicked && m_activeTool) { + // drawing with a tool + if (m_adjustmentButtonPressed) { + m_activeTool->drawMoveWithAdjustment(e->pos()); + } else { + m_activeTool->drawMove(e->pos()); + } + update(); + // Hides the buttons under the mouse. If the mouse leaves, it shows them. + if (m_buttonHandler->buttonsAreInside()) { + const bool containsMouse = m_buttonHandler->contains(m_context.mousePos); + if (containsMouse) { + m_buttonHandler->hide(); + } else { m_buttonHandler->show(); + } } - m_mouseIsClicked = false; - m_newSelection = false; - m_grabbing = false; - - updateCursor(); -} - -void CaptureWidget::keyPressEvent(QKeyEvent *e) { + } else if (m_activeButton && m_activeButton->tool()->showMousePreview()) { + update(); + } else { if (!m_selection->isVisible()) { - return; - } else if (e->key() == Qt::Key_Up - && m_selection->geometry().top() > rect().top()) { - m_selection->move(QPoint(m_selection->x(), m_selection->y() -1)); - QRect newGeometry = m_selection->geometry().intersected(rect()); - m_context.selection = extendedRect(&newGeometry); - m_buttonHandler->updatePosition(m_selection->geometry()); - update(); - } else if (e->key() == Qt::Key_Down - && m_selection->geometry().bottom() < rect().bottom()) { - m_selection->move(QPoint(m_selection->x(), m_selection->y() +1)); - QRect newGeometry = m_selection->geometry().intersected(rect()); - m_context.selection = extendedRect(&newGeometry); - m_buttonHandler->updatePosition(m_selection->geometry()); - update(); - } else if (e->key() == Qt::Key_Left - && m_selection->geometry().left() > rect().left()) { - m_selection->move(QPoint(m_selection->x() -1, m_selection->y())); - m_buttonHandler->updatePosition(m_selection->geometry()); - update(); - } else if (e->key() == Qt::Key_Right - && m_selection->geometry().right() < rect().right()) { - m_selection->move(QPoint(m_selection->x() +1, m_selection->y())); - QRect newGeometry = m_selection->geometry().intersected(rect()); - m_context.selection = extendedRect(&newGeometry); - m_buttonHandler->updatePosition(m_selection->geometry()); - update(); - } else if (e->key() == Qt::Key_Control) { - m_adjustmentButtonPressed = true; + return; } + m_mouseOverHandle = m_selection->getMouseSide(m_context.mousePos); + updateCursor(); + } } -void CaptureWidget::keyReleaseEvent(QKeyEvent *e) { - if (e->key() == Qt::Key_Control) { - m_adjustmentButtonPressed = false; +void +CaptureWidget::mouseReleaseEvent(QMouseEvent* e) +{ + if (e->button() == Qt::RightButton) { + m_colorPicker->hide(); + m_rightClick = false; + // when we end the drawing we have to register the last point and + // add the temp modification to the list of modifications + } else if (m_mouseIsClicked && m_activeTool) { + m_activeTool->drawEnd(m_context.mousePos); + if (m_activeTool->isValid()) { + pushToolToStack(); + } else if (!m_toolWidget) { + m_activeTool->deleteLater(); + m_activeTool = nullptr; } -} + } -void CaptureWidget::wheelEvent(QWheelEvent *e) { - m_context.thickness += e->angleDelta().y() / 120; - m_context.thickness = qBound(0, m_context.thickness, 100); - QPoint topLeft = qApp->desktop()->screenGeometry( - qApp->desktop()->screenNumber(QCursor::pos())).topLeft(); - int offset = m_notifierBox->width() / 4; - m_notifierBox->move(mapFromGlobal(topLeft) + QPoint(offset, offset)); - m_notifierBox->showMessage(QString::number(m_context.thickness)); - if (m_activeButton && m_activeButton->tool()->showMousePreview()) { - update(); + // Show the buttons after the resize of the selection or the creation + // of a new one. + if (!m_buttonHandler->isVisible() && m_selection->isVisible()) { + // Don't go outside + QRect newGeometry = m_selection->geometry().intersected(rect()); + // normalize + if (newGeometry.width() <= 0) { + int left = newGeometry.left(); + newGeometry.setLeft(newGeometry.right()); + newGeometry.setRight(left); } - emit thicknessChanged(m_context.thickness); -} - -void CaptureWidget::resizeEvent(QResizeEvent *e) { - QWidget::resizeEvent(e); - m_context.widgetDimensions = rect(); - m_context.widgetOffset = mapToGlobal(QPoint(0,0)); - m_panel->setFixedHeight(height()); - if (!m_context.fullscreen) { - m_buttonHandler->updateScreenRegions(rect()); + if (newGeometry.height() <= 0) { + int top = newGeometry.top(); + newGeometry.setTop(newGeometry.bottom()); + newGeometry.setBottom(top); } + m_selection->setGeometry(newGeometry); + m_context.selection = extendedRect(&newGeometry); + updateSizeIndicator(); + m_buttonHandler->updatePosition(newGeometry); + m_buttonHandler->show(); + } + m_mouseIsClicked = false; + m_newSelection = false; + m_grabbing = false; + + updateCursor(); } -void CaptureWidget::moveEvent(QMoveEvent *e) { - QWidget::moveEvent(e); - m_context.widgetOffset = mapToGlobal(QPoint(0,0)); +void +CaptureWidget::keyPressEvent(QKeyEvent* e) +{ + if (!m_selection->isVisible()) { + return; + } else if (e->key() == Qt::Key_Up && + m_selection->geometry().top() > rect().top()) { + m_selection->move(QPoint(m_selection->x(), m_selection->y() - 1)); + QRect newGeometry = m_selection->geometry().intersected(rect()); + m_context.selection = extendedRect(&newGeometry); + m_buttonHandler->updatePosition(m_selection->geometry()); + update(); + } else if (e->key() == Qt::Key_Down && + m_selection->geometry().bottom() < rect().bottom()) { + m_selection->move(QPoint(m_selection->x(), m_selection->y() + 1)); + QRect newGeometry = m_selection->geometry().intersected(rect()); + m_context.selection = extendedRect(&newGeometry); + m_buttonHandler->updatePosition(m_selection->geometry()); + update(); + } else if (e->key() == Qt::Key_Left && + m_selection->geometry().left() > rect().left()) { + m_selection->move(QPoint(m_selection->x() - 1, m_selection->y())); + m_buttonHandler->updatePosition(m_selection->geometry()); + update(); + } else if (e->key() == Qt::Key_Right && + m_selection->geometry().right() < rect().right()) { + m_selection->move(QPoint(m_selection->x() + 1, m_selection->y())); + QRect newGeometry = m_selection->geometry().intersected(rect()); + m_context.selection = extendedRect(&newGeometry); + m_buttonHandler->updatePosition(m_selection->geometry()); + update(); + } else if (e->key() == Qt::Key_Control) { + m_adjustmentButtonPressed = true; + } } -void CaptureWidget::initContext(const QString &savePath, bool fullscreen) { - m_context.widgetDimensions = rect(); - m_context.color = m_config.drawColorValue(); - m_context.savePath = savePath; - m_context.widgetOffset = mapToGlobal(QPoint(0,0)); - m_context.mousePos= mapFromGlobal(QCursor::pos()); - m_context.thickness = m_config.drawThicknessValue(); - m_context.fullscreen = fullscreen; +void +CaptureWidget::keyReleaseEvent(QKeyEvent* e) +{ + if (e->key() == Qt::Key_Control) { + m_adjustmentButtonPressed = false; + } } -void CaptureWidget::initPanel() { - m_panel = new UtilityPanel(this); - makeChild(m_panel); - QRect panelRect = rect(); - if (m_context.fullscreen) { - panelRect = QGuiApplication::primaryScreen()->geometry(); +void +CaptureWidget::wheelEvent(QWheelEvent* e) +{ + m_context.thickness += e->angleDelta().y() / 120; + m_context.thickness = qBound(0, m_context.thickness, 100); + QPoint topLeft = + qApp->desktop() + ->screenGeometry(qApp->desktop()->screenNumber(QCursor::pos())) + .topLeft(); + int offset = m_notifierBox->width() / 4; + m_notifierBox->move(mapFromGlobal(topLeft) + QPoint(offset, offset)); + m_notifierBox->showMessage(QString::number(m_context.thickness)); + if (m_activeButton && m_activeButton->tool()->showMousePreview()) { + update(); + } + emit thicknessChanged(m_context.thickness); +} + +void +CaptureWidget::resizeEvent(QResizeEvent* e) +{ + QWidget::resizeEvent(e); + m_context.widgetDimensions = rect(); + m_context.widgetOffset = mapToGlobal(QPoint(0, 0)); + m_panel->setFixedHeight(height()); + if (!m_context.fullscreen) { + m_buttonHandler->updateScreenRegions(rect()); + } +} + +void +CaptureWidget::moveEvent(QMoveEvent* e) +{ + QWidget::moveEvent(e); + m_context.widgetOffset = mapToGlobal(QPoint(0, 0)); +} + +void +CaptureWidget::initContext(const QString& savePath, bool fullscreen) +{ + m_context.widgetDimensions = rect(); + m_context.color = m_config.drawColorValue(); + m_context.savePath = savePath; + m_context.widgetOffset = mapToGlobal(QPoint(0, 0)); + m_context.mousePos = mapFromGlobal(QCursor::pos()); + m_context.thickness = m_config.drawThicknessValue(); + m_context.fullscreen = fullscreen; +} + +void +CaptureWidget::initPanel() +{ + m_panel = new UtilityPanel(this); + makeChild(m_panel); + QRect panelRect = rect(); + if (m_context.fullscreen) { + panelRect = QGuiApplication::primaryScreen()->geometry(); + } + panelRect.moveTo(mapFromGlobal(panelRect.topLeft())); + panelRect.setWidth(m_colorPicker->width() * 3); + m_panel->setGeometry(panelRect); + + SidePanelWidget* sidePanel = new SidePanelWidget(&m_context.screenshot); + connect(sidePanel, + &SidePanelWidget::colorChanged, + this, + &CaptureWidget::setDrawColor); + connect(sidePanel, + &SidePanelWidget::thicknessChanged, + this, + &CaptureWidget::setDrawThickness); + connect(this, + &CaptureWidget::colorChanged, + sidePanel, + &SidePanelWidget::updateColor); + connect(this, + &CaptureWidget::thicknessChanged, + sidePanel, + &SidePanelWidget::updateThickness); + connect( + sidePanel, &SidePanelWidget::togglePanel, m_panel, &UtilityPanel::toggle); + sidePanel->colorChanged(m_context.color); + sidePanel->thicknessChanged(m_context.thickness); + m_panel->pushWidget(sidePanel); + m_panel->pushWidget(new QUndoView(&m_undoStack, this)); +} + +void +CaptureWidget::initSelection() +{ + m_selection = new SelectionWidget(m_uiColor, this); + connect(m_selection, &SelectionWidget::animationEnded, this, [this]() { + this->m_buttonHandler->updatePosition(this->m_selection->geometry()); + }); + m_selection->setVisible(false); + m_selection->setGeometry(QRect()); +} + +void +CaptureWidget::setState(CaptureButton* b) +{ + if (!b) { + return; + } + if (m_toolWidget) { + m_toolWidget->deleteLater(); + if (m_activeTool->isValid()) { + pushToolToStack(); } - panelRect.moveTo(mapFromGlobal(panelRect.topLeft())); - panelRect.setWidth(m_colorPicker->width() * 3); - m_panel->setGeometry(panelRect); + } + if (m_activeButton != b) { + processTool(b->tool()); + } + // Only close activated from button + if (b->tool()->closeOnButtonPressed()) { + close(); + } - SidePanelWidget *sidePanel = - new SidePanelWidget(&m_context.screenshot); - connect(sidePanel, &SidePanelWidget::colorChanged, - this, &CaptureWidget::setDrawColor); - connect(sidePanel, &SidePanelWidget::thicknessChanged, - this, &CaptureWidget::setDrawThickness); - connect(this, &CaptureWidget::colorChanged, - sidePanel, &SidePanelWidget::updateColor); - connect(this, &CaptureWidget::thicknessChanged, - sidePanel, &SidePanelWidget::updateThickness); - connect(sidePanel, &SidePanelWidget::togglePanel, - m_panel, &UtilityPanel::toggle); - sidePanel->colorChanged(m_context.color); - sidePanel->thicknessChanged(m_context.thickness); - m_panel->pushWidget(sidePanel); - m_panel->pushWidget(new QUndoView(&m_undoStack, this)); -} - -void CaptureWidget::initSelection() { - m_selection = new SelectionWidget(m_uiColor, this); - connect(m_selection, &SelectionWidget::animationEnded, this, [this](){ - this->m_buttonHandler->updatePosition(this->m_selection->geometry()); - }); - m_selection->setVisible(false); - m_selection->setGeometry(QRect()); -} - -void CaptureWidget::setState(CaptureButton *b) { - if (!b) { - return; - } - if (m_toolWidget) { - m_toolWidget->deleteLater(); - if (m_activeTool->isValid()) { - pushToolToStack(); - } - } + if (b->tool()->isSelectable()) { if (m_activeButton != b) { - processTool(b->tool()); - } - // Only close activated from button - if (b->tool()->closeOnButtonPressed()) { - close(); - } - - if (b->tool()->isSelectable()) { - if (m_activeButton != b) { - QWidget *confW = b->tool()->configurationWidget(); - m_panel->addToolWidget(confW); - if (m_activeButton) { - m_activeButton->setColor(m_uiColor); - } - m_activeButton = b; - m_activeButton->setColor(m_contrastUiColor); - } else if (m_activeButton) { - m_panel->clearToolWidget(); - m_activeButton->setColor(m_uiColor); - m_activeButton = nullptr; - } - update(); // clear mouse preview + QWidget* confW = b->tool()->configurationWidget(); + m_panel->addToolWidget(confW); + if (m_activeButton) { + m_activeButton->setColor(m_uiColor); + } + m_activeButton = b; + m_activeButton->setColor(m_contrastUiColor); + } else if (m_activeButton) { + m_panel->clearToolWidget(); + m_activeButton->setColor(m_uiColor); + m_activeButton = nullptr; } + update(); // clear mouse preview + } } -void CaptureWidget::processTool(CaptureTool *t) { - auto backup = m_activeTool; - // The tool is active during the pressed(). - m_activeTool = t; - t->pressed(m_context); - m_activeTool = backup; +void +CaptureWidget::processTool(CaptureTool* t) +{ + auto backup = m_activeTool; + // The tool is active during the pressed(). + m_activeTool = t; + t->pressed(m_context); + m_activeTool = backup; } -void CaptureWidget::handleButtonSignal(CaptureTool::Request r) { - switch (r) { +void +CaptureWidget::handleButtonSignal(CaptureTool::Request r) +{ + switch (r) { case CaptureTool::REQ_CLEAR_MODIFICATIONS: - m_undoStack.setIndex(0); - update(); - break; + m_undoStack.setIndex(0); + update(); + break; case CaptureTool::REQ_INCREMENT_CIRCLE_COUNT: - incrementCircleCount(); - break; + incrementCircleCount(); + break; case CaptureTool::REQ_CLOSE_GUI: - close(); - break; + close(); + break; case CaptureTool::REQ_HIDE_GUI: - hide(); - break; + hide(); + break; case CaptureTool::REQ_HIDE_SELECTION: - m_newSelection = true; - m_selection->setVisible(false); - updateCursor(); - break; + m_newSelection = true; + m_selection->setVisible(false); + updateCursor(); + break; case CaptureTool::REQ_SELECT_ALL: - m_selection->setGeometryAnimated(rect()); - break; + m_selection->setGeometryAnimated(rect()); + break; case CaptureTool::REQ_UNDO_MODIFICATION: - m_undoStack.undo(); - break; + m_undoStack.undo(); + break; case CaptureTool::REQ_REDO_MODIFICATION: - m_undoStack.redo(); - break; + m_undoStack.redo(); + break; case CaptureTool::REQ_REDRAW: - update(); - break; + update(); + break; case CaptureTool::REQ_TOGGLE_SIDEBAR: - m_panel->toggle(); - break; + m_panel->toggle(); + break; case CaptureTool::REQ_SHOW_COLOR_PICKER: - // TODO - break; + // TODO + break; case CaptureTool::REQ_MOVE_MODE: - setState(m_activeButton); // Disable the actual button - break; + setState(m_activeButton); // Disable the actual button + break; case CaptureTool::REQ_CAPTURE_DONE_OK: - m_captureDone = true; - break; + m_captureDone = true; + break; case CaptureTool::REQ_ADD_CHILD_WIDGET: - if (!m_activeTool) { - break; - } - if (m_toolWidget) { - m_toolWidget->deleteLater(); - } - m_toolWidget = m_activeTool->widget(); - if (m_toolWidget) { - makeChild(m_toolWidget); - m_toolWidget->move(m_context.mousePos); - m_toolWidget->show(); - m_toolWidget->setFocus(); - } + if (!m_activeTool) { break; + } + if (m_toolWidget) { + m_toolWidget->deleteLater(); + } + m_toolWidget = m_activeTool->widget(); + if (m_toolWidget) { + makeChild(m_toolWidget); + m_toolWidget->move(m_context.mousePos); + m_toolWidget->show(); + m_toolWidget->setFocus(); + } + break; case CaptureTool::REQ_ADD_CHILD_WINDOW: - if (!m_activeTool) { - break; - } else { - QWidget *w = m_activeTool->widget(); - connect(this, &CaptureWidget::destroyed, w, &QWidget::deleteLater); - w->show(); - } + if (!m_activeTool) { break; + } else { + QWidget* w = m_activeTool->widget(); + connect(this, &CaptureWidget::destroyed, w, &QWidget::deleteLater); + w->show(); + } + break; case CaptureTool::REQ_ADD_EXTERNAL_WIDGETS: - if (!m_activeTool) { - break; - } else { - QWidget *w = m_activeTool->widget(); - w->setAttribute(Qt::WA_DeleteOnClose); - w->show(); - } + if (!m_activeTool) { break; + } else { + QWidget* w = m_activeTool->widget(); + w->setAttribute(Qt::WA_DeleteOnClose); + w->show(); + } + break; default: - break; - } + break; + } } -void CaptureWidget::setDrawColor(const QColor &c) { - m_context.color = c; - ConfigHandler().setDrawColor(m_context.color); - emit colorChanged(c); -} - -void CaptureWidget::incrementCircleCount() +void +CaptureWidget::setDrawColor(const QColor& c) { - m_context.circleCount++; + m_context.color = c; + ConfigHandler().setDrawColor(m_context.color); + emit colorChanged(c); } - void CaptureWidget::setDrawThickness(const int &t) +void +CaptureWidget::incrementCircleCount() { - m_context.thickness = qBound(0, t, 100); - ConfigHandler().setdrawThickness(m_context.thickness); - emit thicknessChanged(m_context.thickness); + m_context.circleCount++; } -void CaptureWidget::leftResize() { - if (m_selection->isVisible() && m_selection->geometry().right() > m_selection->geometry().left()) { - m_selection->setGeometry(m_selection->geometry() + QMargins(0, 0, -1, 0)); - QRect newGeometry = m_selection->geometry().intersected(rect()); - m_context.selection = extendedRect(&newGeometry); - m_buttonHandler->updatePosition(m_selection->geometry()); - updateSizeIndicator(); - update(); - } +void +CaptureWidget::setDrawThickness(const int& t) +{ + m_context.thickness = qBound(0, t, 100); + ConfigHandler().setdrawThickness(m_context.thickness); + emit thicknessChanged(m_context.thickness); } -void CaptureWidget::rightResize() { - if (m_selection->isVisible() && m_selection->geometry().right() < rect().right()) { - m_selection->setGeometry(m_selection->geometry() + QMargins(0, 0, 1, 0)); - QRect newGeometry = m_selection->geometry().intersected(rect()); - m_context.selection = extendedRect(&newGeometry); - m_buttonHandler->updatePosition(m_selection->geometry()); - updateSizeIndicator(); - update(); - } -} - -void CaptureWidget::upResize() { - if (m_selection->isVisible() && m_selection->geometry().bottom() > m_selection->geometry().top()) { - m_selection->setGeometry(m_selection->geometry() + QMargins(0, 0, 0, -1)); - QRect newGeometry = m_selection->geometry().intersected(rect()); - m_context.selection = extendedRect(&newGeometry); - m_buttonHandler->updatePosition(m_selection->geometry()); - updateSizeIndicator(); - update(); - } -} - -void CaptureWidget::downResize() { - if (m_selection->isVisible() && m_selection->geometry().bottom() < rect().bottom()) { - m_selection->setGeometry(m_selection->geometry() + QMargins(0, 0, 0, 1)); - QRect newGeometry = m_selection->geometry().intersected(rect()); - m_context.selection = extendedRect(&newGeometry); - m_buttonHandler->updatePosition(m_selection->geometry()); - updateSizeIndicator(); - update(); - } -} - -void CaptureWidget::initShortcuts() { - new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_Q), this, SLOT(close())); - new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_S), this, SLOT(saveScreenshot())); - new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_C), this, SLOT(copyScreenshot())); - new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_Z), this, SLOT(undo())); - new QShortcut(QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_Z), this, SLOT(redo())); - new QShortcut(QKeySequence(Qt::SHIFT + Qt::Key_Right), this, SLOT(rightResize())); - new QShortcut(QKeySequence(Qt::SHIFT + Qt::Key_Left), this, SLOT(leftResize())); - new QShortcut(QKeySequence(Qt::SHIFT + Qt::Key_Up), this, SLOT(upResize())); - new QShortcut(QKeySequence(Qt::SHIFT + Qt::Key_Down), this, SLOT(downResize())); - new QShortcut(Qt::Key_Space, this, SLOT(togglePanel())); - new QShortcut(Qt::Key_Escape, this, SLOT(deleteToolwidgetOrClose())); - new QShortcut(Qt::Key_Return, this, SLOT(copyScreenshot())); - new QShortcut(Qt::Key_Enter, this, SLOT(copyScreenshot())); -} - -void CaptureWidget::updateSizeIndicator() { - if (m_sizeIndButton){ - const QRect &selection = extendedSelection(); - m_sizeIndButton->setText(QStringLiteral("%1\n%2") - .arg(selection.width()) - .arg(selection.height())); - } -} - -void CaptureWidget::updateCursor() { - if (m_rightClick) { - setCursor(Qt::ArrowCursor); - } else if (m_grabbing) { - setCursor(Qt::ClosedHandCursor); - } else if (!m_activeButton) { - using sw = SelectionWidget; - if (m_mouseOverHandle != sw::NO_SIDE){ - // cursor on the handlers - switch (m_mouseOverHandle) { - case sw::TOPLEFT_SIDE: case sw::BOTTONRIGHT_SIDE: - setCursor(Qt::SizeFDiagCursor); - break; - case sw::TOPRIGHT_SIDE: case sw::BOTTONLEFT_SIDE: - setCursor(Qt::SizeBDiagCursor); - break; - case sw::LEFT_SIDE: case sw::RIGHT_SIDE: - setCursor(Qt::SizeHorCursor); - break; - case sw::TOP_SIDE: case sw::BOTTON_SIDE: - setCursor(Qt::SizeVerCursor); - break; - default: - break; - } - } else if (m_selection->isVisible() && - m_selection->geometry().contains(m_context.mousePos)) - { - setCursor(Qt::OpenHandCursor); - } else { - setCursor(Qt::CrossCursor); - } - } else { - setCursor(Qt::CrossCursor); - } -} - -void CaptureWidget::pushToolToStack() { - auto mod = new ModificationCommand( - &m_context.screenshot, m_activeTool); - disconnect(this, &CaptureWidget::colorChanged, - m_activeTool, &CaptureTool::colorChanged); - disconnect(this, &CaptureWidget::thicknessChanged, - m_activeTool, &CaptureTool::thicknessChanged); - if (m_panel->toolWidget()) { - disconnect(m_panel->toolWidget(), nullptr, m_activeTool, nullptr); - } - m_undoStack.push(mod); - m_activeTool = nullptr; -} - -void CaptureWidget::makeChild(QWidget *w) { - w->setParent(this); - w->installEventFilter(m_eventFilter); -} - -void CaptureWidget::togglePanel() { - m_panel->toggle(); -} - -void CaptureWidget::childEnter() { - m_previewEnabled = false; +void +CaptureWidget::leftResize() +{ + if (m_selection->isVisible() && + m_selection->geometry().right() > m_selection->geometry().left()) { + m_selection->setGeometry(m_selection->geometry() + QMargins(0, 0, -1, 0)); + QRect newGeometry = m_selection->geometry().intersected(rect()); + m_context.selection = extendedRect(&newGeometry); + m_buttonHandler->updatePosition(m_selection->geometry()); + updateSizeIndicator(); update(); + } } -void CaptureWidget::childLeave() { - m_previewEnabled = true; +void +CaptureWidget::rightResize() +{ + if (m_selection->isVisible() && + m_selection->geometry().right() < rect().right()) { + m_selection->setGeometry(m_selection->geometry() + QMargins(0, 0, 1, 0)); + QRect newGeometry = m_selection->geometry().intersected(rect()); + m_context.selection = extendedRect(&newGeometry); + m_buttonHandler->updatePosition(m_selection->geometry()); + updateSizeIndicator(); update(); + } } -void CaptureWidget::copyScreenshot() { - m_captureDone = true; - ScreenshotSaver().saveToClipboard(pixmap()); - close(); +void +CaptureWidget::upResize() +{ + if (m_selection->isVisible() && + m_selection->geometry().bottom() > m_selection->geometry().top()) { + m_selection->setGeometry(m_selection->geometry() + QMargins(0, 0, 0, -1)); + QRect newGeometry = m_selection->geometry().intersected(rect()); + m_context.selection = extendedRect(&newGeometry); + m_buttonHandler->updatePosition(m_selection->geometry()); + updateSizeIndicator(); + update(); + } } -void CaptureWidget::saveScreenshot() { - m_captureDone = true; - hide(); - if (m_context.savePath.isEmpty()) { - ScreenshotSaver().saveToFilesystemGUI(pixmap()); +void +CaptureWidget::downResize() +{ + if (m_selection->isVisible() && + m_selection->geometry().bottom() < rect().bottom()) { + m_selection->setGeometry(m_selection->geometry() + QMargins(0, 0, 0, 1)); + QRect newGeometry = m_selection->geometry().intersected(rect()); + m_context.selection = extendedRect(&newGeometry); + m_buttonHandler->updatePosition(m_selection->geometry()); + updateSizeIndicator(); + update(); + } +} + +void +CaptureWidget::initShortcuts() +{ + new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_Q), this, SLOT(close())); + new QShortcut( + QKeySequence(Qt::CTRL + Qt::Key_S), this, SLOT(saveScreenshot())); + new QShortcut( + QKeySequence(Qt::CTRL + Qt::Key_C), this, SLOT(copyScreenshot())); + new QShortcut(QKeySequence(Qt::CTRL + Qt::Key_Z), this, SLOT(undo())); + new QShortcut( + QKeySequence(Qt::CTRL + Qt::SHIFT + Qt::Key_Z), this, SLOT(redo())); + new QShortcut( + QKeySequence(Qt::SHIFT + Qt::Key_Right), this, SLOT(rightResize())); + new QShortcut( + QKeySequence(Qt::SHIFT + Qt::Key_Left), this, SLOT(leftResize())); + new QShortcut(QKeySequence(Qt::SHIFT + Qt::Key_Up), this, SLOT(upResize())); + new QShortcut( + QKeySequence(Qt::SHIFT + Qt::Key_Down), this, SLOT(downResize())); + new QShortcut(Qt::Key_Space, this, SLOT(togglePanel())); + new QShortcut(Qt::Key_Escape, this, SLOT(deleteToolwidgetOrClose())); + new QShortcut(Qt::Key_Return, this, SLOT(copyScreenshot())); + new QShortcut(Qt::Key_Enter, this, SLOT(copyScreenshot())); +} + +void +CaptureWidget::updateSizeIndicator() +{ + if (m_sizeIndButton) { + const QRect& selection = extendedSelection(); + m_sizeIndButton->setText( + QStringLiteral("%1\n%2").arg(selection.width()).arg(selection.height())); + } +} + +void +CaptureWidget::updateCursor() +{ + if (m_rightClick) { + setCursor(Qt::ArrowCursor); + } else if (m_grabbing) { + setCursor(Qt::ClosedHandCursor); + } else if (!m_activeButton) { + using sw = SelectionWidget; + if (m_mouseOverHandle != sw::NO_SIDE) { + // cursor on the handlers + switch (m_mouseOverHandle) { + case sw::TOPLEFT_SIDE: + case sw::BOTTONRIGHT_SIDE: + setCursor(Qt::SizeFDiagCursor); + break; + case sw::TOPRIGHT_SIDE: + case sw::BOTTONLEFT_SIDE: + setCursor(Qt::SizeBDiagCursor); + break; + case sw::LEFT_SIDE: + case sw::RIGHT_SIDE: + setCursor(Qt::SizeHorCursor); + break; + case sw::TOP_SIDE: + case sw::BOTTON_SIDE: + setCursor(Qt::SizeVerCursor); + break; + default: + break; + } + } else if (m_selection->isVisible() && + m_selection->geometry().contains(m_context.mousePos)) { + setCursor(Qt::OpenHandCursor); } else { - ScreenshotSaver().saveToFilesystem(pixmap(), m_context.savePath); + setCursor(Qt::CrossCursor); } - close(); + } else { + setCursor(Qt::CrossCursor); + } } -void CaptureWidget::undo() { - m_undoStack.undo(); +void +CaptureWidget::pushToolToStack() +{ + auto mod = new ModificationCommand(&m_context.screenshot, m_activeTool); + disconnect(this, + &CaptureWidget::colorChanged, + m_activeTool, + &CaptureTool::colorChanged); + disconnect(this, + &CaptureWidget::thicknessChanged, + m_activeTool, + &CaptureTool::thicknessChanged); + if (m_panel->toolWidget()) { + disconnect(m_panel->toolWidget(), nullptr, m_activeTool, nullptr); + } + m_undoStack.push(mod); + m_activeTool = nullptr; } -void CaptureWidget::redo() { - m_undoStack.redo(); +void +CaptureWidget::makeChild(QWidget* w) +{ + w->setParent(this); + w->installEventFilter(m_eventFilter); } -QRect CaptureWidget::extendedSelection() const { - if (!m_selection->isVisible()) - return QRect(); - QRect r = m_selection->geometry(); - return extendedRect(&r); +void +CaptureWidget::togglePanel() +{ + m_panel->toggle(); } -QRect CaptureWidget::extendedRect(QRect *r) const { - auto devicePixelRatio = m_context.screenshot.devicePixelRatio(); - return QRect(r->left() * devicePixelRatio, - r->top() * devicePixelRatio, - r->width() * devicePixelRatio, - r->height() * devicePixelRatio); +void +CaptureWidget::childEnter() +{ + m_previewEnabled = false; + update(); +} + +void +CaptureWidget::childLeave() +{ + m_previewEnabled = true; + update(); +} + +void +CaptureWidget::copyScreenshot() +{ + m_captureDone = true; + ScreenshotSaver().saveToClipboard(pixmap()); + close(); +} + +void +CaptureWidget::saveScreenshot() +{ + m_captureDone = true; + hide(); + if (m_context.savePath.isEmpty()) { + ScreenshotSaver().saveToFilesystemGUI(pixmap()); + } else { + ScreenshotSaver().saveToFilesystem(pixmap(), m_context.savePath); + } + close(); +} + +void +CaptureWidget::undo() +{ + m_undoStack.undo(); +} + +void +CaptureWidget::redo() +{ + m_undoStack.redo(); +} + +QRect +CaptureWidget::extendedSelection() const +{ + if (!m_selection->isVisible()) + return QRect(); + QRect r = m_selection->geometry(); + return extendedRect(&r); +} + +QRect +CaptureWidget::extendedRect(QRect* r) const +{ + auto devicePixelRatio = m_context.screenshot.devicePixelRatio(); + return QRect(r->left() * devicePixelRatio, + r->top() * devicePixelRatio, + r->width() * devicePixelRatio, + r->height() * devicePixelRatio); } diff --git a/src/widgets/capture/capturewidget.h b/src/widgets/capture/capturewidget.h index c33157c4..c203e3f5 100644 --- a/src/widgets/capture/capturewidget.h +++ b/src/widgets/capture/capturewidget.h @@ -15,24 +15,26 @@ // You should have received a copy of the GNU General Public License // along with Flameshot. If not, see . -// Based on Lightscreen areadialog.h, Copyright 2017 Christian Kaiser -// released under the GNU GPL2 +// Based on Lightscreen areadialog.h, Copyright 2017 Christian Kaiser +// released under the GNU GPL2 +// -// Based on KDE's KSnapshot regiongrabber.cpp, revision 796531, Copyright 2007 Luca Gugelmann -// released under the GNU LGPL +// Based on KDE's KSnapshot regiongrabber.cpp, revision 796531, Copyright 2007 +// Luca Gugelmann released under the GNU LGPL +// #pragma once +#include "buttonhandler.h" #include "capturebutton.h" #include "src/tools/capturecontext.h" #include "src/tools/capturetool.h" #include "src/utils/confighandler.h" #include "src/widgets/capture/selectionwidget.h" #include "src/widgets/panel/utilitypanel.h" -#include "buttonhandler.h" -#include -#include #include +#include +#include class QPaintEvent; class QResizeEvent; @@ -45,115 +47,113 @@ class Screenshot; class NotifierBox; class HoverEventFilter; -class CaptureWidget : public QWidget { - Q_OBJECT +class CaptureWidget : public QWidget +{ + Q_OBJECT public: + explicit CaptureWidget(const uint id = 0, + const QString& savePath = QString(), + bool fullScreen = true, + QWidget* parent = nullptr); + ~CaptureWidget(); - explicit CaptureWidget(const uint id = 0, - const QString &savePath = QString(), - bool fullScreen = true, - QWidget *parent = nullptr); - ~CaptureWidget(); - - - void updateButtons(); - QPixmap pixmap(); + void updateButtons(); + QPixmap pixmap(); public slots: - void deleteToolwidgetOrClose(); + void deleteToolwidgetOrClose(); signals: - void captureTaken(uint id, QPixmap p); - void captureFailed(uint id); - void colorChanged(const QColor &c); - void thicknessChanged(const int thickness); + void captureTaken(uint id, QPixmap p); + void captureFailed(uint id); + void colorChanged(const QColor& c); + void thicknessChanged(const int thickness); private slots: - // TODO replace with tools - void copyScreenshot(); - void saveScreenshot(); - void undo(); - void redo(); - void togglePanel(); - void childEnter(); - void childLeave(); + // TODO replace with tools + void copyScreenshot(); + void saveScreenshot(); + void undo(); + void redo(); + void togglePanel(); + void childEnter(); + void childLeave(); - void leftResize(); - void rightResize(); - void upResize(); - void downResize(); + void leftResize(); + void rightResize(); + void upResize(); + void downResize(); + + void setState(CaptureButton* b); + void processTool(CaptureTool* t); + void handleButtonSignal(CaptureTool::Request r); + void setDrawColor(const QColor& c); + void setDrawThickness(const int& t); + void incrementCircleCount(); - void setState(CaptureButton *b); - void processTool(CaptureTool *t); - void handleButtonSignal(CaptureTool::Request r); - void setDrawColor(const QColor &c); - void setDrawThickness(const int &t); - void incrementCircleCount(); protected: - void paintEvent(QPaintEvent *); - void mousePressEvent(QMouseEvent *); - void mouseMoveEvent(QMouseEvent *); - void mouseReleaseEvent(QMouseEvent *); - void keyPressEvent(QKeyEvent *); - void keyReleaseEvent(QKeyEvent *); - void wheelEvent(QWheelEvent *); - void resizeEvent(QResizeEvent *); - void moveEvent(QMoveEvent *); + void paintEvent(QPaintEvent*); + void mousePressEvent(QMouseEvent*); + void mouseMoveEvent(QMouseEvent*); + void mouseReleaseEvent(QMouseEvent*); + void keyPressEvent(QKeyEvent*); + void keyReleaseEvent(QKeyEvent*); + void wheelEvent(QWheelEvent*); + void resizeEvent(QResizeEvent*); + void moveEvent(QMoveEvent*); - // Context information - CaptureContext m_context; + // Context information + CaptureContext m_context; - // Main ui color - QColor m_uiColor; - // Secondary ui color - QColor m_contrastUiColor; - - // Outside selection opacity - int m_opacity; - - // utility flags - bool m_mouseIsClicked; - bool m_rightClick; - bool m_newSelection; - bool m_grabbing; - bool m_showInitialMsg; - bool m_captureDone; - bool m_previewEnabled; - bool m_adjustmentButtonPressed; + // Main ui color + QColor m_uiColor; + // Secondary ui color + QColor m_contrastUiColor; + // Outside selection opacity + int m_opacity; + // utility flags + bool m_mouseIsClicked; + bool m_rightClick; + bool m_newSelection; + bool m_grabbing; + bool m_showInitialMsg; + bool m_captureDone; + bool m_previewEnabled; + bool m_adjustmentButtonPressed; private: - void initContext(const QString &savePath, bool fullscreen); - void initPanel(); - void initSelection(); - void initShortcuts(); - void updateSizeIndicator(); - void updateCursor(); - void pushToolToStack(); - void makeChild(QWidget *w); + void initContext(const QString& savePath, bool fullscreen); + void initPanel(); + void initSelection(); + void initShortcuts(); + void updateSizeIndicator(); + void updateCursor(); + void pushToolToStack(); + void makeChild(QWidget* w); - QRect extendedSelection() const; - QRect extendedRect(QRect *r) const; + QRect extendedSelection() const; + QRect extendedRect(QRect* r) const; - QUndoStack m_undoStack; - QPointer m_sizeIndButton; - // Last pressed button - QPointer m_activeButton; - QPointer m_activeTool; - QPointer m_toolWidget; + QUndoStack m_undoStack; + QPointer m_sizeIndButton; + // Last pressed button + QPointer m_activeButton; + QPointer m_activeTool; + QPointer m_toolWidget; - ButtonHandler *m_buttonHandler; - UtilityPanel *m_panel; - ColorPicker *m_colorPicker; - ConfigHandler m_config; - NotifierBox *m_notifierBox; - HoverEventFilter *m_eventFilter; - SelectionWidget *m_selection; + ButtonHandler* m_buttonHandler; + UtilityPanel* m_panel; + ColorPicker* m_colorPicker; + ConfigHandler m_config; + NotifierBox* m_notifierBox; + HoverEventFilter* m_eventFilter; + SelectionWidget* m_selection; - QPoint m_dragStartPoint; - SelectionWidget::SideType m_mouseOverHandle; - uint m_id; + QPoint m_dragStartPoint; + SelectionWidget::SideType m_mouseOverHandle; + uint m_id; }; diff --git a/src/widgets/capture/colorpicker.cpp b/src/widgets/capture/colorpicker.cpp index 249330b4..b3f34123 100644 --- a/src/widgets/capture/colorpicker.cpp +++ b/src/widgets/capture/colorpicker.cpp @@ -18,93 +18,108 @@ #include "colorpicker.h" #include "src/utils/confighandler.h" #include "src/utils/globalvalues.h" -#include #include +#include -ColorPicker::ColorPicker(QWidget *parent) : QWidget(parent) { - ConfigHandler config; - m_colorList = config.getUserColors(); - m_colorAreaSize = GlobalValues::buttonBaseSize() * 0.6; - setMouseTracking(true); - // save the color values in member variables for faster access - m_uiColor = config.uiMainColorValue(); - m_drawColor = config.drawColorValue(); - // extraSize represents the extra space needed for the highlight of the - // selected color. - const int extraSize = 6; - double radius = (m_colorList.size()*m_colorAreaSize/1.3)/(3.141592); - resize(radius*2 + m_colorAreaSize + extraSize, - radius*2 + m_colorAreaSize+ extraSize); - double degree = 360 / (m_colorList.size()); - double degreeAcum = degree; - // this line is the radius of the circle which will be rotated to add - // the color components. - QLineF baseLine = QLineF(QPoint(radius+extraSize/2, radius+extraSize/2), - QPoint(radius*2, radius)); +ColorPicker::ColorPicker(QWidget* parent) + : QWidget(parent) +{ + ConfigHandler config; + m_colorList = config.getUserColors(); + m_colorAreaSize = GlobalValues::buttonBaseSize() * 0.6; + setMouseTracking(true); + // save the color values in member variables for faster access + m_uiColor = config.uiMainColorValue(); + m_drawColor = config.drawColorValue(); + // extraSize represents the extra space needed for the highlight of the + // selected color. + const int extraSize = 6; + double radius = (m_colorList.size() * m_colorAreaSize / 1.3) / (3.141592); + resize(radius * 2 + m_colorAreaSize + extraSize, + radius * 2 + m_colorAreaSize + extraSize); + double degree = 360 / (m_colorList.size()); + double degreeAcum = degree; + // this line is the radius of the circle which will be rotated to add + // the color components. + QLineF baseLine = + QLineF(QPoint(radius + extraSize / 2, radius + extraSize / 2), + QPoint(radius * 2, radius)); - for (int i = 0; i rects = handleMask(); + painter.setPen(QColor(Qt::black)); + for (int i = 0; i < rects.size(); ++i) { + // draw the highlight when we have to draw the selected color + if (m_drawColor == QColor(m_colorList.at(i))) { + QColor c = QColor(m_uiColor); + c.setAlpha(155); + painter.setBrush(c); + c.setAlpha(100); + painter.setPen(c); + QRect highlight = rects.at(i); + highlight.moveTo(highlight.x() - 3, highlight.y() - 3); + highlight.setHeight(highlight.height() + 6); + highlight.setWidth(highlight.width() + 6); + painter.drawRoundedRect(highlight, 100, 100); + painter.setPen(QColor(Qt::black)); } + painter.setBrush(QColor(m_colorList.at(i))); + painter.drawRoundedRect(rects.at(i), 100, 100); + } } -QColor ColorPicker::drawColor() { - return m_drawColor; -} - -void ColorPicker::show() { - grabMouse(); - QWidget::show(); -} - -void ColorPicker::hide() { - releaseMouse(); - QWidget::hide(); -} - -void ColorPicker::paintEvent(QPaintEvent *) { - QPainter painter(this); - painter.setRenderHint(QPainter::Antialiasing); - - QVector rects = handleMask(); - painter.setPen(QColor(Qt::black)); - for (int i = 0; i < rects.size(); ++i) { - // draw the highlight when we have to draw the selected color - if (m_drawColor == QColor(m_colorList.at(i))) { - QColor c = QColor(m_uiColor); - c.setAlpha(155); - painter.setBrush(c); - c.setAlpha(100); - painter.setPen(c); - QRect highlight = rects.at(i); - highlight.moveTo(highlight.x() - 3, highlight.y() - 3); - highlight.setHeight(highlight.height() + 6); - highlight.setWidth(highlight.width() + 6); - painter.drawRoundedRect(highlight, 100, 100); - painter.setPen(QColor(Qt::black)); - } - painter.setBrush(QColor(m_colorList.at(i))); - painter.drawRoundedRect(rects.at(i), 100, 100); +void +ColorPicker::mouseMoveEvent(QMouseEvent* e) +{ + for (int i = 0; i < m_colorList.size(); ++i) { + if (m_colorAreaList.at(i).contains(e->pos())) { + m_drawColor = m_colorList.at(i); + emit colorSelected(m_drawColor); + update(); + break; } + } } -void ColorPicker::mouseMoveEvent(QMouseEvent *e) { - for (int i = 0; i < m_colorList.size(); ++i) { - if (m_colorAreaList.at(i).contains(e->pos())) { - m_drawColor = m_colorList.at(i); - emit colorSelected(m_drawColor); - update(); - break; - } - } -} - -QVector ColorPicker::handleMask() const { - QVector areas; - for (const QRect &rect: m_colorAreaList) { - areas.append(rect); - } - return areas; +QVector +ColorPicker::handleMask() const +{ + QVector areas; + for (const QRect& rect : m_colorAreaList) { + areas.append(rect); + } + return areas; } diff --git a/src/widgets/capture/colorpicker.h b/src/widgets/capture/colorpicker.h index 47f6d17b..bbf98a75 100644 --- a/src/widgets/capture/colorpicker.h +++ b/src/widgets/capture/colorpicker.h @@ -19,29 +19,30 @@ #include -class ColorPicker : public QWidget { - Q_OBJECT +class ColorPicker : public QWidget +{ + Q_OBJECT public: - explicit ColorPicker(QWidget *parent = nullptr); + explicit ColorPicker(QWidget* parent = nullptr); - QColor drawColor(); + QColor drawColor(); - void show(); - void hide(); + void show(); + void hide(); signals: - void colorSelected(QColor c); + void colorSelected(QColor c); protected: - void paintEvent(QPaintEvent *); - void mouseMoveEvent(QMouseEvent *); + void paintEvent(QPaintEvent*); + void mouseMoveEvent(QMouseEvent*); - QVector handleMask() const; + QVector handleMask() const; private: - int m_colorAreaSize; - QVector m_colorAreaList; - QVector m_colorList; + int m_colorAreaSize; + QVector m_colorAreaList; + QVector m_colorList; - QColor m_uiColor, m_drawColor; + QColor m_uiColor, m_drawColor; }; diff --git a/src/widgets/capture/hovereventfilter.cpp b/src/widgets/capture/hovereventfilter.cpp index 687711ad..32ad19db 100644 --- a/src/widgets/capture/hovereventfilter.cpp +++ b/src/widgets/capture/hovereventfilter.cpp @@ -15,30 +15,34 @@ // You should have received a copy of the GNU General Public License // along with Flameshot. If not, see . -// Based on Lightscreen areadialog.h, Copyright 2017 Christian Kaiser -// released under the GNU GPL2 +// Based on Lightscreen areadialog.h, Copyright 2017 Christian Kaiser +// released under the GNU GPL2 +// -// Based on KDE's KSnapshot regiongrabber.cpp, revision 796531, Copyright 2007 Luca Gugelmann -// released under the GNU LGPL +// Based on KDE's KSnapshot regiongrabber.cpp, revision 796531, Copyright 2007 +// Luca Gugelmann released under the GNU LGPL +// #include "hovereventfilter.h" #include -HoverEventFilter::HoverEventFilter(QObject *parent) : QObject(parent) { +HoverEventFilter::HoverEventFilter(QObject* parent) + : QObject(parent) +{} -} - -bool HoverEventFilter::eventFilter(QObject *watched, QEvent *event) { - QEvent::Type t = event->type(); - switch (t) { +bool +HoverEventFilter::eventFilter(QObject* watched, QEvent* event) +{ + QEvent::Type t = event->type(); + switch (t) { case QEvent::Enter: - emit hoverIn(watched); - break; + emit hoverIn(watched); + break; case QEvent::Leave: - emit hoverOut(watched); - break; + emit hoverOut(watched); + break; default: - break; - } - return false; + break; + } + return false; } diff --git a/src/widgets/capture/hovereventfilter.h b/src/widgets/capture/hovereventfilter.h index 7a26f56d..7a4c41cd 100644 --- a/src/widgets/capture/hovereventfilter.h +++ b/src/widgets/capture/hovereventfilter.h @@ -15,11 +15,13 @@ // You should have received a copy of the GNU General Public License // along with Flameshot. If not, see . -// Based on Lightscreen areadialog.h, Copyright 2017 Christian Kaiser -// released under the GNU GPL2 +// Based on Lightscreen areadialog.h, Copyright 2017 Christian Kaiser +// released under the GNU GPL2 +// -// Based on KDE's KSnapshot regiongrabber.cpp, revision 796531, Copyright 2007 Luca Gugelmann -// released under the GNU LGPL +// Based on KDE's KSnapshot regiongrabber.cpp, revision 796531, Copyright 2007 +// Luca Gugelmann released under the GNU LGPL +// #pragma once @@ -27,14 +29,14 @@ class HoverEventFilter : public QObject { - Q_OBJECT + Q_OBJECT public: - explicit HoverEventFilter(QObject *parent = nullptr); + explicit HoverEventFilter(QObject* parent = nullptr); signals: - void hoverIn(QObject *); - void hoverOut(QObject *); + void hoverIn(QObject*); + void hoverOut(QObject*); protected: - bool eventFilter(QObject *watched, QEvent *event); + bool eventFilter(QObject* watched, QEvent* event); }; diff --git a/src/widgets/capture/modificationcommand.cpp b/src/widgets/capture/modificationcommand.cpp index 737b3b77..178d48b2 100644 --- a/src/widgets/capture/modificationcommand.cpp +++ b/src/widgets/capture/modificationcommand.cpp @@ -18,18 +18,23 @@ #include "modificationcommand.h" #include -ModificationCommand::ModificationCommand(QPixmap *p, CaptureTool *t) : - m_pixmap(p), m_tool(t) +ModificationCommand::ModificationCommand(QPixmap* p, CaptureTool* t) + : m_pixmap(p) + , m_tool(t) { - setText(t->name()); + setText(t->name()); } -void ModificationCommand::undo() { - m_tool->undo(*m_pixmap); +void +ModificationCommand::undo() +{ + m_tool->undo(*m_pixmap); } -void ModificationCommand::redo() { - QPainter p(m_pixmap); - p.setRenderHint(QPainter::Antialiasing); - m_tool->process(p, *m_pixmap, true); +void +ModificationCommand::redo() +{ + QPainter p(m_pixmap); + p.setRenderHint(QPainter::Antialiasing); + m_tool->process(p, *m_pixmap, true); } diff --git a/src/widgets/capture/modificationcommand.h b/src/widgets/capture/modificationcommand.h index 4465fec1..c172d6fd 100644 --- a/src/widgets/capture/modificationcommand.h +++ b/src/widgets/capture/modificationcommand.h @@ -17,17 +17,18 @@ #pragma once -#include #include "src/tools/capturetool.h" +#include -class ModificationCommand : public QUndoCommand { +class ModificationCommand : public QUndoCommand +{ public: - ModificationCommand(QPixmap *, CaptureTool *); + ModificationCommand(QPixmap*, CaptureTool*); - virtual void undo() override; - virtual void redo() override; + virtual void undo() override; + virtual void redo() override; private: - QPixmap *m_pixmap; - QScopedPointer m_tool; + QPixmap* m_pixmap; + QScopedPointer m_tool; }; diff --git a/src/widgets/capture/notifierbox.cpp b/src/widgets/capture/notifierbox.cpp index 93774029..95b55553 100644 --- a/src/widgets/capture/notifierbox.cpp +++ b/src/widgets/capture/notifierbox.cpp @@ -16,52 +16,62 @@ // along with Flameshot. If not, see . #include "notifierbox.h" -#include "src/utils/confighandler.h" #include "src/utils/colorutils.h" +#include "src/utils/confighandler.h" #include "src/utils/globalvalues.h" -#include -#include #include +#include +#include -NotifierBox::NotifierBox(QWidget *parent) : QWidget(parent) { - m_timer = new QTimer(this); - m_timer->setSingleShot(true); - m_timer->setInterval(1200); - connect(m_timer, &QTimer::timeout, this, &NotifierBox::hide); - m_bgColor = ConfigHandler().uiMainColorValue(); - m_foregroundColor = (ColorUtils::colorIsDark(m_bgColor) ? - Qt::white : Qt::black); - m_bgColor.setAlpha(180); - const int size = (GlobalValues::buttonBaseSize() + - GlobalValues::buttonBaseSize()/2) * - qApp->devicePixelRatio(); - setFixedSize(QSize(size, size)); +NotifierBox::NotifierBox(QWidget* parent) + : QWidget(parent) +{ + m_timer = new QTimer(this); + m_timer->setSingleShot(true); + m_timer->setInterval(1200); + connect(m_timer, &QTimer::timeout, this, &NotifierBox::hide); + m_bgColor = ConfigHandler().uiMainColorValue(); + m_foregroundColor = + (ColorUtils::colorIsDark(m_bgColor) ? Qt::white : Qt::black); + m_bgColor.setAlpha(180); + const int size = + (GlobalValues::buttonBaseSize() + GlobalValues::buttonBaseSize() / 2) * + qApp->devicePixelRatio(); + setFixedSize(QSize(size, size)); } -void NotifierBox::enterEvent(QEvent *) { - hide(); +void +NotifierBox::enterEvent(QEvent*) +{ + hide(); } -void NotifierBox::paintEvent(QPaintEvent *) { - QPainter painter(this); - // draw Elipse - painter.setRenderHint(QPainter::Antialiasing); - painter.setBrush(QBrush(m_bgColor, Qt::SolidPattern)); - painter.setPen(QPen(Qt::transparent)); - painter.drawEllipse(rect()); - // Draw the text: - painter.setPen(QPen(m_foregroundColor)); - painter.drawText(rect(), Qt::AlignCenter, m_message); +void +NotifierBox::paintEvent(QPaintEvent*) +{ + QPainter painter(this); + // draw Elipse + painter.setRenderHint(QPainter::Antialiasing); + painter.setBrush(QBrush(m_bgColor, Qt::SolidPattern)); + painter.setPen(QPen(Qt::transparent)); + painter.drawEllipse(rect()); + // Draw the text: + painter.setPen(QPen(m_foregroundColor)); + painter.drawText(rect(), Qt::AlignCenter, m_message); } -void NotifierBox::showMessage(const QString &msg) { - m_message = msg; - update(); - show(); - m_timer->start(); +void +NotifierBox::showMessage(const QString& msg) +{ + m_message = msg; + update(); + show(); + m_timer->start(); } -void NotifierBox::showColor(const QColor &color) { - Q_UNUSED(color); - m_message = QLatin1String(""); +void +NotifierBox::showColor(const QColor& color) +{ + Q_UNUSED(color); + m_message = QLatin1String(""); } diff --git a/src/widgets/capture/notifierbox.h b/src/widgets/capture/notifierbox.h index e1ecd939..d8b97030 100644 --- a/src/widgets/capture/notifierbox.h +++ b/src/widgets/capture/notifierbox.h @@ -21,22 +21,23 @@ class QTimer; -class NotifierBox : public QWidget { - Q_OBJECT +class NotifierBox : public QWidget +{ + Q_OBJECT public: - explicit NotifierBox(QWidget *parent = nullptr); + explicit NotifierBox(QWidget* parent = nullptr); protected: - virtual void enterEvent(QEvent *); - virtual void paintEvent(QPaintEvent *); + virtual void enterEvent(QEvent*); + virtual void paintEvent(QPaintEvent*); public slots: - void showMessage(const QString &msg); - void showColor(const QColor &color); + void showMessage(const QString& msg); + void showColor(const QColor& color); private: - QTimer *m_timer; - QString m_message; - QColor m_bgColor; - QColor m_foregroundColor; + QTimer* m_timer; + QString m_message; + QColor m_bgColor; + QColor m_foregroundColor; }; diff --git a/src/widgets/capture/selectionwidget.cpp b/src/widgets/capture/selectionwidget.cpp index 1f8eebe0..1ab4df30 100644 --- a/src/widgets/capture/selectionwidget.cpp +++ b/src/widgets/capture/selectionwidget.cpp @@ -20,109 +20,132 @@ #include #include -SelectionWidget::SelectionWidget(const QColor &c, QWidget *parent) : - QWidget(parent), m_color(c) +SelectionWidget::SelectionWidget(const QColor& c, QWidget* parent) + : QWidget(parent) + , m_color(c) { - m_animation = new QPropertyAnimation(this, "geometry", this); - m_animation->setEasingCurve(QEasingCurve::InOutQuad); - m_animation->setDuration(200); - connect(m_animation, &QPropertyAnimation::finished, - this, &SelectionWidget::animationEnded); + m_animation = new QPropertyAnimation(this, "geometry", this); + m_animation->setEasingCurve(QEasingCurve::InOutQuad); + m_animation->setDuration(200); + connect(m_animation, + &QPropertyAnimation::finished, + this, + &SelectionWidget::animationEnded); - setAttribute(Qt::WA_TransparentForMouseEvents); - int sideVal = GlobalValues::buttonBaseSize() * 0.6; - int handleSide = sideVal / 2; - const QRect areaRect(0, 0, sideVal, sideVal); - const QRect handleRect(0, 0, handleSide, handleSide); - m_TLHandle = m_TRHandle = m_BLHandle = m_BRHandle = - m_LHandle = m_THandle = m_RHandle = m_BHandle= handleRect; - m_TLArea = m_TRArea = m_BLArea = m_BRArea = areaRect; + setAttribute(Qt::WA_TransparentForMouseEvents); + int sideVal = GlobalValues::buttonBaseSize() * 0.6; + int handleSide = sideVal / 2; + const QRect areaRect(0, 0, sideVal, sideVal); + const QRect handleRect(0, 0, handleSide, handleSide); + m_TLHandle = m_TRHandle = m_BLHandle = m_BRHandle = m_LHandle = m_THandle = + m_RHandle = m_BHandle = handleRect; + m_TLArea = m_TRArea = m_BLArea = m_BRArea = areaRect; - m_areaOffset = QPoint(-sideVal/2, -sideVal/2); - m_handleOffset = QPoint(-handleSide/2, -handleSide/2); + m_areaOffset = QPoint(-sideVal / 2, -sideVal / 2); + m_handleOffset = QPoint(-handleSide / 2, -handleSide / 2); } -SelectionWidget::SideType SelectionWidget::getMouseSide(const QPoint &point) const { - if (m_TLArea.contains(point)) { - return TOPLEFT_SIDE; - } else if (m_TRArea.contains(point)) { - return TOPRIGHT_SIDE; - } else if (m_BLArea.contains(point)) { - return BOTTONLEFT_SIDE; - } else if (m_BRArea.contains(point)) { - return BOTTONRIGHT_SIDE; - } else if (m_LArea.contains(point)) { - return LEFT_SIDE; - } else if (m_TArea.contains(point)) { - return TOP_SIDE; - } else if (m_RArea.contains(point)) { - return RIGHT_SIDE; - } else if (m_BArea.contains(point)) { - return BOTTON_SIDE; - } else { - return NO_SIDE; - } +SelectionWidget::SideType +SelectionWidget::getMouseSide(const QPoint& point) const +{ + if (m_TLArea.contains(point)) { + return TOPLEFT_SIDE; + } else if (m_TRArea.contains(point)) { + return TOPRIGHT_SIDE; + } else if (m_BLArea.contains(point)) { + return BOTTONLEFT_SIDE; + } else if (m_BRArea.contains(point)) { + return BOTTONRIGHT_SIDE; + } else if (m_LArea.contains(point)) { + return LEFT_SIDE; + } else if (m_TArea.contains(point)) { + return TOP_SIDE; + } else if (m_RArea.contains(point)) { + return RIGHT_SIDE; + } else if (m_BArea.contains(point)) { + return BOTTON_SIDE; + } else { + return NO_SIDE; + } } -QVector SelectionWidget::handlerAreas() { - QVector areas; - areas << m_TLHandle << m_TRHandle << m_BLHandle << m_BRHandle - < +SelectionWidget::handlerAreas() +{ + QVector areas; + areas << m_TLHandle << m_TRHandle << m_BLHandle << m_BRHandle << m_LHandle + << m_THandle << m_RHandle << m_BHandle; + return areas; } -void SelectionWidget::setGeometryAnimated(const QRect &r) { - if (isVisible()) { - m_animation->setStartValue(geometry()); - m_animation->setEndValue(r); - m_animation->start(); - } +void +SelectionWidget::setGeometryAnimated(const QRect& r) +{ + if (isVisible()) { + m_animation->setStartValue(geometry()); + m_animation->setEndValue(r); + m_animation->start(); + } } -void SelectionWidget::saveGeometry() { - m_geometryBackup = geometry(); +void +SelectionWidget::saveGeometry() +{ + m_geometryBackup = geometry(); } -QRect SelectionWidget::savedGeometry() { - return m_geometryBackup; +QRect +SelectionWidget::savedGeometry() +{ + return m_geometryBackup; } -void SelectionWidget::paintEvent(QPaintEvent *) { - QPainter p(this); - p.setPen(m_color); - p.drawRect(rect() + QMargins(0, 0, -1, -1)); +void +SelectionWidget::paintEvent(QPaintEvent*) +{ + QPainter p(this); + p.setPen(m_color); + p.drawRect(rect() + QMargins(0, 0, -1, -1)); } -void SelectionWidget::resizeEvent(QResizeEvent *) { - updateAreas(); +void +SelectionWidget::resizeEvent(QResizeEvent*) +{ + updateAreas(); } -void SelectionWidget::moveEvent(QMoveEvent *) { - updateAreas(); +void +SelectionWidget::moveEvent(QMoveEvent*) +{ + updateAreas(); } -void SelectionWidget::updateColor(const QColor &c) { - m_color = c; +void +SelectionWidget::updateColor(const QColor& c) +{ + m_color = c; } -void SelectionWidget::updateAreas() { - QRect r = rect(); - m_TLArea.moveTo(m_areaOffset + pos()); - m_TRArea.moveTo(r.topRight() + m_areaOffset + pos()); - m_BLArea.moveTo(r.bottomLeft() + m_areaOffset + pos()); - m_BRArea.moveTo(r.bottomRight() + m_areaOffset + pos()); +void +SelectionWidget::updateAreas() +{ + QRect r = rect(); + m_TLArea.moveTo(m_areaOffset + pos()); + m_TRArea.moveTo(r.topRight() + m_areaOffset + pos()); + m_BLArea.moveTo(r.bottomLeft() + m_areaOffset + pos()); + m_BRArea.moveTo(r.bottomRight() + m_areaOffset + pos()); - m_LArea = QRect(m_TLArea.bottomLeft(), m_BLArea.topRight()); - m_TArea = QRect(m_TLArea.topRight(), m_TRArea.bottomLeft()); - m_RArea = QRect(m_TRArea.bottomLeft(), m_BRArea.topRight()); - m_BArea = QRect(m_BLArea.topRight(), m_BRArea.bottomLeft()); + m_LArea = QRect(m_TLArea.bottomLeft(), m_BLArea.topRight()); + m_TArea = QRect(m_TLArea.topRight(), m_TRArea.bottomLeft()); + m_RArea = QRect(m_TRArea.bottomLeft(), m_BRArea.topRight()); + m_BArea = QRect(m_BLArea.topRight(), m_BRArea.bottomLeft()); - m_TLHandle.moveTo(m_TLArea.center() + m_handleOffset); - m_BLHandle.moveTo(m_BLArea.center() + m_handleOffset); - m_TRHandle.moveTo(m_TRArea.center() + m_handleOffset); - m_BRHandle.moveTo(m_BRArea.center() + m_handleOffset); - m_LHandle.moveTo(m_LArea.center() + m_handleOffset); - m_THandle.moveTo(m_TArea.center() + m_handleOffset); - m_RHandle.moveTo(m_RArea.center() + m_handleOffset); - m_BHandle.moveTo(m_BArea.center() + m_handleOffset); + m_TLHandle.moveTo(m_TLArea.center() + m_handleOffset); + m_BLHandle.moveTo(m_BLArea.center() + m_handleOffset); + m_TRHandle.moveTo(m_TRArea.center() + m_handleOffset); + m_BRHandle.moveTo(m_BRArea.center() + m_handleOffset); + m_LHandle.moveTo(m_LArea.center() + m_handleOffset); + m_THandle.moveTo(m_TArea.center() + m_handleOffset); + m_RHandle.moveTo(m_RArea.center() + m_handleOffset); + m_BHandle.moveTo(m_BArea.center() + m_handleOffset); } diff --git a/src/widgets/capture/selectionwidget.h b/src/widgets/capture/selectionwidget.h index 78e3c7e8..b585aa27 100644 --- a/src/widgets/capture/selectionwidget.h +++ b/src/widgets/capture/selectionwidget.h @@ -23,57 +23,58 @@ class QPropertyAnimation; class SelectionWidget : public QWidget { - Q_OBJECT + Q_OBJECT public: - enum SideType { - TOPLEFT_SIDE, - BOTTONLEFT_SIDE, - TOPRIGHT_SIDE, - BOTTONRIGHT_SIDE, - TOP_SIDE, - BOTTON_SIDE, - RIGHT_SIDE, - LEFT_SIDE, - NO_SIDE, - }; + enum SideType + { + TOPLEFT_SIDE, + BOTTONLEFT_SIDE, + TOPRIGHT_SIDE, + BOTTONRIGHT_SIDE, + TOP_SIDE, + BOTTON_SIDE, + RIGHT_SIDE, + LEFT_SIDE, + NO_SIDE, + }; - explicit SelectionWidget(const QColor &c, QWidget *parent = nullptr); + explicit SelectionWidget(const QColor& c, QWidget* parent = nullptr); - SideType getMouseSide(const QPoint &point) const; - QVector handlerAreas(); + SideType getMouseSide(const QPoint& point) const; + QVector handlerAreas(); - void setGeometryAnimated(const QRect &r); - void saveGeometry(); - QRect savedGeometry(); + void setGeometryAnimated(const QRect& r); + void saveGeometry(); + QRect savedGeometry(); protected: - void paintEvent(QPaintEvent *); - void resizeEvent(QResizeEvent *); - void moveEvent(QMoveEvent *); + void paintEvent(QPaintEvent*); + void resizeEvent(QResizeEvent*); + void moveEvent(QMoveEvent*); signals: - void animationEnded(); + void animationEnded(); public slots: - void updateColor(const QColor &c); + void updateColor(const QColor& c); private: - void updateAreas(); + void updateAreas(); - QPropertyAnimation *m_animation; + QPropertyAnimation* m_animation; - QColor m_color; - QPoint m_areaOffset; - QPoint m_handleOffset; - QRect m_geometryBackup; + QColor m_color; + QPoint m_areaOffset; + QPoint m_handleOffset; + QRect m_geometryBackup; - // naming convention for handles - // T top, B bottom, R Right, L left - // 2 letters: a corner - // 1 letter: the handle on the middle of the corresponding side - QRect m_TLHandle, m_TRHandle, m_BLHandle, m_BRHandle; - QRect m_LHandle, m_THandle, m_RHandle, m_BHandle; + // naming convention for handles + // T top, B bottom, R Right, L left + // 2 letters: a corner + // 1 letter: the handle on the middle of the corresponding side + QRect m_TLHandle, m_TRHandle, m_BLHandle, m_BRHandle; + QRect m_LHandle, m_THandle, m_RHandle, m_BHandle; - QRect m_TLArea, m_TRArea, m_BLArea, m_BRArea; - QRect m_LArea, m_TArea, m_RArea, m_BArea; + QRect m_TLArea, m_TRArea, m_BLArea, m_BRArea; + QRect m_LArea, m_TArea, m_RArea, m_BArea; }; diff --git a/src/widgets/capturelauncher.cpp b/src/widgets/capturelauncher.cpp index 268984a6..8722e264 100644 --- a/src/widgets/capturelauncher.cpp +++ b/src/widgets/capturelauncher.cpp @@ -17,126 +17,144 @@ #include "capturelauncher.h" #include "src/core/controller.h" +#include "src/utils/screengrabber.h" #include "src/widgets/imagelabel.h" #include "src/widgets/notificationwidget.h" -#include "src/utils/screengrabber.h" #include -#include -#include -#include -#include -#include #include -#include #include #include +#include +#include +#include +#include +#include +#include // https://github.com/KDE/spectacle/blob/941c1a517be82bed25d1254ebd735c29b0d2951c/src/Gui/KSWidget.cpp // https://github.com/KDE/spectacle/blob/941c1a517be82bed25d1254ebd735c29b0d2951c/src/Gui/KSMainWindow.cpp -CaptureLauncher::CaptureLauncher(QWidget *parent) : - QWidget(parent), m_id(0) +CaptureLauncher::CaptureLauncher(QWidget* parent) + : QWidget(parent) + , m_id(0) { - setAttribute(Qt::WA_DeleteOnClose); - connect(Controller::getInstance(), &Controller::captureTaken, - this, &CaptureLauncher::captureTaken); - connect(Controller::getInstance(), &Controller::captureFailed, - this, &CaptureLauncher::captureFailed); + setAttribute(Qt::WA_DeleteOnClose); + connect(Controller::getInstance(), + &Controller::captureTaken, + this, + &CaptureLauncher::captureTaken); + connect(Controller::getInstance(), + &Controller::captureFailed, + this, + &CaptureLauncher::captureFailed); - m_imageLabel = new ImageLabel(this); - bool ok; - m_imageLabel->setScreenshot(ScreenGrabber().grabEntireDesktop(ok)); - if (!ok) { + m_imageLabel = new ImageLabel(this); + bool ok; + m_imageLabel->setScreenshot(ScreenGrabber().grabEntireDesktop(ok)); + if (!ok) { + } + m_imageLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); + connect(m_imageLabel, + &ImageLabel::dragInitiated, + this, + &CaptureLauncher::startDrag); - } - m_imageLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); - connect(m_imageLabel, &ImageLabel::dragInitiated, - this, &CaptureLauncher::startDrag); + QGridLayout* layout = new QGridLayout(this); + layout->addWidget(m_imageLabel, 0, 0); - QGridLayout *layout = new QGridLayout(this); - layout->addWidget(m_imageLabel, 0, 0); + m_CaptureModeLabel = new QLabel(tr("Capture Mode")); - m_CaptureModeLabel = new QLabel(tr("Capture Mode")); + m_captureType = new QComboBox(); + m_captureType->setMinimumWidth(240); + // TODO remember number + m_captureType->insertItem( + 1, tr("Rectangular Region"), CaptureRequest::GRAPHICAL_MODE); + m_captureType->insertItem( + 2, tr("Full Screen (All Monitors)"), CaptureRequest::FULLSCREEN_MODE); + // m_captureType->insertItem(3, tr("Single Screen"), + // CaptureRequest::SCREEN_MODE); - m_captureType = new QComboBox(); - m_captureType->setMinimumWidth(240); - // TODO remember number - m_captureType->insertItem(1, tr("Rectangular Region"), CaptureRequest::GRAPHICAL_MODE); - m_captureType->insertItem(2, tr("Full Screen (All Monitors)"), CaptureRequest::FULLSCREEN_MODE); - //m_captureType->insertItem(3, tr("Single Screen"), CaptureRequest::SCREEN_MODE); + m_delaySpinBox = new QSpinBox(); + m_delaySpinBox->setSingleStep(1.0); + m_delaySpinBox->setMinimum(0.0); + m_delaySpinBox->setMaximum(999.0); + m_delaySpinBox->setSpecialValueText(tr("No Delay")); + m_delaySpinBox->setMinimumWidth(160); + // with QT 5.7 qOverload(&QSpinBox::valueChanged), + connect(m_delaySpinBox, + static_cast(&QSpinBox::valueChanged), + this, + [this](int val) { + QString sufix = val == 1 ? tr(" second") : tr(" seconds"); + this->m_delaySpinBox->setSuffix(sufix); + }); - m_delaySpinBox = new QSpinBox(); - m_delaySpinBox->setSingleStep(1.0); - m_delaySpinBox->setMinimum(0.0); - m_delaySpinBox->setMaximum(999.0); - m_delaySpinBox->setSpecialValueText(tr("No Delay")); - m_delaySpinBox->setMinimumWidth(160); - // with QT 5.7 qOverload(&QSpinBox::valueChanged), - connect(m_delaySpinBox, - static_cast(&QSpinBox::valueChanged), - this, [this](int val) - { - QString sufix = val == 1 ?tr(" second") : tr(" seconds"); - this->m_delaySpinBox->setSuffix(sufix); - }); + m_launchButton = new QPushButton(tr("Take new screenshot")); + m_launchButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); + connect(m_launchButton, + &QPushButton::pressed, + this, + &CaptureLauncher::startCapture); + m_launchButton->setFocus(); - m_launchButton = new QPushButton(tr("Take new screenshot")); - m_launchButton->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); - connect(m_launchButton, &QPushButton::pressed, - this, &CaptureLauncher::startCapture); - m_launchButton->setFocus(); - - QFormLayout *captureModeForm = new QFormLayout; - captureModeForm->addRow(tr("Area:"), m_captureType); - captureModeForm->addRow(tr("Delay:"), m_delaySpinBox); - captureModeForm->setContentsMargins(24, 0, 0, 0); - - m_mainLayout = new QVBoxLayout(); - m_mainLayout->addStretch(1); - m_mainLayout->addWidget(m_CaptureModeLabel); - m_mainLayout->addLayout(captureModeForm); - m_mainLayout->addStretch(10); - m_mainLayout->addWidget(m_launchButton, 1 , Qt::AlignCenter); - m_mainLayout->setContentsMargins(10, 0, 0, 10); - layout->addLayout(m_mainLayout, 0 ,1); - layout->setColumnMinimumWidth(0, 320); - layout->setColumnMinimumWidth(1, 320); + QFormLayout* captureModeForm = new QFormLayout; + captureModeForm->addRow(tr("Area:"), m_captureType); + captureModeForm->addRow(tr("Delay:"), m_delaySpinBox); + captureModeForm->setContentsMargins(24, 0, 0, 0); + m_mainLayout = new QVBoxLayout(); + m_mainLayout->addStretch(1); + m_mainLayout->addWidget(m_CaptureModeLabel); + m_mainLayout->addLayout(captureModeForm); + m_mainLayout->addStretch(10); + m_mainLayout->addWidget(m_launchButton, 1, Qt::AlignCenter); + m_mainLayout->setContentsMargins(10, 0, 0, 10); + layout->addLayout(m_mainLayout, 0, 1); + layout->setColumnMinimumWidth(0, 320); + layout->setColumnMinimumWidth(1, 320); } -// HACK: https://github.com/KDE/spectacle/blob/fa1e780b8bf3df3ac36c410b9ece4ace041f401b/src/Gui/KSMainWindow.cpp#L70 -void CaptureLauncher::startCapture() { - hide(); - auto mode = static_cast( - m_captureType->currentData().toInt()); - CaptureRequest req(mode, 600 + m_delaySpinBox->value() * 1000); - m_id = req.id(); - Controller::getInstance()->requestCapture(req); +// HACK: +// https://github.com/KDE/spectacle/blob/fa1e780b8bf3df3ac36c410b9ece4ace041f401b/src/Gui/KSMainWindow.cpp#L70 +void +CaptureLauncher::startCapture() +{ + hide(); + auto mode = static_cast( + m_captureType->currentData().toInt()); + CaptureRequest req(mode, 600 + m_delaySpinBox->value() * 1000); + m_id = req.id(); + Controller::getInstance()->requestCapture(req); } -void CaptureLauncher::startDrag() { - QDrag *dragHandler = new QDrag(this); - QMimeData *mimeData = new QMimeData; - mimeData->setImageData(m_imageLabel->pixmap()); - dragHandler->setMimeData(mimeData); +void +CaptureLauncher::startDrag() +{ + QDrag* dragHandler = new QDrag(this); + QMimeData* mimeData = new QMimeData; + mimeData->setImageData(m_imageLabel->pixmap()); + dragHandler->setMimeData(mimeData); - dragHandler->setPixmap(m_imageLabel->pixmap() - ->scaled(256, 256, Qt::KeepAspectRatioByExpanding, - Qt::SmoothTransformation)); - dragHandler->exec(); + dragHandler->setPixmap(m_imageLabel->pixmap()->scaled( + 256, 256, Qt::KeepAspectRatioByExpanding, Qt::SmoothTransformation)); + dragHandler->exec(); } -void CaptureLauncher::captureTaken(uint id, QPixmap p) { - if (id == m_id) { - m_id = 0; - m_imageLabel->setScreenshot(p); - show(); - } +void +CaptureLauncher::captureTaken(uint id, QPixmap p) +{ + if (id == m_id) { + m_id = 0; + m_imageLabel->setScreenshot(p); + show(); + } } -void CaptureLauncher::captureFailed(uint id) { - if (id == m_id) { - m_id = 0; - show(); - } +void +CaptureLauncher::captureFailed(uint id) +{ + if (id == m_id) { + m_id = 0; + show(); + } } diff --git a/src/widgets/capturelauncher.h b/src/widgets/capturelauncher.h index 88c7cb0b..df3f5cc7 100644 --- a/src/widgets/capturelauncher.h +++ b/src/widgets/capturelauncher.h @@ -29,23 +29,22 @@ class ImageLabel; class CaptureLauncher : public QWidget { - Q_OBJECT + Q_OBJECT public: - explicit CaptureLauncher(QWidget *parent = nullptr); + explicit CaptureLauncher(QWidget* parent = nullptr); private slots: - void startCapture(); - void startDrag(); - void captureTaken(uint id, QPixmap p); - void captureFailed(uint id); + void startCapture(); + void startDrag(); + void captureTaken(uint id, QPixmap p); + void captureFailed(uint id); private: - - QSpinBox *m_delaySpinBox; - QComboBox *m_captureType; - QVBoxLayout *m_mainLayout; - QPushButton *m_launchButton; - QLabel *m_CaptureModeLabel; - ImageLabel *m_imageLabel; - uint m_id; + QSpinBox* m_delaySpinBox; + QComboBox* m_captureType; + QVBoxLayout* m_mainLayout; + QPushButton* m_launchButton; + QLabel* m_CaptureModeLabel; + ImageLabel* m_imageLabel; + uint m_id; }; diff --git a/src/widgets/imagelabel.cpp b/src/widgets/imagelabel.cpp index c64cead4..d09a901b 100644 --- a/src/widgets/imagelabel.cpp +++ b/src/widgets/imagelabel.cpp @@ -20,67 +20,79 @@ #include "imagelabel.h" -ImageLabel::ImageLabel(QWidget *parent): - QLabel(parent), m_pixmap(QPixmap()) +ImageLabel::ImageLabel(QWidget* parent) + : QLabel(parent) + , m_pixmap(QPixmap()) { - m_DSEffect = new QGraphicsDropShadowEffect(this); + m_DSEffect = new QGraphicsDropShadowEffect(this); - m_DSEffect->setBlurRadius(5); - m_DSEffect->setOffset(0); - m_DSEffect->setColor(QColor(Qt::black)); + m_DSEffect->setBlurRadius(5); + m_DSEffect->setOffset(0); + m_DSEffect->setColor(QColor(Qt::black)); - setGraphicsEffect(m_DSEffect); - setCursor(Qt::OpenHandCursor); - setAlignment(Qt::AlignCenter); - setMinimumSize(size()); + setGraphicsEffect(m_DSEffect); + setCursor(Qt::OpenHandCursor); + setAlignment(Qt::AlignCenter); + setMinimumSize(size()); } -void ImageLabel::setScreenshot(const QPixmap &pixmap) { - m_pixmap = pixmap; - const QString tooltip = QStringLiteral("%1x%2 px").arg(m_pixmap.width()) - .arg(m_pixmap.height()); - setToolTip(tooltip); - setScaledPixmap(); +void +ImageLabel::setScreenshot(const QPixmap& pixmap) +{ + m_pixmap = pixmap; + const QString tooltip = + QStringLiteral("%1x%2 px").arg(m_pixmap.width()).arg(m_pixmap.height()); + setToolTip(tooltip); + setScaledPixmap(); } -void ImageLabel::setScaledPixmap() { - const qreal scale = qApp->devicePixelRatio(); - QPixmap scaledPixmap = m_pixmap.scaled(size() * scale, Qt::KeepAspectRatio, - Qt::SmoothTransformation); - scaledPixmap.setDevicePixelRatio(scale); - setPixmap(scaledPixmap); +void +ImageLabel::setScaledPixmap() +{ + const qreal scale = qApp->devicePixelRatio(); + QPixmap scaledPixmap = m_pixmap.scaled( + size() * scale, Qt::KeepAspectRatio, Qt::SmoothTransformation); + scaledPixmap.setDevicePixelRatio(scale); + setPixmap(scaledPixmap); } // drag handlers -void ImageLabel::mousePressEvent(QMouseEvent *event) { - if (event->button() == Qt::LeftButton) { - m_dragStartPosition = event->pos(); - setCursor(Qt::ClosedHandCursor); - } +void +ImageLabel::mousePressEvent(QMouseEvent* event) +{ + if (event->button() == Qt::LeftButton) { + m_dragStartPosition = event->pos(); + setCursor(Qt::ClosedHandCursor); + } } -void ImageLabel::mouseReleaseEvent(QMouseEvent *event) { - if (event->button() == Qt::LeftButton) { - setCursor(Qt::OpenHandCursor); - } -} - -void ImageLabel::mouseMoveEvent(QMouseEvent *event) { - if (!(event->buttons() & Qt::LeftButton)) { - return; - } - if ((event->pos() - m_dragStartPosition).manhattanLength() < - QGuiApplication::styleHints()->startDragDistance()) - { - return; - } +void +ImageLabel::mouseReleaseEvent(QMouseEvent* event) +{ + if (event->button() == Qt::LeftButton) { setCursor(Qt::OpenHandCursor); - emit dragInitiated(); + } +} + +void +ImageLabel::mouseMoveEvent(QMouseEvent* event) +{ + if (!(event->buttons() & Qt::LeftButton)) { + return; + } + if ((event->pos() - m_dragStartPosition).manhattanLength() < + QGuiApplication::styleHints()->startDragDistance()) { + return; + } + setCursor(Qt::OpenHandCursor); + emit dragInitiated(); } // resize handler -void ImageLabel::resizeEvent(QResizeEvent *event) { - Q_UNUSED(event); - setScaledPixmap(); +void +ImageLabel::resizeEvent(QResizeEvent* event) +{ + Q_UNUSED(event); + setScaledPixmap(); } diff --git a/src/widgets/imagelabel.h b/src/widgets/imagelabel.h index 36983b67..f40ac933 100644 --- a/src/widgets/imagelabel.h +++ b/src/widgets/imagelabel.h @@ -20,35 +20,36 @@ #pragma once -#include -#include -#include #include -#include -#include -#include #include +#include +#include +#include +#include +#include +#include -class ImageLabel : public QLabel { - Q_OBJECT +class ImageLabel : public QLabel +{ + Q_OBJECT public: - explicit ImageLabel(QWidget *parent = nullptr); - void setScreenshot(const QPixmap &pixmap); + explicit ImageLabel(QWidget* parent = nullptr); + void setScreenshot(const QPixmap& pixmap); signals: - void dragInitiated(); + void dragInitiated(); protected: - void mousePressEvent(QMouseEvent *event) Q_DECL_OVERRIDE; - void mouseReleaseEvent(QMouseEvent *event) Q_DECL_OVERRIDE; - void mouseMoveEvent(QMouseEvent *event) Q_DECL_OVERRIDE; - void resizeEvent(QResizeEvent *event) Q_DECL_OVERRIDE; + void mousePressEvent(QMouseEvent* event) Q_DECL_OVERRIDE; + void mouseReleaseEvent(QMouseEvent* event) Q_DECL_OVERRIDE; + void mouseMoveEvent(QMouseEvent* event) Q_DECL_OVERRIDE; + void resizeEvent(QResizeEvent* event) Q_DECL_OVERRIDE; private: - void setScaledPixmap(); + void setScaledPixmap(); - QGraphicsDropShadowEffect *m_DSEffect; - QPixmap m_pixmap; - QPoint m_dragStartPosition; + QGraphicsDropShadowEffect* m_DSEffect; + QPixmap m_pixmap; + QPoint m_dragStartPosition; }; diff --git a/src/widgets/infowindow.cpp b/src/widgets/infowindow.cpp index c3698624..e392f1ac 100644 --- a/src/widgets/infowindow.cpp +++ b/src/widgets/infowindow.cpp @@ -16,136 +16,142 @@ // along with Flameshot. If not, see . #include "infowindow.h" -#include -#include -#include #include -#include +#include #include +#include +#include +#include #if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0)) #include +#include #include #include -#include #endif // InfoWindow show basic information about the usage of Flameshot -InfoWindow::InfoWindow(QWidget *parent) : QWidget(parent) { - setAttribute(Qt::WA_DeleteOnClose); - setWindowIcon(QIcon(":img/app/flameshot.svg")); - setWindowTitle(tr("About")); +InfoWindow::InfoWindow(QWidget* parent) + : QWidget(parent) +{ + setAttribute(Qt::WA_DeleteOnClose); + setWindowIcon(QIcon(":img/app/flameshot.svg")); + setWindowTitle(tr("About")); #if (QT_VERSION >= QT_VERSION_CHECK(5, 10, 0)) - QRect position = frameGeometry(); - QScreen *screen = QGuiApplication::screenAt(QCursor::pos()); - position.moveCenter(screen->availableGeometry().center()); - move(position.topLeft()); + QRect position = frameGeometry(); + QScreen* screen = QGuiApplication::screenAt(QCursor::pos()); + position.moveCenter(screen->availableGeometry().center()); + move(position.topLeft()); #endif - m_layout = new QVBoxLayout(this); - m_layout->setAlignment(Qt::AlignHCenter); - initLabels(); - initInfoTable(); - show(); + m_layout = new QVBoxLayout(this); + m_layout->setAlignment(Qt::AlignHCenter); + initLabels(); + initInfoTable(); + show(); } +QVector InfoWindow::m_keys = { "←↓↑→", + "SHIFT + ←↓↑→", + "ESC", + "CTRL + C", + "CTRL + S", + "CTRL + Z", + QT_TR_NOOP("SPACEBAR"), + QT_TR_NOOP("Right Click"), + QT_TR_NOOP("Mouse Wheel") }; -QVector InfoWindow::m_keys = { - "←↓↑→", - "SHIFT + ←↓↑→", - "ESC", - "CTRL + C", - "CTRL + S", - "CTRL + Z", - QT_TR_NOOP("SPACEBAR"), - QT_TR_NOOP("Right Click"), - QT_TR_NOOP("Mouse Wheel") +QVector InfoWindow::m_description = { + QT_TR_NOOP("Move selection 1px"), + QT_TR_NOOP("Resize selection 1px"), + QT_TR_NOOP("Quit capture"), + QT_TR_NOOP("Copy to clipboard"), + QT_TR_NOOP("Save selection as a file"), + QT_TR_NOOP("Undo the last modification"), + QT_TR_NOOP("Toggle visibility of sidebar with options of the selected tool"), + QT_TR_NOOP("Show color picker"), + QT_TR_NOOP("Change the tool's thickness") }; -QVector InfoWindow::m_description = { - QT_TR_NOOP("Move selection 1px"), - QT_TR_NOOP("Resize selection 1px"), - QT_TR_NOOP("Quit capture"), - QT_TR_NOOP("Copy to clipboard"), - QT_TR_NOOP("Save selection as a file"), - QT_TR_NOOP("Undo the last modification"), - QT_TR_NOOP("Toggle visibility of sidebar with options of the selected tool"), - QT_TR_NOOP("Show color picker"), - QT_TR_NOOP("Change the tool's thickness") -}; +void +InfoWindow::initInfoTable() +{ + QTableWidget* table = new QTableWidget(this); + table->setToolTip(tr("Available shortcuts in the screen capture mode.")); -void InfoWindow::initInfoTable() { - QTableWidget *table = new QTableWidget(this); - table->setToolTip(tr("Available shortcuts in the screen capture mode.")); + m_layout->addWidget(table); - m_layout->addWidget(table); + table->setColumnCount(2); + table->setRowCount(m_keys.size()); + table->setSelectionMode(QAbstractItemView::NoSelection); + table->setFocusPolicy(Qt::NoFocus); + table->verticalHeader()->hide(); + // header creation + QStringList names; + names << tr("Key") << tr("Description"); + table->setHorizontalHeaderLabels(names); - table->setColumnCount(2); - table->setRowCount(m_keys.size()); - table->setSelectionMode(QAbstractItemView::NoSelection); - table->setFocusPolicy(Qt::NoFocus); - table->verticalHeader()->hide(); - // header creation - QStringList names; - names << tr("Key") << tr("Description"); - table->setHorizontalHeaderLabels(names); + // add content + for (int i = 0; i < m_keys.size(); ++i) { + table->setItem(i, 0, new QTableWidgetItem(tr(m_keys.at(i)))); + table->setItem(i, 1, new QTableWidgetItem(tr(m_description.at(i)))); + } - //add content - for (int i= 0; i < m_keys.size(); ++i){ - table->setItem(i, 0, new QTableWidgetItem(tr(m_keys.at(i)))); - table->setItem(i, 1, new QTableWidgetItem(tr(m_description.at(i)))); + // Read-only table items + for (int x = 0; x < table->rowCount(); ++x) { + for (int y = 0; y < table->columnCount(); ++y) { + QTableWidgetItem* item = table->item(x, y); + item->setFlags(item->flags() ^ Qt::ItemIsEditable); } + } - // Read-only table items - for (int x = 0; x < table->rowCount(); ++x) { - for (int y = 0; y < table->columnCount(); ++y) { - QTableWidgetItem *item = table->item(x, y); - item->setFlags(item->flags() ^ Qt::ItemIsEditable); - } - } + // adjust size + table->resizeColumnsToContents(); + table->resizeRowsToContents(); + table->setMinimumWidth(400); + table->setMaximumWidth(600); - // adjust size - table->resizeColumnsToContents(); - table->resizeRowsToContents(); - table->setMinimumWidth(400); - table->setMaximumWidth(600); - - table->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Stretch); - table->horizontalHeader()->setSizePolicy(QSizePolicy::Expanding, - QSizePolicy::Expanding); - m_layout->addStretch(); + table->horizontalHeader()->setSectionResizeMode(1, QHeaderView::Stretch); + table->horizontalHeader()->setSizePolicy(QSizePolicy::Expanding, + QSizePolicy::Expanding); + m_layout->addStretch(); } -void InfoWindow::initLabels() { - m_layout->addStretch(); - QLabel *licenseTitleLabel = new QLabel(tr("License"), this); - licenseTitleLabel->setAlignment(Qt::AlignHCenter); - m_layout->addWidget(licenseTitleLabel); - QLabel *licenseLabel = new QLabel(QStringLiteral("GPLv3+"), this); - licenseLabel->setAlignment(Qt::AlignHCenter); - m_layout->addWidget(licenseLabel); - m_layout->addStretch(); +void +InfoWindow::initLabels() +{ + m_layout->addStretch(); + QLabel* licenseTitleLabel = new QLabel(tr("License"), this); + licenseTitleLabel->setAlignment(Qt::AlignHCenter); + m_layout->addWidget(licenseTitleLabel); + QLabel* licenseLabel = new QLabel(QStringLiteral("GPLv3+"), this); + licenseLabel->setAlignment(Qt::AlignHCenter); + m_layout->addWidget(licenseLabel); + m_layout->addStretch(); - QLabel *versionTitleLabel = new QLabel(tr("Version"), this); - versionTitleLabel->setAlignment(Qt::AlignHCenter); - m_layout->addWidget(versionTitleLabel); - - QString versionMsg = "Flameshot " + QStringLiteral(APP_VERSION) + "\nCompiled with Qt " - + QT_VERSION_STR; - QLabel *versionLabel = new QLabel(versionMsg, this); - versionLabel->setAlignment(Qt::AlignHCenter); - m_layout->addWidget(versionLabel); - m_layout->addStretch(); - m_layout->addSpacing(10); - QLabel *shortcutsTitleLabel = new QLabel(tr("Shortcuts"), this); - shortcutsTitleLabel->setAlignment(Qt::AlignHCenter);; - m_layout->addWidget(shortcutsTitleLabel); + QLabel* versionTitleLabel = new QLabel(tr("Version"), this); + versionTitleLabel->setAlignment(Qt::AlignHCenter); + m_layout->addWidget(versionTitleLabel); + + QString versionMsg = "Flameshot " + QStringLiteral(APP_VERSION) + + "\nCompiled with Qt " + QT_VERSION_STR; + QLabel* versionLabel = new QLabel(versionMsg, this); + versionLabel->setAlignment(Qt::AlignHCenter); + m_layout->addWidget(versionLabel); + m_layout->addStretch(); + m_layout->addSpacing(10); + QLabel* shortcutsTitleLabel = new QLabel(tr("Shortcuts"), this); + shortcutsTitleLabel->setAlignment(Qt::AlignHCenter); + ; + m_layout->addWidget(shortcutsTitleLabel); } -void InfoWindow::keyPressEvent(QKeyEvent *e) { - if (e->key() == Qt::Key_Escape) { - close(); - } +void +InfoWindow::keyPressEvent(QKeyEvent* e) +{ + if (e->key() == Qt::Key_Escape) { + close(); + } } diff --git a/src/widgets/infowindow.h b/src/widgets/infowindow.h index e88d34d1..37d33778 100644 --- a/src/widgets/infowindow.h +++ b/src/widgets/infowindow.h @@ -21,19 +21,20 @@ class QVBoxLayout; -class InfoWindow : public QWidget { - Q_OBJECT +class InfoWindow : public QWidget +{ + Q_OBJECT public: - explicit InfoWindow(QWidget *parent = nullptr); + explicit InfoWindow(QWidget* parent = nullptr); protected: - void keyPressEvent(QKeyEvent *); + void keyPressEvent(QKeyEvent*); private: - void initInfoTable(); - void initLabels(); - QVBoxLayout *m_layout; + void initInfoTable(); + void initLabels(); + QVBoxLayout* m_layout; - static QVector m_keys; - static QVector m_description; + static QVector m_keys; + static QVector m_description; }; diff --git a/src/widgets/loadspinner.cpp b/src/widgets/loadspinner.cpp index 66ba8498..4c5baef8 100644 --- a/src/widgets/loadspinner.cpp +++ b/src/widgets/loadspinner.cpp @@ -16,81 +16,99 @@ // along with Flameshot. If not, see . #include "loadspinner.h" +#include #include #include #include -#include #define OFFSET 5 -LoadSpinner::LoadSpinner(QWidget *parent) : - QWidget(parent), m_startAngle(0), m_span(0), m_growing(true) +LoadSpinner::LoadSpinner(QWidget* parent) + : QWidget(parent) + , m_startAngle(0) + , m_span(0) + , m_growing(true) { - setAttribute(Qt::WA_TranslucentBackground); - const int size = QApplication::fontMetrics().height() * 8; - setFixedSize(size, size); - updateFrame(); - // init timer - m_timer = new QTimer(this); - connect(m_timer, &QTimer::timeout, this, &LoadSpinner::rotate); - m_timer->setInterval(30); + setAttribute(Qt::WA_TranslucentBackground); + const int size = QApplication::fontMetrics().height() * 8; + setFixedSize(size, size); + updateFrame(); + // init timer + m_timer = new QTimer(this); + connect(m_timer, &QTimer::timeout, this, &LoadSpinner::rotate); + m_timer->setInterval(30); } -void LoadSpinner::setColor(const QColor &c) { - m_color = c; +void +LoadSpinner::setColor(const QColor& c) +{ + m_color = c; } -void LoadSpinner::setWidth(int w) { - setFixedSize(w, w); - updateFrame(); +void +LoadSpinner::setWidth(int w) +{ + setFixedSize(w, w); + updateFrame(); } -void LoadSpinner::setHeight(int h) { - setFixedSize(h, h); - updateFrame(); +void +LoadSpinner::setHeight(int h) +{ + setFixedSize(h, h); + updateFrame(); } -void LoadSpinner::start() { - m_timer->start(); +void +LoadSpinner::start() +{ + m_timer->start(); } -void LoadSpinner::stop() { - m_timer->stop(); +void +LoadSpinner::stop() +{ + m_timer->stop(); } -void LoadSpinner::paintEvent(QPaintEvent *) { - QPainter painter(this); - painter.setRenderHint(QPainter::Antialiasing, true); - auto pen = QPen(m_color); - - pen.setWidth(height()/10); - painter.setPen(pen); - painter.setOpacity(0.2); - painter.drawArc(m_frame, 0, 5760); - painter.setOpacity(1.0); - painter.drawArc(m_frame, (m_startAngle * 16), (m_span * 16)); +void +LoadSpinner::paintEvent(QPaintEvent*) +{ + QPainter painter(this); + painter.setRenderHint(QPainter::Antialiasing, true); + auto pen = QPen(m_color); + pen.setWidth(height() / 10); + painter.setPen(pen); + painter.setOpacity(0.2); + painter.drawArc(m_frame, 0, 5760); + painter.setOpacity(1.0); + painter.drawArc(m_frame, (m_startAngle * 16), (m_span * 16)); } -void LoadSpinner::rotate() { - const int advance = 3; - const int grow = 8; - if (m_growing) { - m_startAngle = (m_startAngle + advance) % 360; - m_span += grow; - if(m_span > 260) { - m_growing = false; - } - } else { - m_startAngle = (m_startAngle + grow) % 360; - m_span = m_span + advance - grow; - if(m_span < 10) { - m_growing = true; - } +void +LoadSpinner::rotate() +{ + const int advance = 3; + const int grow = 8; + if (m_growing) { + m_startAngle = (m_startAngle + advance) % 360; + m_span += grow; + if (m_span > 260) { + m_growing = false; } - update(); + } else { + m_startAngle = (m_startAngle + grow) % 360; + m_span = m_span + advance - grow; + if (m_span < 10) { + m_growing = true; + } + } + update(); } -void LoadSpinner::updateFrame() { - m_frame = QRect(OFFSET, OFFSET, width() - OFFSET*2, height() - OFFSET*2); +void +LoadSpinner::updateFrame() +{ + m_frame = QRect(OFFSET, OFFSET, width() - OFFSET * 2, height() - OFFSET * 2); } diff --git a/src/widgets/loadspinner.h b/src/widgets/loadspinner.h index a0fea570..707fc3f0 100644 --- a/src/widgets/loadspinner.h +++ b/src/widgets/loadspinner.h @@ -19,31 +19,32 @@ #include -class LoadSpinner : public QWidget { - Q_OBJECT +class LoadSpinner : public QWidget +{ + Q_OBJECT public: - explicit LoadSpinner(QWidget *parent = nullptr); + explicit LoadSpinner(QWidget* parent = nullptr); - void setColor(const QColor &c); - void setWidth(int w); - void setHeight(int h); - void start(); - void stop(); + void setColor(const QColor& c); + void setWidth(int w); + void setHeight(int h); + void start(); + void stop(); protected: - void paintEvent(QPaintEvent *); + void paintEvent(QPaintEvent*); private slots: - void rotate(); + void rotate(); private: - QColor m_color; - QTimer *m_timer; + QColor m_color; + QTimer* m_timer; - int m_startAngle = 0; - int m_span =180; - bool m_growing; + int m_startAngle = 0; + int m_span = 180; + bool m_growing; - QRect m_frame; - void updateFrame(); + QRect m_frame; + void updateFrame(); }; diff --git a/src/widgets/notificationwidget.cpp b/src/widgets/notificationwidget.cpp index 35b70f54..24135034 100644 --- a/src/widgets/notificationwidget.cpp +++ b/src/widgets/notificationwidget.cpp @@ -16,57 +16,65 @@ // along with Flameshot. If not, see . #include "notificationwidget.h" -#include -#include -#include -#include -#include #include #include +#include +#include +#include +#include -NotificationWidget::NotificationWidget(QWidget *parent) : QWidget(parent) { - m_timer = new QTimer(this); - m_timer->setSingleShot(true); - m_timer->setInterval(7000); - connect(m_timer, &QTimer::timeout, this, &NotificationWidget::animatedHide); +NotificationWidget::NotificationWidget(QWidget* parent) + : QWidget(parent) +{ + m_timer = new QTimer(this); + m_timer->setSingleShot(true); + m_timer->setInterval(7000); + connect(m_timer, &QTimer::timeout, this, &NotificationWidget::animatedHide); - m_content = new QFrame(); - m_layout = new QVBoxLayout(); - m_label = new QLabel(m_content); - m_label->hide(); + m_content = new QFrame(); + m_layout = new QVBoxLayout(); + m_label = new QLabel(m_content); + m_label->hide(); - m_showAnimation = new QPropertyAnimation(m_content, "geometry", this); - m_showAnimation->setDuration(300); + m_showAnimation = new QPropertyAnimation(m_content, "geometry", this); + m_showAnimation->setDuration(300); - m_hideAnimation = new QPropertyAnimation(m_content, "geometry", this); - m_hideAnimation->setDuration(300); - connect(m_hideAnimation, &QPropertyAnimation::finished, m_label, &QLabel::hide); + m_hideAnimation = new QPropertyAnimation(m_content, "geometry", this); + m_hideAnimation->setDuration(300); + connect( + m_hideAnimation, &QPropertyAnimation::finished, m_label, &QLabel::hide); - auto mainLayout = new QVBoxLayout(); - setLayout(mainLayout); + auto mainLayout = new QVBoxLayout(); + setLayout(mainLayout); - mainLayout->addWidget(m_content); - m_layout->addWidget(m_label, 0, Qt::AlignHCenter); - m_content->setLayout(m_layout); + mainLayout->addWidget(m_content); + m_layout->addWidget(m_label, 0, Qt::AlignHCenter); + m_content->setLayout(m_layout); - setFixedHeight(40); + setFixedHeight(40); } -void NotificationWidget::showMessage(const QString &msg) { - m_label->setText(msg); - m_label->show(); - animatedShow(); +void +NotificationWidget::showMessage(const QString& msg) +{ + m_label->setText(msg); + m_label->show(); + animatedShow(); } -void NotificationWidget::animatedShow() { - m_showAnimation->setStartValue(QRect(0, 0, width(), 0)); - m_showAnimation->setEndValue(QRect(0, 0, width(), height())); - m_showAnimation->start(); - m_timer->start(); +void +NotificationWidget::animatedShow() +{ + m_showAnimation->setStartValue(QRect(0, 0, width(), 0)); + m_showAnimation->setEndValue(QRect(0, 0, width(), height())); + m_showAnimation->start(); + m_timer->start(); } -void NotificationWidget::animatedHide() { - m_hideAnimation->setStartValue(QRect(0, 0, width(), height())); - m_hideAnimation->setEndValue(QRect(0, 0, width(), 0)); - m_hideAnimation->start(); +void +NotificationWidget::animatedHide() +{ + m_hideAnimation->setStartValue(QRect(0, 0, width(), height())); + m_hideAnimation->setEndValue(QRect(0, 0, width(), 0)); + m_hideAnimation->start(); } diff --git a/src/widgets/notificationwidget.h b/src/widgets/notificationwidget.h index 4836e1ea..b4b55535 100644 --- a/src/widgets/notificationwidget.h +++ b/src/widgets/notificationwidget.h @@ -25,21 +25,22 @@ class QPropertyAnimation; class QVBoxLayout; class QFrame; -class NotificationWidget : public QWidget { - Q_OBJECT +class NotificationWidget : public QWidget +{ + Q_OBJECT public: - explicit NotificationWidget(QWidget *parent = nullptr); + explicit NotificationWidget(QWidget* parent = nullptr); - void showMessage(const QString &msg); + void showMessage(const QString& msg); private: - QLabel *m_label; - QPropertyAnimation *m_showAnimation; - QPropertyAnimation *m_hideAnimation; - QVBoxLayout *m_layout; - QFrame *m_content; - QTimer *m_timer; + QLabel* m_label; + QPropertyAnimation* m_showAnimation; + QPropertyAnimation* m_hideAnimation; + QVBoxLayout* m_layout; + QFrame* m_content; + QTimer* m_timer; - void animatedShow(); - void animatedHide(); + void animatedShow(); + void animatedHide(); }; diff --git a/src/widgets/panel/sidepanelwidget.cpp b/src/widgets/panel/sidepanelwidget.cpp index 90ece87c..f985fb5f 100644 --- a/src/widgets/panel/sidepanelwidget.cpp +++ b/src/widgets/panel/sidepanelwidget.cpp @@ -16,173 +16,206 @@ // along with Flameshot. If not, see . #include "sidepanelwidget.h" -#include "src/utils/pathinfo.h" #include "src/utils/colorutils.h" -#include +#include "src/utils/pathinfo.h" #include -#include -#include #include +#include +#include #include +#include -class QColorPickingEventFilter : public QObject { +class QColorPickingEventFilter : public QObject +{ public: + explicit QColorPickingEventFilter(SidePanelWidget* pw, + QObject* parent = nullptr) + : QObject(parent) + , m_pw(pw) + {} - explicit QColorPickingEventFilter( - SidePanelWidget *pw, QObject *parent = nullptr) : - QObject(parent), m_pw(pw) {} - - bool eventFilter(QObject *, QEvent *event) override { - event->accept(); - switch (event->type()) { - case QEvent::MouseMove: - return m_pw->handleMouseMove(static_cast(event)); - case QEvent::MouseButtonPress: - return m_pw->handleMouseButtonPressed( - static_cast(event)); - case QEvent::KeyPress: - return m_pw->handleKeyPress(static_cast(event)); - default: - break; - } - return false; + bool eventFilter(QObject*, QEvent* event) override + { + event->accept(); + switch (event->type()) { + case QEvent::MouseMove: + return m_pw->handleMouseMove(static_cast(event)); + case QEvent::MouseButtonPress: + return m_pw->handleMouseButtonPressed(static_cast(event)); + case QEvent::KeyPress: + return m_pw->handleKeyPress(static_cast(event)); + default: + break; } + return false; + } private: - SidePanelWidget *m_pw; + SidePanelWidget* m_pw; }; //////////////////////// -SidePanelWidget::SidePanelWidget(QPixmap *p, QWidget *parent) : - QWidget(parent), m_pixmap(p), m_eventFilter(nullptr) +SidePanelWidget::SidePanelWidget(QPixmap* p, QWidget* parent) + : QWidget(parent) + , m_pixmap(p) + , m_eventFilter(nullptr) { - m_layout = new QVBoxLayout(this); + m_layout = new QVBoxLayout(this); - QFormLayout *colorForm = new QFormLayout(); - m_thicknessSlider = new QSlider(Qt::Horizontal); - m_thicknessSlider->setValue(m_thickness); - m_colorLabel = new QLabel(); - m_colorLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); - colorForm->addRow(tr("Active thickness:"), m_thicknessSlider); - colorForm->addRow(tr("Active color:"), m_colorLabel); - m_layout->addLayout(colorForm); + QFormLayout* colorForm = new QFormLayout(); + m_thicknessSlider = new QSlider(Qt::Horizontal); + m_thicknessSlider->setValue(m_thickness); + m_colorLabel = new QLabel(); + m_colorLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed); + colorForm->addRow(tr("Active thickness:"), m_thicknessSlider); + colorForm->addRow(tr("Active color:"), m_colorLabel); + m_layout->addLayout(colorForm); - connect(m_thicknessSlider, &QSlider::sliderReleased, - this, &SidePanelWidget::updateCurrentThickness); - connect(this, &SidePanelWidget::thicknessChanged, - this, &SidePanelWidget::updateThickness); + connect(m_thicknessSlider, + &QSlider::sliderReleased, + this, + &SidePanelWidget::updateCurrentThickness); + connect(this, + &SidePanelWidget::thicknessChanged, + this, + &SidePanelWidget::updateThickness); - QColor background = this->palette().window().color(); - bool isDark = ColorUtils::colorIsDark(background); - QString modifier = isDark ? PathInfo::whiteIconPath() : - PathInfo::blackIconPath(); - QIcon grabIcon(modifier + "colorize.svg"); - m_colorGrabButton = new QPushButton(grabIcon, QLatin1String("")); - updateGrabButton(false); - connect(m_colorGrabButton, &QPushButton::pressed, - this, &SidePanelWidget::colorGrabberActivated); - m_layout->addWidget(m_colorGrabButton); + QColor background = this->palette().window().color(); + bool isDark = ColorUtils::colorIsDark(background); + QString modifier = + isDark ? PathInfo::whiteIconPath() : PathInfo::blackIconPath(); + QIcon grabIcon(modifier + "colorize.svg"); + m_colorGrabButton = new QPushButton(grabIcon, QLatin1String("")); + updateGrabButton(false); + connect(m_colorGrabButton, + &QPushButton::pressed, + this, + &SidePanelWidget::colorGrabberActivated); + m_layout->addWidget(m_colorGrabButton); - m_colorWheel = new color_widgets::ColorWheel(this); - m_colorWheel->setColor(m_color); - connect(m_colorWheel, &color_widgets::ColorWheel::mouseReleaseOnColor, this, - &SidePanelWidget::colorChanged); - connect(m_colorWheel, &color_widgets::ColorWheel::colorChanged, this, - &SidePanelWidget::updateColorNoWheel); - m_layout->addWidget(m_colorWheel); + m_colorWheel = new color_widgets::ColorWheel(this); + m_colorWheel->setColor(m_color); + connect(m_colorWheel, + &color_widgets::ColorWheel::mouseReleaseOnColor, + this, + &SidePanelWidget::colorChanged); + connect(m_colorWheel, + &color_widgets::ColorWheel::colorChanged, + this, + &SidePanelWidget::updateColorNoWheel); + m_layout->addWidget(m_colorWheel); } -void SidePanelWidget::updateColor(const QColor &c) { - m_color = c; - m_colorLabel->setStyleSheet( - QStringLiteral("QLabel { background-color : %1; }").arg(c.name())); - m_colorWheel->setColor(m_color); -} - -void SidePanelWidget::updateThickness(const int &t) +void +SidePanelWidget::updateColor(const QColor& c) { - m_thickness = qBound(0, t, 100); - m_thicknessSlider->setValue(m_thickness); + m_color = c; + m_colorLabel->setStyleSheet( + QStringLiteral("QLabel { background-color : %1; }").arg(c.name())); + m_colorWheel->setColor(m_color); } -void SidePanelWidget::updateColorNoWheel(const QColor &c) { - m_color = c; - m_colorLabel->setStyleSheet( - QStringLiteral("QLabel { background-color : %1; }").arg(c.name())); -} - -void SidePanelWidget::updateCurrentThickness() +void +SidePanelWidget::updateThickness(const int& t) { - emit thicknessChanged(m_thicknessSlider->value()); + m_thickness = qBound(0, t, 100); + m_thicknessSlider->setValue(m_thickness); } -void SidePanelWidget::colorGrabberActivated() { - grabKeyboard(); - grabMouse(Qt::CrossCursor); - setMouseTracking(true); - m_colorBackup = m_color; - if (!m_eventFilter) { - m_eventFilter = new QColorPickingEventFilter(this, this); - } - installEventFilter(m_eventFilter); - updateGrabButton(true); +void +SidePanelWidget::updateColorNoWheel(const QColor& c) +{ + m_color = c; + m_colorLabel->setStyleSheet( + QStringLiteral("QLabel { background-color : %1; }").arg(c.name())); } -void SidePanelWidget::releaseColorGrab() { - setMouseTracking(false); - removeEventFilter(m_eventFilter); - releaseMouse(); - releaseKeyboard(); - setFocus(); - updateGrabButton(false); +void +SidePanelWidget::updateCurrentThickness() +{ + emit thicknessChanged(m_thicknessSlider->value()); } -QColor SidePanelWidget::grabPixmapColor(const QPoint &p) { - QColor c; - if (m_pixmap) { - QPixmap pixel = m_pixmap->copy(QRect(p, p)); - c = pixel.toImage().pixel(0,0); - } - return c; +void +SidePanelWidget::colorGrabberActivated() +{ + grabKeyboard(); + grabMouse(Qt::CrossCursor); + setMouseTracking(true); + m_colorBackup = m_color; + if (!m_eventFilter) { + m_eventFilter = new QColorPickingEventFilter(this, this); + } + installEventFilter(m_eventFilter); + updateGrabButton(true); } -bool SidePanelWidget::handleKeyPress(QKeyEvent *e) { - if (e->key() == Qt::Key_Space) { - emit togglePanel(); - } else if (e->key() == Qt::Key_Escape) { - releaseColorGrab(); - updateColor(m_colorBackup); - } else if (e->key() == Qt::Key_Return || e->key() == Qt::Key_Enter) { - updateColor(grabPixmapColor(QCursor::pos())); - releaseColorGrab(); - emit colorChanged(m_color); - } - return true; +void +SidePanelWidget::releaseColorGrab() +{ + setMouseTracking(false); + removeEventFilter(m_eventFilter); + releaseMouse(); + releaseKeyboard(); + setFocus(); + updateGrabButton(false); } -bool SidePanelWidget::handleMouseButtonPressed(QMouseEvent *e) { - if (m_colorGrabButton->geometry().contains(e->pos()) || - e->button() == Qt::RightButton) - { - updateColorNoWheel(m_colorBackup); - } else if (e->button() == Qt::LeftButton) { - updateColor(grabPixmapColor(QCursor::pos())); - } +QColor +SidePanelWidget::grabPixmapColor(const QPoint& p) +{ + QColor c; + if (m_pixmap) { + QPixmap pixel = m_pixmap->copy(QRect(p, p)); + c = pixel.toImage().pixel(0, 0); + } + return c; +} + +bool +SidePanelWidget::handleKeyPress(QKeyEvent* e) +{ + if (e->key() == Qt::Key_Space) { + emit togglePanel(); + } else if (e->key() == Qt::Key_Escape) { + releaseColorGrab(); + updateColor(m_colorBackup); + } else if (e->key() == Qt::Key_Return || e->key() == Qt::Key_Enter) { + updateColor(grabPixmapColor(QCursor::pos())); releaseColorGrab(); emit colorChanged(m_color); - return true; + } + return true; } -bool SidePanelWidget::handleMouseMove(QMouseEvent *e) { - updateColorNoWheel(grabPixmapColor(e->globalPos())); - return true; +bool +SidePanelWidget::handleMouseButtonPressed(QMouseEvent* e) +{ + if (m_colorGrabButton->geometry().contains(e->pos()) || + e->button() == Qt::RightButton) { + updateColorNoWheel(m_colorBackup); + } else if (e->button() == Qt::LeftButton) { + updateColor(grabPixmapColor(QCursor::pos())); + } + releaseColorGrab(); + emit colorChanged(m_color); + return true; } -void SidePanelWidget::updateGrabButton(const bool activated) { - if (activated) { - m_colorGrabButton->setText(tr("Press ESC to cancel")); - } else { - m_colorGrabButton->setText(tr("Grab Color")); - } +bool +SidePanelWidget::handleMouseMove(QMouseEvent* e) +{ + updateColorNoWheel(grabPixmapColor(e->globalPos())); + return true; +} + +void +SidePanelWidget::updateGrabButton(const bool activated) +{ + if (activated) { + m_colorGrabButton->setText(tr("Press ESC to cancel")); + } else { + m_colorGrabButton->setText(tr("Grab Color")); + } } diff --git a/src/widgets/panel/sidepanelwidget.h b/src/widgets/panel/sidepanelwidget.h index 5757fadd..5ac935c0 100644 --- a/src/widgets/panel/sidepanelwidget.h +++ b/src/widgets/panel/sidepanelwidget.h @@ -17,8 +17,8 @@ #pragma once -#include #include "color_wheel.hpp" +#include class QVBoxLayout; class QPushButton; @@ -26,48 +26,49 @@ class QLabel; class QColorPickingEventFilter; class QSlider; -class SidePanelWidget : public QWidget { - Q_OBJECT +class SidePanelWidget : public QWidget +{ + Q_OBJECT + + friend class QColorPickingEventFilter; - friend class QColorPickingEventFilter; public: - explicit SidePanelWidget(QPixmap *p, QWidget *parent = nullptr); + explicit SidePanelWidget(QPixmap* p, QWidget* parent = nullptr); signals: - void colorChanged(const QColor &c); - void thicknessChanged(const int &t); - void togglePanel(); + void colorChanged(const QColor& c); + void thicknessChanged(const int& t); + void togglePanel(); public slots: - void updateColor(const QColor &c); - void updateThickness(const int &t); + void updateColor(const QColor& c); + void updateThickness(const int& t); private slots: - void updateColorNoWheel(const QColor &c); - void updateCurrentThickness(); + void updateColorNoWheel(const QColor& c); + void updateCurrentThickness(); private slots: - void colorGrabberActivated(); - void releaseColorGrab(); + void colorGrabberActivated(); + void releaseColorGrab(); private: - QColor grabPixmapColor(const QPoint &p); + QColor grabPixmapColor(const QPoint& p); - bool handleKeyPress(QKeyEvent *e); - bool handleMouseButtonPressed(QMouseEvent *e); - bool handleMouseMove(QMouseEvent *e); + bool handleKeyPress(QKeyEvent* e); + bool handleMouseButtonPressed(QMouseEvent* e); + bool handleMouseMove(QMouseEvent* e); - void updateGrabButton(const bool activated); - - QVBoxLayout *m_layout; - QPushButton *m_colorGrabButton; - color_widgets::ColorWheel *m_colorWheel; - QLabel *m_colorLabel; - QPixmap *m_pixmap; - QColor m_colorBackup; - QColor m_color; - QSlider *m_thicknessSlider; - int m_thickness; - QColorPickingEventFilter *m_eventFilter; + void updateGrabButton(const bool activated); + QVBoxLayout* m_layout; + QPushButton* m_colorGrabButton; + color_widgets::ColorWheel* m_colorWheel; + QLabel* m_colorLabel; + QPixmap* m_pixmap; + QColor m_colorBackup; + QColor m_color; + QSlider* m_thicknessSlider; + int m_thickness; + QColorPickingEventFilter* m_eventFilter; }; diff --git a/src/widgets/panel/utilitypanel.cpp b/src/widgets/panel/utilitypanel.cpp index 97da5083..dbfd0fb4 100644 --- a/src/widgets/panel/utilitypanel.cpp +++ b/src/widgets/panel/utilitypanel.cpp @@ -17,82 +17,98 @@ #include "utilitypanel.h" #include -#include -#include #include +#include +#include #include -UtilityPanel::UtilityPanel(QWidget *parent) : QWidget(parent) { - initInternalPanel(); +UtilityPanel::UtilityPanel(QWidget* parent) + : QWidget(parent) +{ + initInternalPanel(); + setAttribute(Qt::WA_TransparentForMouseEvents); + setCursor(Qt::ArrowCursor); + + m_showAnimation = new QPropertyAnimation(m_internalPanel, "geometry", this); + m_showAnimation->setEasingCurve(QEasingCurve::InOutQuad); + m_showAnimation->setDuration(300); + + m_hideAnimation = new QPropertyAnimation(m_internalPanel, "geometry", this); + m_hideAnimation->setEasingCurve(QEasingCurve::InOutQuad); + m_hideAnimation->setDuration(300); + + connect(m_hideAnimation, + &QPropertyAnimation::finished, + m_internalPanel, + &QWidget::hide); +} + +QWidget* +UtilityPanel::toolWidget() const +{ + return m_toolWidget; +} + +void +UtilityPanel::addToolWidget(QWidget* w) +{ + if (m_toolWidget) { + m_toolWidget->deleteLater(); + } + if (w) { + m_toolWidget = w; + m_upLayout->addWidget(w); + } +} + +void +UtilityPanel::clearToolWidget() +{ + if (m_toolWidget) { + m_toolWidget->deleteLater(); + } +} + +void +UtilityPanel::pushWidget(QWidget* w) +{ + m_layout->addWidget(w); +} + +void +UtilityPanel::toggle() +{ + if (m_internalPanel->isHidden()) { + setAttribute(Qt::WA_TransparentForMouseEvents, false); + m_showAnimation->setStartValue(QRect(-width(), 0, 0, height())); + m_showAnimation->setEndValue(QRect(0, 0, width(), height())); + m_internalPanel->show(); + m_showAnimation->start(); + } else { setAttribute(Qt::WA_TransparentForMouseEvents); - setCursor(Qt::ArrowCursor); - - m_showAnimation = new QPropertyAnimation(m_internalPanel, "geometry", this); - m_showAnimation->setEasingCurve(QEasingCurve::InOutQuad); - m_showAnimation->setDuration(300); - - m_hideAnimation = new QPropertyAnimation(m_internalPanel, "geometry", this); - m_hideAnimation->setEasingCurve(QEasingCurve::InOutQuad); - m_hideAnimation->setDuration(300); - - connect(m_hideAnimation, &QPropertyAnimation::finished, - m_internalPanel, &QWidget::hide); + m_hideAnimation->setStartValue(QRect(0, 0, width(), height())); + m_hideAnimation->setEndValue(QRect(-width(), 0, 0, height())); + m_hideAnimation->start(); + } } -QWidget *UtilityPanel::toolWidget() const { - return m_toolWidget; -} - -void UtilityPanel::addToolWidget(QWidget *w) { - if (m_toolWidget) { - m_toolWidget->deleteLater(); - } - if (w) { - m_toolWidget = w; - m_upLayout->addWidget(w); - } -} - -void UtilityPanel::clearToolWidget() { - if (m_toolWidget) { - m_toolWidget->deleteLater(); - } -} - -void UtilityPanel::pushWidget(QWidget *w) { - m_layout->addWidget(w); -} - -void UtilityPanel::toggle() { - if (m_internalPanel->isHidden()) { - setAttribute(Qt::WA_TransparentForMouseEvents, false); - m_showAnimation->setStartValue(QRect(-width(), 0, 0, height())); - m_showAnimation->setEndValue(QRect(0, 0, width(), height())); - m_internalPanel->show(); - m_showAnimation->start(); - } else { - setAttribute(Qt::WA_TransparentForMouseEvents); - m_hideAnimation->setStartValue(QRect(0, 0, width(), height())); - m_hideAnimation->setEndValue(QRect(-width(), 0, 0, height())); - m_hideAnimation->start(); - } -} - -void UtilityPanel::initInternalPanel() { - m_internalPanel = new QScrollArea(this); - m_internalPanel->setAttribute(Qt::WA_NoMousePropagation); - QWidget *widget = new QWidget(); - m_internalPanel->setWidget(widget); - m_internalPanel->setWidgetResizable(true); - - m_layout = new QVBoxLayout(); - m_upLayout = new QVBoxLayout(); - m_layout->addLayout(m_upLayout); - widget->setLayout(m_layout); - - QColor bgColor = palette().window().color(); - bgColor.setAlphaF(0.0); - m_internalPanel->setStyleSheet(QStringLiteral("QScrollArea {background-color: %1}") - .arg(bgColor.name())); - m_internalPanel->hide(); +void +UtilityPanel::initInternalPanel() +{ + m_internalPanel = new QScrollArea(this); + m_internalPanel->setAttribute(Qt::WA_NoMousePropagation); + QWidget* widget = new QWidget(); + m_internalPanel->setWidget(widget); + m_internalPanel->setWidgetResizable(true); + + m_layout = new QVBoxLayout(); + m_upLayout = new QVBoxLayout(); + m_layout->addLayout(m_upLayout); + widget->setLayout(m_layout); + + QColor bgColor = palette().window().color(); + bgColor.setAlphaF(0.0); + m_internalPanel->setStyleSheet( + QStringLiteral("QScrollArea {background-color: %1}").arg(bgColor.name())); + m_internalPanel->hide(); } diff --git a/src/widgets/panel/utilitypanel.h b/src/widgets/panel/utilitypanel.h index 8cf18a7b..630ed078 100644 --- a/src/widgets/panel/utilitypanel.h +++ b/src/widgets/panel/utilitypanel.h @@ -17,37 +17,38 @@ #pragma once -#include #include +#include class QVBoxLayout; class QPropertyAnimation; class QScrollArea; -class UtilityPanel : public QWidget { - Q_OBJECT +class UtilityPanel : public QWidget +{ + Q_OBJECT public: - explicit UtilityPanel(QWidget *parent = nullptr); + explicit UtilityPanel(QWidget* parent = nullptr); - QWidget* toolWidget() const; - void addToolWidget(QWidget *w); - void clearToolWidget(); - void pushWidget(QWidget *w); + QWidget* toolWidget() const; + void addToolWidget(QWidget* w); + void clearToolWidget(); + void pushWidget(QWidget* w); signals: - void mouseEnter(); - void mouseLeave(); + void mouseEnter(); + void mouseLeave(); public slots: - void toggle(); + void toggle(); private: - void initInternalPanel(); + void initInternalPanel(); - QPointer m_toolWidget; - QScrollArea *m_internalPanel; - QVBoxLayout *m_upLayout; - QVBoxLayout *m_layout; - QPropertyAnimation *m_showAnimation; - QPropertyAnimation *m_hideAnimation; + QPointer m_toolWidget; + QScrollArea* m_internalPanel; + QVBoxLayout* m_upLayout; + QVBoxLayout* m_layout; + QPropertyAnimation* m_showAnimation; + QPropertyAnimation* m_hideAnimation; };