[Cleanup] Using clang-tidy

This commit is contained in:
Dave Davenport
2021-08-18 01:16:45 +02:00
parent 3a1b768bf4
commit 954fc728b2
41 changed files with 13115 additions and 12950 deletions

View File

@@ -1,6 +1,7 @@
#ifndef ROFI_INCLUDE_CSS_COLORS_H #ifndef ROFI_INCLUDE_CSS_COLORS_H
#define ROFI_INCLUDE_CSS_COLORS_H #define ROFI_INCLUDE_CSS_COLORS_H
#include <stdint.h>
/** /**
* @defgroup CSSCOLORS CssColors * @defgroup CSSCOLORS CssColors
* @ingroup HELPERS * @ingroup HELPERS
@@ -13,8 +14,7 @@
/** /**
* Structure of colors. * Structure of colors.
*/ */
typedef struct CSSColor typedef struct CSSColor {
{
/** CSS name of the color. */ /** CSS name of the color. */
char *name; char *name;
/** BGRA 8 bit color components. */ /** BGRA 8 bit color components. */
@@ -22,7 +22,8 @@ typedef struct CSSColor
} CSSColor; } CSSColor;
/** /**
* Array with all the named colors. Of type #CSSColor, there are #num_CSSColors items in this array. * Array with all the named colors. Of type #CSSColor, there are #num_CSSColors
* items in this array.
*/ */
extern const CSSColor CSSColors[]; extern const CSSColor CSSColors[];
/** /**

View File

@@ -28,12 +28,13 @@
#ifndef ROFI_DIALOG_DRUN_H #ifndef ROFI_DIALOG_DRUN_H
#define ROFI_DIALOG_DRUN_H #define ROFI_DIALOG_DRUN_H
#include "mode.h"
/** /**
* @defgroup DRUNMode DRun * @defgroup DRUNMode DRun
* @ingroup MODES * @ingroup MODES
* @{ * @{
*/ */
#include <config.h>
#ifdef ENABLE_DRUN #ifdef ENABLE_DRUN
/** #Mode object representing the desktop menu run dialog. */ /** #Mode object representing the desktop menu run dialog. */
extern Mode drun_mode; extern Mode drun_mode;

View File

@@ -27,7 +27,7 @@
#ifndef ROFI_DIALOG_FILE_BROWSER_H #ifndef ROFI_DIALOG_FILE_BROWSER_H
#define ROFI_DIALOG_FILE_BROWSER_H #define ROFI_DIALOG_FILE_BROWSER_H
#include "mode.h"
/** /**
* @defgroup FileBrowserMode FileBrowser * @defgroup FileBrowserMode FileBrowser
* @ingroup MODES * @ingroup MODES
@@ -52,6 +52,7 @@ Mode *create_new_file_browser ( void );
* *
* @returns the state the user selected. * @returns the state the user selected.
*/ */
ModeMode file_browser_mode_completer ( Mode *sw, int mretv, char **input, unsigned int selected_line, char **path ); ModeMode file_browser_mode_completer(Mode *sw, int mretv, char **input,
unsigned int selected_line, char **path);
/**@}*/ /**@}*/
#endif // ROFI_DIALOG_FILE_BROWSER_H #endif // ROFI_DIALOG_FILE_BROWSER_H

View File

@@ -28,6 +28,7 @@
#ifndef ROFI_DIALOG_HELPKEYS_H #ifndef ROFI_DIALOG_HELPKEYS_H
#define ROFI_DIALOG_HELPKEYS_H #define ROFI_DIALOG_HELPKEYS_H
#include "mode.h"
/** /**
* @defgroup HELPKEYSMode KeysHelp * @defgroup HELPKEYSMode KeysHelp
* @ingroup MODES * @ingroup MODES

View File

@@ -28,6 +28,8 @@
#ifndef ROFI_DIALOG_SCRIPT_H #ifndef ROFI_DIALOG_SCRIPT_H
#define ROFI_DIALOG_SCRIPT_H #define ROFI_DIALOG_SCRIPT_H
#include "mode.h"
/** /**
* @defgroup SCRIPTMode Script * @defgroup SCRIPTMode Script
* @ingroup MODES * @ingroup MODES

View File

@@ -27,7 +27,7 @@
#ifndef ROFI_DIALOG_SSH_H #ifndef ROFI_DIALOG_SSH_H
#define ROFI_DIALOG_SSH_H #define ROFI_DIALOG_SSH_H
#include "mode.h"
/** /**
* @defgroup SSHMode SSH * @defgroup SSHMode SSH
* @ingroup MODES * @ingroup MODES

View File

@@ -28,13 +28,14 @@
#ifndef ROFI_DIALOG_WINDOW_H #ifndef ROFI_DIALOG_WINDOW_H
#define ROFI_DIALOG_WINDOW_H #define ROFI_DIALOG_WINDOW_H
#include "mode.h"
/** /**
* @defgroup WINDOWMode Window * @defgroup WINDOWMode Window
* @ingroup MODES * @ingroup MODES
* *
* @{ * @{
*/ */
#include <config.h>
#ifdef WINDOW_MODE #ifdef WINDOW_MODE
extern Mode window_mode; extern Mode window_mode;

View File

@@ -28,9 +28,9 @@
#ifndef ROFI_DISPLAY_H #ifndef ROFI_DISPLAY_H
#define ROFI_DISPLAY_H #define ROFI_DISPLAY_H
#include <glib.h>
#include "helper.h" #include "helper.h"
#include "nkutils-bindings.h" #include "nkutils-bindings.h"
#include <glib.h>
/** /**
* @param main_loop The GMainLoop * @param main_loop The GMainLoop
@@ -71,6 +71,8 @@ void display_dump_monitor_layout ( void );
* *
* Provides the needed child setup function * Provides the needed child setup function
*/ */
void display_startup_notification ( RofiHelperExecuteContext *context, GSpawnChildSetupFunc *child_setup, gpointer *user_data ); void display_startup_notification(RofiHelperExecuteContext *context,
GSpawnChildSetupFunc *child_setup,
gpointer *user_data);
#endif #endif

View File

@@ -27,8 +27,8 @@
#ifndef ROFI_HELPER_H #ifndef ROFI_HELPER_H
#define ROFI_HELPER_H #define ROFI_HELPER_H
#include <cairo.h>
#include "rofi-types.h" #include "rofi-types.h"
#include <cairo.h>
G_BEGIN_DECLS G_BEGIN_DECLS
/** /**
@@ -140,8 +140,8 @@ int helper_token_match ( rofi_int_matcher * const *tokens, const char *input );
/** /**
* @param cmd The command to execute. * @param cmd The command to execute.
* *
* Execute cmd using config.run_command and outputs the result (stdout) to the opened file * Execute cmd using config.run_command and outputs the result (stdout) to the
* descriptor. * opened file descriptor.
* *
* @returns a valid file descriptor on success, or -1 on failure. * @returns a valid file descriptor on success, or -1 on failure.
*/ */
@@ -163,7 +163,8 @@ void remove_pid_file ( int fd );
* Do some input validation, especially the first few could break things. * Do some input validation, especially the first few could break things.
* It is good to catch them beforehand. * It is good to catch them beforehand.
* *
* This functions exits the program with 1 when it finds an invalid configuration. * This functions exits the program with 1 when it finds an invalid
* configuration.
*/ */
int config_sanity_check(void); int config_sanity_check(void);
@@ -203,13 +204,15 @@ char *rofi_expand_path ( const char *input );
* *
* @returns the levenshtein distance between needle and haystack * @returns the levenshtein distance between needle and haystack
*/ */
unsigned int levenshtein ( const char *needle, const glong needlelen, const char *haystack, const glong haystacklen ); unsigned int levenshtein(const char *needle, const glong needlelen,
const char *haystack, const glong haystacklen);
/** /**
* @param data the unvalidated character array holding possible UTF-8 data * @param data the unvalidated character array holding possible UTF-8 data
* @param length the length of the data array * @param length the length of the data array
* *
* Convert string to valid utf-8, replacing invalid parts with replacement character. * Convert string to valid utf-8, replacing invalid parts with replacement
* character.
* *
* @returns the converted UTF-8 string * @returns the converted UTF-8 string
*/ */
@@ -240,28 +243,35 @@ gchar *rofi_escape_markup ( gchar *text );
* @param str The input to match against pattern. * @param str The input to match against pattern.
* @param slen Length of str. * @param slen Length of str.
* *
* rofi_scorer_fuzzy_evaluate implements a global sequence alignment algorithm to find the maximum accumulated score by * rofi_scorer_fuzzy_evaluate implements a global sequence alignment algorithm
* aligning `pattern` to `str`. It applies when `pattern` is a subsequence of `str`. * to find the maximum accumulated score by aligning `pattern` to `str`. It
* applies when `pattern` is a subsequence of `str`.
* *
* Scoring criteria * Scoring criteria
* - Prefer matches at the start of a word, or the start of subwords in CamelCase/camelCase/camel123 words. See WORD_START_SCORE/CAMEL_SCORE. * - Prefer matches at the start of a word, or the start of subwords in
* CamelCase/camelCase/camel123 words. See WORD_START_SCORE/CAMEL_SCORE.
* - Non-word characters matter. See NON_WORD_SCORE. * - Non-word characters matter. See NON_WORD_SCORE.
* - The first characters of words of `pattern` receive bonus because they usually have more significance than the rest. * - The first characters of words of `pattern` receive bonus because they
* See PATTERN_START_MULTIPLIER/PATTERN_NON_START_MULTIPLIER. * usually have more significance than the rest. See
* - Superfluous characters in `str` will reduce the score (gap penalty). See GAP_SCORE. * PATTERN_START_MULTIPLIER/PATTERN_NON_START_MULTIPLIER.
* - Prefer early occurrence of the first character. See LEADING_GAP_SCORE/GAP_SCORE. * - Superfluous characters in `str` will reduce the score (gap penalty). See
* GAP_SCORE.
* - Prefer early occurrence of the first character. See
* LEADING_GAP_SCORE/GAP_SCORE.
* *
* The recurrence of the dynamic programming: * The recurrence of the dynamic programming:
* dp[i][j]: maximum accumulated score by aligning pattern[0..i] to str[0..j] * dp[i][j]: maximum accumulated score by aligning pattern[0..i] to str[0..j]
* dp[0][j] = leading_gap_penalty(0, j) + score[j] * dp[0][j] = leading_gap_penalty(0, j) + score[j]
* dp[i][j] = max(dp[i-1][j-1] + CONSECUTIVE_SCORE, max(dp[i-1][k] + gap_penalty(k+1, j) + score[j] : k < j)) * dp[i][j] = max(dp[i-1][j-1] + CONSECUTIVE_SCORE, max(dp[i-1][k] +
* gap_penalty(k+1, j) + score[j] : k < j))
* *
* The first dimension can be suppressed since we do not need a matching scheme, which reduces the space complexity from * The first dimension can be suppressed since we do not need a matching
* O(N*M) to O(M) * scheme, which reduces the space complexity from O(N*M) to O(M)
* *
* @returns the sorting weight. * @returns the sorting weight.
*/ */
int rofi_scorer_fuzzy_evaluate ( const char *pattern, glong plen, const char *str, glong slen ); int rofi_scorer_fuzzy_evaluate(const char *pattern, glong plen, const char *str,
glong slen);
/*@}*/ /*@}*/
/** /**
@@ -271,17 +281,17 @@ int rofi_scorer_fuzzy_evaluate ( const char *pattern, glong plen, const char *st
* *
* Compares the `G_NORMALIZE_ALL_COMPOSE` forms of the two strings. * Compares the `G_NORMALIZE_ALL_COMPOSE` forms of the two strings.
* *
* @returns less than, equal to, or greater than zero if the first `n` characters (not bytes) of `a` * @returns less than, equal to, or greater than zero if the first `n`
* are found, respectively, to be less than, to match, or be greater than the first `n` * characters (not bytes) of `a` are found, respectively, to be less than, to
* characters (not bytes) of `b`. * match, or be greater than the first `n` characters (not bytes) of `b`.
*/ */
int utf8_strncmp ( const char *a, const char* b, size_t n ) __attribute__( ( nonnull ( 1, 2 ) ) ); int utf8_strncmp(const char *a, const char *b, size_t n)
__attribute__((nonnull(1, 2)));
/** /**
* The startup notification context of the application to launch * The startup notification context of the application to launch
*/ */
typedef struct typedef struct {
{
/** The name of the application */ /** The name of the application */
const gchar *name; const gchar *name;
/** The binary name of the application */ /** The binary name of the application */
@@ -309,7 +319,9 @@ typedef struct
* *
* @returns TRUE when successful, FALSE when failed. * @returns TRUE when successful, FALSE when failed.
*/ */
gboolean helper_execute ( const char *wd, char **args, const char *error_precmd, const char *error_cmd, RofiHelperExecuteContext *context ); gboolean helper_execute(const char *wd, char **args, const char *error_precmd,
const char *error_cmd,
RofiHelperExecuteContext *context);
/** /**
* @param wd The work directory (optional) * @param wd The work directory (optional)
@@ -322,7 +334,9 @@ gboolean helper_execute ( const char *wd, char **args, const char *error_precmd,
* *
* @returns FALSE On failure, TRUE on success * @returns FALSE On failure, TRUE on success
*/ */
gboolean helper_execute_command ( const char *wd, const char *cmd, gboolean run_in_term, RofiHelperExecuteContext *context ); gboolean helper_execute_command(const char *wd, const char *cmd,
gboolean run_in_term,
RofiHelperExecuteContext *context);
/** /**
* @param file The file path * @param file The file path
@@ -331,7 +345,8 @@ gboolean helper_execute_command ( const char *wd, const char *cmd, gboolean run_
* *
* @returns a cairo surface from an svg path * @returns a cairo surface from an svg path
*/ */
cairo_surface_t *cairo_image_surface_create_from_svg ( const gchar* file, int height ); cairo_surface_t *cairo_image_surface_create_from_svg(const gchar *file,
int height);
/** /**
* Ranges. * Ranges.
@@ -361,18 +376,21 @@ void parse_ranges ( char *input, rofi_range_pair **list, unsigned int *length );
* * f: Print the entered filter. * * f: Print the entered filter.
* * F: Print the entered filter, quoted * * F: Print the entered filter, quoted
* *
* This functions outputs the formatted string to stdout, appends a newline (\n) character and * This functions outputs the formatted string to stdout, appends a newline (\n)
* calls flush on the file descriptor. * character and calls flush on the file descriptor.
*/ */
void rofi_output_formatted_line ( const char *format, const char *string, int selected_line, const char *filter ); void rofi_output_formatted_line(const char *format, const char *string,
int selected_line, const char *filter);
/** /**
* @param string The string with elements to be replaced * @param string The string with elements to be replaced
* @param ... Set of {key}, value that will be replaced, terminated by a NULL * @param ... Set of {key}, value that will be replaced, terminated by a
* NULL
* *
* Items {key} are replaced by the value if '{key}' is passed as key/value pair, otherwise removed from string. * Items {key} are replaced by the value if '{key}' is passed as key/value pair,
* If the {key} is in between [] all the text between [] are removed if {key} * otherwise removed from string. If the {key} is in between [] all the text
* is not found. Otherwise key is replaced and [ & ] removed. * between [] are removed if {key} is not found. Otherwise key is replaced and [
* & ] removed.
* *
* This allows for optional replacement, f.e. '{ssh-client} [-t {title}] -e * This allows for optional replacement, f.e. '{ssh-client} [-t {title}] -e
* "{cmd}"' the '-t {title}' is only there if {title} is set. * "{cmd}"' the '-t {title}' is only there if {title} is set.
@@ -389,8 +407,6 @@ char *helper_string_replace_if_exists ( char * string, ... );
*/ */
char *helper_get_theme_path(const char *file, const char *ext); char *helper_get_theme_path(const char *file, const char *ext);
G_END_DECLS G_END_DECLS
/**@} */ /**@} */

View File

@@ -1,6 +1,5 @@
#ifndef INCLUDE_ROFI_TYPES_H #ifndef INCLUDE_ROFI_TYPES_H
#define INCLUDE_ROFI_TYPES_H #define INCLUDE_ROFI_TYPES_H
#include <glib.h> #include <glib.h>
#include <stdint.h> #include <stdint.h>
G_BEGIN_DECLS G_BEGIN_DECLS
@@ -8,8 +7,7 @@ G_BEGIN_DECLS
/** /**
* Type of property * Type of property
*/ */
typedef enum typedef enum {
{
/** Integer */ /** Integer */
P_INTEGER, P_INTEGER,
/** Double */ /** Double */
@@ -51,8 +49,7 @@ typedef enum
extern const char *const PropertyTypeName[P_NUM_TYPES]; extern const char *const PropertyTypeName[P_NUM_TYPES];
/** Style of text highlight */ /** Style of text highlight */
typedef enum typedef enum {
{
/** no highlight */ /** no highlight */
ROFI_HL_NONE = 0, ROFI_HL_NONE = 0,
/** bold */ /** bold */
@@ -70,8 +67,7 @@ typedef enum
} RofiHighlightStyle; } RofiHighlightStyle;
/** Style of line */ /** Style of line */
typedef enum typedef enum {
{
/** Solid line */ /** Solid line */
ROFI_HL_SOLID, ROFI_HL_SOLID,
/** Dashed line */ /** Dashed line */
@@ -81,8 +77,7 @@ typedef enum
/** /**
* Distance unit type. * Distance unit type.
*/ */
typedef enum typedef enum {
{
/** PixelWidth in pixels. */ /** PixelWidth in pixels. */
ROFI_PU_PX, ROFI_PU_PX,
/** PixelWidth in millimeters. */ /** PixelWidth in millimeters. */
@@ -98,8 +93,7 @@ typedef enum
/** /**
* Structure representing a distance. * Structure representing a distance.
*/ */
typedef enum typedef enum {
{
ROFI_DISTANCE_MODIFIER_NONE, ROFI_DISTANCE_MODIFIER_NONE,
ROFI_DISTANCE_MODIFIER_ADD, ROFI_DISTANCE_MODIFIER_ADD,
ROFI_DISTANCE_MODIFIER_SUBTRACT, ROFI_DISTANCE_MODIFIER_SUBTRACT,
@@ -111,8 +105,7 @@ typedef enum
ROFI_DISTANCE_MODIFIER_MAX, ROFI_DISTANCE_MODIFIER_MAX,
} RofiDistanceModifier; } RofiDistanceModifier;
typedef struct RofiDistanceUnit typedef struct RofiDistanceUnit {
{
/** Distance */ /** Distance */
double distance; double distance;
/** Unit type of the distance */ /** Unit type of the distance */
@@ -128,8 +121,7 @@ typedef struct RofiDistanceUnit
struct RofiDistanceUnit *right; struct RofiDistanceUnit *right;
} RofiDistanceUnit; } RofiDistanceUnit;
typedef struct typedef struct {
{
/** Base */ /** Base */
RofiDistanceUnit base; RofiDistanceUnit base;
/** Style of the line (optional)*/ /** Style of the line (optional)*/
@@ -139,8 +131,7 @@ typedef struct
/** /**
* Type of orientation. * Type of orientation.
*/ */
typedef enum typedef enum {
{
ROFI_ORIENTATION_VERTICAL, ROFI_ORIENTATION_VERTICAL,
ROFI_ORIENTATION_HORIZONTAL ROFI_ORIENTATION_HORIZONTAL
} RofiOrientation; } RofiOrientation;
@@ -148,8 +139,7 @@ typedef enum
/** /**
* Cursor type. * Cursor type.
*/ */
typedef enum typedef enum {
{
ROFI_CURSOR_DEFAULT, ROFI_CURSOR_DEFAULT,
ROFI_CURSOR_POINTER, ROFI_CURSOR_POINTER,
ROFI_CURSOR_TEXT ROFI_CURSOR_TEXT
@@ -158,8 +148,7 @@ typedef enum
/** /**
* Represent the color in theme. * Represent the color in theme.
*/ */
typedef struct typedef struct {
{
/** red channel */ /** red channel */
double red; double red;
/** green channel */ /** green channel */
@@ -173,14 +162,9 @@ typedef struct
/** /**
* Theme Image * Theme Image
*/ */
typedef enum typedef enum { ROFI_IMAGE_URL, ROFI_IMAGE_LINEAR_GRADIENT } RofiImageType;
{
ROFI_IMAGE_URL,
ROFI_IMAGE_LINEAR_GRADIENT
} RofiImageType;
typedef enum typedef enum {
{
ROFI_DIRECTION_LEFT, ROFI_DIRECTION_LEFT,
ROFI_DIRECTION_RIGHT, ROFI_DIRECTION_RIGHT,
ROFI_DIRECTION_TOP, ROFI_DIRECTION_TOP,
@@ -188,16 +172,14 @@ typedef enum
ROFI_DIRECTION_ANGLE, ROFI_DIRECTION_ANGLE,
} RofiDirection; } RofiDirection;
typedef enum typedef enum {
{
ROFI_SCALE_NONE, ROFI_SCALE_NONE,
ROFI_SCALE_BOTH, ROFI_SCALE_BOTH,
ROFI_SCALE_HEIGHT, ROFI_SCALE_HEIGHT,
ROFI_SCALE_WIDTH, ROFI_SCALE_WIDTH,
} RofiScaleType; } RofiScaleType;
typedef struct typedef struct {
{
RofiImageType type; RofiImageType type;
char *url; char *url;
RofiScaleType scaling; RofiScaleType scaling;
@@ -217,8 +199,7 @@ typedef struct
/** /**
* RofiPadding * RofiPadding
*/ */
typedef struct typedef struct {
{
RofiDistance top; RofiDistance top;
RofiDistance right; RofiDistance right;
RofiDistance bottom; RofiDistance bottom;
@@ -228,8 +209,7 @@ typedef struct
/** /**
* Theme highlight. * Theme highlight.
*/ */
typedef struct typedef struct {
{
/** style to display */ /** style to display */
RofiHighlightStyle style; RofiHighlightStyle style;
/** Color */ /** Color */
@@ -245,8 +225,7 @@ typedef struct
* *
* @ingroup CONFIGURATION * @ingroup CONFIGURATION
*/ */
typedef enum typedef enum {
{
/** Center */ /** Center */
WL_CENTER = 0, WL_CENTER = 0,
/** Top middle */ /** Top middle */
@@ -267,8 +246,7 @@ typedef enum
WL_SOUTH_WEST = WL_SOUTH | WL_WEST, WL_SOUTH_WEST = WL_SOUTH | WL_WEST,
} WindowLocation; } WindowLocation;
typedef union _PropertyValue typedef union _PropertyValue {
{
/** integer */ /** integer */
int i; int i;
/** Double */ /** Double */
@@ -284,8 +262,7 @@ typedef union _PropertyValue
/** RofiPadding */ /** RofiPadding */
RofiPadding padding; RofiPadding padding;
/** Reference */ /** Reference */
struct struct {
{
/** Name */ /** Name */
char *name; char *name;
/** Cached looked up ref */ /** Cached looked up ref */
@@ -304,8 +281,7 @@ typedef union _PropertyValue
/** /**
* Property structure. * Property structure.
*/ */
typedef struct Property typedef struct Property {
{
/** Name of property */ /** Name of property */
char *name; char *name;
/** Type of property. */ /** Type of property. */
@@ -317,8 +293,7 @@ typedef struct Property
/** /**
* Structure to hold a range. * Structure to hold a range.
*/ */
typedef struct rofi_range_pair typedef struct rofi_range_pair {
{
int start; int start;
int stop; int stop;
} rofi_range_pair; } rofi_range_pair;
@@ -326,8 +301,7 @@ typedef struct rofi_range_pair
/** /**
* Internal structure for matching. * Internal structure for matching.
*/ */
typedef struct rofi_int_matcher_t typedef struct rofi_int_matcher_t {
{
GRegex *regex; GRegex *regex;
gboolean invert; gboolean invert;
} rofi_int_matcher; } rofi_int_matcher;
@@ -336,8 +310,7 @@ typedef struct rofi_int_matcher_t
* Structure with data to process by each worker thread. * Structure with data to process by each worker thread.
* TODO: Make this more generic wrapper. * TODO: Make this more generic wrapper.
*/ */
typedef struct _thread_state typedef struct _thread_state {
{
void (*callback)(struct _thread_state *t, gpointer data); void (*callback)(struct _thread_state *t, gpointer data);
} thread_state; } thread_state;

View File

@@ -32,7 +32,6 @@
*/ */
#ifndef ROFI_TIMINGS_H #ifndef ROFI_TIMINGS_H
#define ROFI_TIMINGS_H #define ROFI_TIMINGS_H
#include <config.h>
/** /**
* Init the timestamping mechanism . * Init the timestamping mechanism .
@@ -47,7 +46,8 @@ void rofi_timings_init ( void );
* *
* Report a tick. * Report a tick.
*/ */
void rofi_timings_tick ( const char *file, char const *str, int line, char const *msg ); void rofi_timings_tick(const char *file, char const *str, int line,
char const *msg);
/** /**
* Stop the timestamping mechanism * Stop the timestamping mechanism
*/ */

View File

@@ -29,6 +29,7 @@
#define ROFI_HBOX_H #define ROFI_HBOX_H
#include "widget.h" #include "widget.h"
#include "rofi-types.h"
/** /**
* @defgroup box box * @defgroup box box

View File

@@ -28,6 +28,8 @@
#ifndef ROFI_LISTVIEW_H #ifndef ROFI_LISTVIEW_H
#define ROFI_LISTVIEW_H #define ROFI_LISTVIEW_H
#include "widgets/textbox.h"
/** /**
* @defgroup listview listview * @defgroup listview listview
* @ingroup widget * @ingroup widget

View File

@@ -1,4 +1,3 @@
#include <stdint.h>
#include "css-colors.h" #include "css-colors.h"
const CSSColor CSSColors[] = { const CSSColor CSSColors[] = {
{.name = "AliceBlue", .r = 0xF0, .g = 0xF8, .b = 0xFF}, {.name = "AliceBlue", .r = 0xF0, .g = 0xF8, .b = 0xFF},
@@ -148,7 +147,6 @@ const CSSColor CSSColors[] = {
{.name = "White", .r = 0xFF, .g = 0xFF, .b = 0xFF}, {.name = "White", .r = 0xFF, .g = 0xFF, .b = 0xFF},
{.name = "WhiteSmoke", .r = 0xF5, .g = 0xF5, .b = 0xF5}, {.name = "WhiteSmoke", .r = 0xF5, .g = 0xF5, .b = 0xF5},
{.name = "Yellow", .r = 0xFF, .g = 0xFF, .b = 0x00}, {.name = "Yellow", .r = 0xFF, .g = 0xFF, .b = 0x00},
{ .name = "YellowGreen", .r = 0x9A, .g = 0xCD, .b = 0x32 } {.name = "YellowGreen", .r = 0x9A, .g = 0xCD, .b = 0x32}};
};
const unsigned int num_CSSColors = sizeof(CSSColors) / sizeof(*CSSColors); const unsigned int num_CSSColors = sizeof(CSSColors) / sizeof(*CSSColors);

View File

@@ -28,29 +28,26 @@
/** The log domain of this dialog. */ /** The log domain of this dialog. */
#define G_LOG_DOMAIN "Dialogs.Combi" #define G_LOG_DOMAIN "Dialogs.Combi"
#include <config.h>
#include <stdlib.h>
#include <stdio.h>
#include <rofi.h>
#include "settings.h"
#include "helper.h" #include "helper.h"
#include "settings.h"
#include <rofi.h>
#include <stdio.h>
#include <stdlib.h>
#include "mode-private.h"
#include <dialogs/dialogs.h> #include <dialogs/dialogs.h>
#include <pango/pango.h> #include <pango/pango.h>
#include "mode-private.h"
#include <theme.h> #include <theme.h>
/** /**
* Combi Mode * Combi Mode
*/ */
typedef struct typedef struct {
{
Mode *mode; Mode *mode;
gboolean disable; gboolean disable;
} CombiMode; } CombiMode;
typedef struct typedef struct {
{
// List of (combined) entries. // List of (combined) entries.
unsigned int cmd_list_length; unsigned int cmd_list_length;
// List to validate where each switcher starts. // List to validate where each switcher starts.
@@ -61,8 +58,7 @@ typedef struct
CombiMode *switchers; CombiMode *switchers;
} CombiModePrivateData; } CombiModePrivateData;
static void combi_mode_parse_switchers ( Mode *sw ) static void combi_mode_parse_switchers(Mode *sw) {
{
CombiModePrivateData *pd = mode_get_private_data(sw); CombiModePrivateData *pd = mode_get_private_data(sw);
char *savept = NULL; char *savept = NULL;
// Make a copy, as strtok will modify it. // Make a copy, as strtok will modify it.
@@ -72,8 +68,8 @@ static void combi_mode_parse_switchers ( Mode *sw )
for (char *token = strtok_r(switcher_str, sep, &savept); token != NULL; for (char *token = strtok_r(switcher_str, sep, &savept); token != NULL;
token = strtok_r(NULL, sep, &savept)) { token = strtok_r(NULL, sep, &savept)) {
// Resize and add entry. // Resize and add entry.
pd->switchers = (CombiMode *) g_realloc ( pd->switchers, pd->switchers = (CombiMode *)g_realloc(
sizeof ( CombiMode ) * ( pd->num_switchers + 1 ) ); pd->switchers, sizeof(CombiMode) * (pd->num_switchers + 1));
Mode *mode = rofi_collect_modi_search(token); Mode *mode = rofi_collect_modi_search(token);
if (mode != NULL) { if (mode != NULL) {
@@ -95,9 +91,9 @@ static void combi_mode_parse_switchers ( Mode *sw )
// Free string that was modified by strtok_r // Free string that was modified by strtok_r
g_free(switcher_str); g_free(switcher_str);
} }
static unsigned int combi_mode_get_num_entries ( const Mode *sw ) static unsigned int combi_mode_get_num_entries(const Mode *sw) {
{ const CombiModePrivateData *pd =
const CombiModePrivateData *pd = (const CombiModePrivateData *) mode_get_private_data ( sw ); (const CombiModePrivateData *)mode_get_private_data(sw);
unsigned int length = 0; unsigned int length = 0;
for (unsigned int i = 0; i < pd->num_switchers; i++) { for (unsigned int i = 0; i < pd->num_switchers; i++) {
unsigned int entries = mode_get_num_entries(pd->switchers[i].mode); unsigned int entries = mode_get_num_entries(pd->switchers[i].mode);
@@ -108,8 +104,7 @@ static unsigned int combi_mode_get_num_entries ( const Mode *sw )
return length; return length;
} }
static int combi_mode_init ( Mode *sw ) static int combi_mode_init(Mode *sw) {
{
if (mode_get_private_data(sw) == NULL) { if (mode_get_private_data(sw) == NULL) {
CombiModePrivateData *pd = g_malloc0(sizeof(*pd)); CombiModePrivateData *pd = g_malloc0(sizeof(*pd));
mode_set_private_data(sw, (void *)pd); mode_set_private_data(sw, (void *)pd);
@@ -127,8 +122,7 @@ static int combi_mode_init ( Mode *sw )
} }
return TRUE; return TRUE;
} }
static void combi_mode_destroy ( Mode *sw ) static void combi_mode_destroy(Mode *sw) {
{
CombiModePrivateData *pd = (CombiModePrivateData *)mode_get_private_data(sw); CombiModePrivateData *pd = (CombiModePrivateData *)mode_get_private_data(sw);
if (pd != NULL) { if (pd != NULL) {
g_free(pd->starts); g_free(pd->starts);
@@ -142,8 +136,8 @@ static void combi_mode_destroy ( Mode *sw )
mode_set_private_data(sw, NULL); mode_set_private_data(sw, NULL);
} }
} }
static ModeMode combi_mode_result ( Mode *sw, int mretv, char **input, unsigned int selected_line ) static ModeMode combi_mode_result(Mode *sw, int mretv, char **input,
{ unsigned int selected_line) {
CombiModePrivateData *pd = mode_get_private_data(sw); CombiModePrivateData *pd = mode_get_private_data(sw);
if (input[0][0] == '!') { if (input[0][0] == '!') {
@@ -158,7 +152,8 @@ static ModeMode combi_mode_result ( Mode *sw, int mretv, char **input, unsigned
for (unsigned i = 0; i < pd->num_switchers; i++) { for (unsigned i = 0; i < pd->num_switchers; i++) {
const char *mode_name = mode_get_name(pd->switchers[i].mode); const char *mode_name = mode_get_name(pd->switchers[i].mode);
size_t mode_name_len = g_utf8_strlen(mode_name, -1); size_t mode_name_len = g_utf8_strlen(mode_name, -1);
if ( (size_t) bang_len <= mode_name_len && utf8_strncmp ( &input[0][1], mode_name, bang_len ) == 0 ) { if ((size_t)bang_len <= mode_name_len &&
utf8_strncmp(&input[0][1], mode_name, bang_len) == 0) {
switcher = i; switcher = i;
break; break;
} }
@@ -179,7 +174,8 @@ static ModeMode combi_mode_result ( Mode *sw, int mretv, char **input, unsigned
for (unsigned i = 0; i < pd->num_switchers; i++) { for (unsigned i = 0; i < pd->num_switchers; i++) {
if (selected_line >= pd->starts[i] && if (selected_line >= pd->starts[i] &&
selected_line < (pd->starts[i] + pd->lengths[i])) { selected_line < (pd->starts[i] + pd->lengths[i])) {
return mode_result ( pd->switchers[i].mode, mretv, input, selected_line - pd->starts[i] ); return mode_result(pd->switchers[i].mode, mretv, input,
selected_line - pd->starts[i]);
} }
} }
if ((mretv & MENU_CUSTOM_INPUT)) { if ((mretv & MENU_CUSTOM_INPUT)) {
@@ -187,35 +183,42 @@ static ModeMode combi_mode_result ( Mode *sw, int mretv, char **input, unsigned
} }
return MODE_EXIT; return MODE_EXIT;
} }
static int combi_mode_match ( const Mode *sw, rofi_int_matcher **tokens, unsigned int index ) static int combi_mode_match(const Mode *sw, rofi_int_matcher **tokens,
{ unsigned int index) {
CombiModePrivateData *pd = mode_get_private_data(sw); CombiModePrivateData *pd = mode_get_private_data(sw);
for (unsigned i = 0; i < pd->num_switchers; i++) { for (unsigned i = 0; i < pd->num_switchers; i++) {
if (pd->switchers[i].disable) { if (pd->switchers[i].disable) {
continue; continue;
} }
if (index >= pd->starts[i] && index < (pd->starts[i] + pd->lengths[i])) { if (index >= pd->starts[i] && index < (pd->starts[i] + pd->lengths[i])) {
return mode_token_match ( pd->switchers[i].mode, tokens, index - pd->starts[i] ); return mode_token_match(pd->switchers[i].mode, tokens,
index - pd->starts[i]);
} }
} }
return 0; return 0;
} }
static char * combi_mgrv ( const Mode *sw, unsigned int selected_line, int *state, GList **attr_list, int get_entry ) static char *combi_mgrv(const Mode *sw, unsigned int selected_line, int *state,
{ GList **attr_list, int get_entry) {
CombiModePrivateData *pd = mode_get_private_data(sw); CombiModePrivateData *pd = mode_get_private_data(sw);
if (!get_entry) { if (!get_entry) {
for (unsigned i = 0; i < pd->num_switchers; i++) { for (unsigned i = 0; i < pd->num_switchers; i++) {
if ( selected_line >= pd->starts[i] && selected_line < ( pd->starts[i] + pd->lengths[i] ) ) { if (selected_line >= pd->starts[i] &&
mode_get_display_value ( pd->switchers[i].mode, selected_line - pd->starts[i], state, attr_list, FALSE ); selected_line < (pd->starts[i] + pd->lengths[i])) {
mode_get_display_value(pd->switchers[i].mode,
selected_line - pd->starts[i], state, attr_list,
FALSE);
return NULL; return NULL;
} }
} }
return NULL; return NULL;
} }
for (unsigned i = 0; i < pd->num_switchers; i++) { for (unsigned i = 0; i < pd->num_switchers; i++) {
if ( selected_line >= pd->starts[i] && selected_line < ( pd->starts[i] + pd->lengths[i] ) ) { if (selected_line >= pd->starts[i] &&
selected_line < (pd->starts[i] + pd->lengths[i])) {
char *retv; char *retv;
char * str = retv = mode_get_display_value ( pd->switchers[i].mode, selected_line - pd->starts[i], state, attr_list, TRUE ); char *str = retv = mode_get_display_value(pd->switchers[i].mode,
selected_line - pd->starts[i],
state, attr_list, TRUE);
const char *dname = mode_get_display_name(pd->switchers[i].mode); const char *dname = mode_get_display_name(pd->switchers[i].mode);
if (!config.combi_hide_mode_prefix) { if (!config.combi_hide_mode_prefix) {
retv = g_strdup_printf("%s %s", dname, str); retv = g_strdup_printf("%s %s", dname, str);
@@ -223,11 +226,11 @@ static char * combi_mgrv ( const Mode *sw, unsigned int selected_line, int *stat
if (attr_list != NULL) { if (attr_list != NULL) {
ThemeWidget *wid = rofi_config_find_widget(sw->name, NULL, TRUE); ThemeWidget *wid = rofi_config_find_widget(sw->name, NULL, TRUE);
Property *p = rofi_theme_find_property ( wid, P_COLOR, pd->switchers[i].mode->name, TRUE ); Property *p = rofi_theme_find_property(
wid, P_COLOR, pd->switchers[i].mode->name, TRUE);
if (p != NULL) { if (p != NULL) {
PangoAttribute *pa = pango_attr_foreground_new( PangoAttribute *pa = pango_attr_foreground_new(
p->value.color.red * 65535, p->value.color.red * 65535, p->value.color.green * 65535,
p->value.color.green * 65535,
p->value.color.blue * 65535); p->value.color.blue * 65535);
pa->start_index = PANGO_ATTR_INDEX_FROM_TEXT_BEGINNING; pa->start_index = PANGO_ATTR_INDEX_FROM_TEXT_BEGINNING;
pa->end_index = strlen(dname); pa->end_index = strlen(dname);
@@ -241,13 +244,14 @@ static char * combi_mgrv ( const Mode *sw, unsigned int selected_line, int *stat
return NULL; return NULL;
} }
static char * combi_get_completion ( const Mode *sw, unsigned int index ) static char *combi_get_completion(const Mode *sw, unsigned int index) {
{
CombiModePrivateData *pd = mode_get_private_data(sw); CombiModePrivateData *pd = mode_get_private_data(sw);
for (unsigned i = 0; i < pd->num_switchers; i++) { for (unsigned i = 0; i < pd->num_switchers; i++) {
if (index >= pd->starts[i] && index < (pd->starts[i] + pd->lengths[i])) { if (index >= pd->starts[i] && index < (pd->starts[i] + pd->lengths[i])) {
char *comp = mode_get_completion ( pd->switchers[i].mode, index - pd->starts[i] ); char *comp =
char *mcomp = g_strdup_printf ( "!%s %s", mode_get_name ( pd->switchers[i].mode ), comp ); mode_get_completion(pd->switchers[i].mode, index - pd->starts[i]);
char *mcomp =
g_strdup_printf("!%s %s", mode_get_name(pd->switchers[i].mode), comp);
g_free(comp); g_free(comp);
return mcomp; return mcomp;
} }
@@ -257,20 +261,20 @@ static char * combi_get_completion ( const Mode *sw, unsigned int index )
return NULL; return NULL;
} }
static cairo_surface_t * combi_get_icon ( const Mode *sw, unsigned int index, int height ) static cairo_surface_t *combi_get_icon(const Mode *sw, unsigned int index,
{ int height) {
CombiModePrivateData *pd = mode_get_private_data(sw); CombiModePrivateData *pd = mode_get_private_data(sw);
for (unsigned i = 0; i < pd->num_switchers; i++) { for (unsigned i = 0; i < pd->num_switchers; i++) {
if (index >= pd->starts[i] && index < (pd->starts[i] + pd->lengths[i])) { if (index >= pd->starts[i] && index < (pd->starts[i] + pd->lengths[i])) {
cairo_surface_t *icon = mode_get_icon ( pd->switchers[i].mode, index - pd->starts[i], height ); cairo_surface_t *icon =
mode_get_icon(pd->switchers[i].mode, index - pd->starts[i], height);
return icon; return icon;
} }
} }
return NULL; return NULL;
} }
static char * combi_preprocess_input ( Mode *sw, const char *input ) static char *combi_preprocess_input(Mode *sw, const char *input) {
{
CombiModePrivateData *pd = mode_get_private_data(sw); CombiModePrivateData *pd = mode_get_private_data(sw);
for (unsigned i = 0; i < pd->num_switchers; i++) { for (unsigned i = 0; i < pd->num_switchers; i++) {
pd->switchers[i].disable = FALSE; pd->switchers[i].disable = FALSE;
@@ -287,7 +291,8 @@ static char * combi_preprocess_input ( Mode *sw, const char *input )
for (unsigned i = 0; i < pd->num_switchers; i++) { for (unsigned i = 0; i < pd->num_switchers; i++) {
const char *mode_name = mode_get_name(pd->switchers[i].mode); const char *mode_name = mode_get_name(pd->switchers[i].mode);
size_t mode_name_len = g_utf8_strlen(mode_name, -1); size_t mode_name_len = g_utf8_strlen(mode_name, -1);
if ( !( (size_t) bang_len <= mode_name_len && utf8_strncmp ( &input[1], mode_name, bang_len ) == 0 ) ) { if (!((size_t)bang_len <= mode_name_len &&
utf8_strncmp(&input[1], mode_name, bang_len) == 0)) {
// No match. // No match.
pd->switchers[i].disable = TRUE; pd->switchers[i].disable = TRUE;
} }
@@ -301,9 +306,7 @@ static char * combi_preprocess_input ( Mode *sw, const char *input )
return g_strdup(input); return g_strdup(input);
} }
Mode combi_mode = Mode combi_mode = {.name = "combi",
{
.name = "combi",
.cfg_name_key = "display-combi", .cfg_name_key = "display-combi",
._init = combi_mode_init, ._init = combi_mode_init,
._get_num_entries = combi_mode_get_num_entries, ._get_num_entries = combi_mode_get_num_entries,
@@ -315,5 +318,4 @@ Mode combi_mode =
._get_icon = combi_get_icon, ._get_icon = combi_get_icon,
._preprocess_input = combi_preprocess_input, ._preprocess_input = combi_preprocess_input,
.private_data = NULL, .private_data = NULL,
.free = NULL .free = NULL};
};

View File

@@ -28,52 +28,50 @@
/** The log domain of this dialog. */ /** The log domain of this dialog. */
#define G_LOG_DOMAIN "Dialogs.DMenu" #define G_LOG_DOMAIN "Dialogs.DMenu"
#include <config.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <strings.h>
#include <string.h>
#include <ctype.h>
#include <stdint.h>
#include <errno.h>
#include <gio/gio.h>
#include <gio/gunixinputstream.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "rofi.h"
#include "settings.h"
#include "widgets/textbox.h"
#include "dialogs/dmenu.h" #include "dialogs/dmenu.h"
#include "helper.h" #include "helper.h"
#include "xrmoptions.h"
#include "view.h"
#include "rofi-icon-fetcher.h" #include "rofi-icon-fetcher.h"
#include "rofi.h"
#include "settings.h"
#include "view.h"
#include "widgets/textbox.h"
#include "xrmoptions.h"
#include <ctype.h>
#include <errno.h>
#include <fcntl.h>
#include <gio/gio.h>
#include <gio/gunixinputstream.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include "dialogs/dmenuscriptshared.h" #include "dialogs/dmenuscriptshared.h"
static int dmenu_mode_init(Mode *sw); static int dmenu_mode_init(Mode *sw);
static int dmenu_token_match ( const Mode *sw, rofi_int_matcher **tokens, unsigned int index ); static int dmenu_token_match(const Mode *sw, rofi_int_matcher **tokens,
static cairo_surface_t *dmenu_get_icon ( const Mode *sw, unsigned int selected_line, int height ); unsigned int index);
static cairo_surface_t *dmenu_get_icon(const Mode *sw,
unsigned int selected_line, int height);
static char *dmenu_get_message(const Mode *sw); static char *dmenu_get_message(const Mode *sw);
static inline unsigned int bitget ( uint32_t *array, unsigned int index ) static inline unsigned int bitget(uint32_t *array, unsigned int index) {
{
uint32_t bit = index % 32; uint32_t bit = index % 32;
uint32_t val = array[index / 32]; uint32_t val = array[index / 32];
return (val >> bit) & 1; return (val >> bit) & 1;
} }
static inline void bittoggle ( uint32_t *array, unsigned int index ) static inline void bittoggle(uint32_t *array, unsigned int index) {
{
uint32_t bit = index % 32; uint32_t bit = index % 32;
uint32_t *v = &array[index / 32]; uint32_t *v = &array[index / 32];
*v ^= 1 << bit; *v ^= 1 << bit;
} }
typedef struct typedef struct {
{
/** Settings */ /** Settings */
// Separator. // Separator.
char separator; char separator;
@@ -105,18 +103,18 @@ typedef struct
GDataInputStream *data_input_stream; GDataInputStream *data_input_stream;
} DmenuModePrivateData; } DmenuModePrivateData;
static void async_close_callback ( GObject *source_object, GAsyncResult *res, G_GNUC_UNUSED gpointer user_data ) static void async_close_callback(GObject *source_object, GAsyncResult *res,
{ G_GNUC_UNUSED gpointer user_data) {
g_input_stream_close_finish(G_INPUT_STREAM(source_object), res, NULL); g_input_stream_close_finish(G_INPUT_STREAM(source_object), res, NULL);
g_debug("Closing data stream."); g_debug("Closing data stream.");
} }
static void read_add ( DmenuModePrivateData * pd, char *data, gsize len ) static void read_add(DmenuModePrivateData *pd, char *data, gsize len) {
{
gsize data_len = len; gsize data_len = len;
if ((pd->cmd_list_length + 2) > pd->cmd_list_real_length) { if ((pd->cmd_list_length + 2) > pd->cmd_list_real_length) {
pd->cmd_list_real_length = MAX(pd->cmd_list_real_length * 2, 512); pd->cmd_list_real_length = MAX(pd->cmd_list_real_length * 2, 512);
pd->cmd_list = g_realloc ( pd->cmd_list, ( pd->cmd_list_real_length ) * sizeof ( DmenuScriptEntry ) ); pd->cmd_list = g_realloc(pd->cmd_list, (pd->cmd_list_real_length) *
sizeof(DmenuScriptEntry));
} }
// Init. // Init.
pd->cmd_list[pd->cmd_list_length].icon_fetch_uid = 0; pd->cmd_list[pd->cmd_list_length].icon_fetch_uid = 0;
@@ -129,7 +127,8 @@ static void read_add ( DmenuModePrivateData * pd, char *data, gsize len )
} }
if (end != data + len) { if (end != data + len) {
data_len = end - data; data_len = end - data;
dmenuscript_parse_entry_extras ( NULL, &( pd->cmd_list[pd->cmd_list_length] ), end + 1, len - data_len ); dmenuscript_parse_entry_extras(NULL, &(pd->cmd_list[pd->cmd_list_length]),
end + 1, len - data_len);
} }
char *utfstr = rofi_force_utf8(data, data_len); char *utfstr = rofi_force_utf8(data, data_len);
pd->cmd_list[pd->cmd_list_length].entry = utfstr; pd->cmd_list[pd->cmd_list_length].entry = utfstr;
@@ -137,8 +136,8 @@ static void read_add ( DmenuModePrivateData * pd, char *data, gsize len )
pd->cmd_list_length++; pd->cmd_list_length++;
} }
static void async_read_callback ( GObject *source_object, GAsyncResult *res, gpointer user_data ) static void async_read_callback(GObject *source_object, GAsyncResult *res,
{ gpointer user_data) {
GDataInputStream *stream = (GDataInputStream *)source_object; GDataInputStream *stream = (GDataInputStream *)source_object;
DmenuModePrivateData *pd = (DmenuModePrivateData *)user_data; DmenuModePrivateData *pd = (DmenuModePrivateData *)user_data;
gsize len; gsize len;
@@ -150,11 +149,11 @@ static void async_read_callback ( GObject *source_object, GAsyncResult *res, gpo
g_free(data); g_free(data);
rofi_view_reload(); rofi_view_reload();
g_data_input_stream_read_upto_async ( pd->data_input_stream, &( pd->separator ), 1, G_PRIORITY_LOW, pd->cancel, g_data_input_stream_read_upto_async(pd->data_input_stream, &(pd->separator),
1, G_PRIORITY_LOW, pd->cancel,
async_read_callback, pd); async_read_callback, pd);
return; return;
} } else {
else {
GError *error = NULL; GError *error = NULL;
// Absorb separator, already in buffer so should not block. // Absorb separator, already in buffer so should not block.
// If error == NULL end of stream.. // If error == NULL end of stream..
@@ -164,49 +163,52 @@ static void async_read_callback ( GObject *source_object, GAsyncResult *res, gpo
read_add(pd, "", 0); read_add(pd, "", 0);
rofi_view_reload(); rofi_view_reload();
g_data_input_stream_read_upto_async ( pd->data_input_stream, &( pd->separator ), 1, G_PRIORITY_LOW, pd->cancel, g_data_input_stream_read_upto_async(pd->data_input_stream,
async_read_callback, pd ); &(pd->separator), 1, G_PRIORITY_LOW,
pd->cancel, async_read_callback, pd);
return; return;
} }
else {
g_error_free(error); g_error_free(error);
} }
}
if (!g_cancellable_is_cancelled(pd->cancel)) { if (!g_cancellable_is_cancelled(pd->cancel)) {
// Hack, don't use get active. // Hack, don't use get active.
g_debug("Clearing overlay"); g_debug("Clearing overlay");
rofi_view_set_overlay(rofi_view_get_active(), NULL); rofi_view_set_overlay(rofi_view_get_active(), NULL);
g_input_stream_close_async ( G_INPUT_STREAM ( stream ), G_PRIORITY_LOW, pd->cancel, async_close_callback, pd ); g_input_stream_close_async(G_INPUT_STREAM(stream), G_PRIORITY_LOW,
pd->cancel, async_close_callback, pd);
} }
} }
static void async_read_cancel ( G_GNUC_UNUSED GCancellable *cancel, G_GNUC_UNUSED gpointer data ) static void async_read_cancel(G_GNUC_UNUSED GCancellable *cancel,
{ G_GNUC_UNUSED gpointer data) {
g_debug("Cancelled the async read."); g_debug("Cancelled the async read.");
} }
static int get_dmenu_async ( DmenuModePrivateData *pd, int sync_pre_read ) static int get_dmenu_async(DmenuModePrivateData *pd, int sync_pre_read) {
{
while (sync_pre_read--) { while (sync_pre_read--) {
gsize len = 0; gsize len = 0;
char *data = g_data_input_stream_read_upto ( pd->data_input_stream, &( pd->separator ), 1, &len, NULL, NULL ); char *data = g_data_input_stream_read_upto(
pd->data_input_stream, &(pd->separator), 1, &len, NULL, NULL);
if (data == NULL) { if (data == NULL) {
g_input_stream_close_async ( G_INPUT_STREAM ( pd->input_stream ), G_PRIORITY_LOW, pd->cancel, async_close_callback, pd ); g_input_stream_close_async(G_INPUT_STREAM(pd->input_stream),
G_PRIORITY_LOW, pd->cancel,
async_close_callback, pd);
return FALSE; return FALSE;
} }
g_data_input_stream_read_byte(pd->data_input_stream, NULL, NULL); g_data_input_stream_read_byte(pd->data_input_stream, NULL, NULL);
read_add(pd, data, len); read_add(pd, data, len);
g_free(data); g_free(data);
} }
g_data_input_stream_read_upto_async ( pd->data_input_stream, &( pd->separator ), 1, G_PRIORITY_LOW, pd->cancel, g_data_input_stream_read_upto_async(pd->data_input_stream, &(pd->separator),
1, G_PRIORITY_LOW, pd->cancel,
async_read_callback, pd); async_read_callback, pd);
return TRUE; return TRUE;
} }
static void get_dmenu_sync ( DmenuModePrivateData *pd ) static void get_dmenu_sync(DmenuModePrivateData *pd) {
{
while (TRUE) { while (TRUE) {
gsize len = 0; gsize len = 0;
char *data = g_data_input_stream_read_upto ( pd->data_input_stream, &( pd->separator ), 1, &len, NULL, NULL ); char *data = g_data_input_stream_read_upto(
pd->data_input_stream, &(pd->separator), 1, &len, NULL, NULL);
if (data == NULL) { if (data == NULL) {
break; break;
} }
@@ -214,33 +216,35 @@ static void get_dmenu_sync ( DmenuModePrivateData *pd )
read_add(pd, data, len); read_add(pd, data, len);
g_free(data); g_free(data);
} }
g_input_stream_close_async ( G_INPUT_STREAM ( pd->input_stream ), G_PRIORITY_LOW, pd->cancel, async_close_callback, pd ); g_input_stream_close_async(G_INPUT_STREAM(pd->input_stream), G_PRIORITY_LOW,
pd->cancel, async_close_callback, pd);
} }
static unsigned int dmenu_mode_get_num_entries ( const Mode *sw ) static unsigned int dmenu_mode_get_num_entries(const Mode *sw) {
{ const DmenuModePrivateData *rmpd =
const DmenuModePrivateData *rmpd = (const DmenuModePrivateData *) mode_get_private_data ( sw ); (const DmenuModePrivateData *)mode_get_private_data(sw);
return rmpd->cmd_list_length; return rmpd->cmd_list_length;
} }
static gchar * dmenu_format_output_string ( const DmenuModePrivateData *pd, const char *input ) static gchar *dmenu_format_output_string(const DmenuModePrivateData *pd,
{ const char *input) {
if (pd->columns == NULL) { if (pd->columns == NULL) {
return g_strdup(input); return g_strdup(input);
} }
char *retv = NULL; char *retv = NULL;
char ** splitted = g_regex_split_simple ( pd->column_separator, input, G_REGEX_CASELESS, 00 ); char **splitted =
g_regex_split_simple(pd->column_separator, input, G_REGEX_CASELESS, 00);
uint32_t ns = 0; uint32_t ns = 0;
for (; splitted && splitted[ns]; ns++) { for (; splitted && splitted[ns]; ns++) {
; ;
} }
for (uint32_t i = 0; pd->columns && pd->columns[i]; i++) { for (uint32_t i = 0; pd->columns && pd->columns[i]; i++) {
unsigned int index = (unsigned int ) g_ascii_strtoull ( pd->columns[i], NULL, 10 ); unsigned int index =
(unsigned int)g_ascii_strtoull(pd->columns[i], NULL, 10);
if (index < ns && index > 0) { if (index < ns && index > 0) {
if (retv == NULL) { if (retv == NULL) {
retv = g_strdup(splitted[index - 1]); retv = g_strdup(splitted[index - 1]);
} } else {
else {
gchar *t = g_strjoin("\t", retv, splitted[index - 1], NULL); gchar *t = g_strjoin("\t", retv, splitted[index - 1], NULL);
g_free(retv); g_free(retv);
retv = t; retv = t;
@@ -251,8 +255,7 @@ static gchar * dmenu_format_output_string ( const DmenuModePrivateData *pd, cons
return retv ? retv : g_strdup(""); return retv ? retv : g_strdup("");
} }
static inline unsigned int get_index ( unsigned int length, int index ) static inline unsigned int get_index(unsigned int length, int index) {
{
if (index >= 0) { if (index >= 0) {
return index; return index;
} }
@@ -263,20 +266,22 @@ static inline unsigned int get_index ( unsigned int length, int index )
return UINT_MAX; return UINT_MAX;
} }
static char *get_display_data ( const Mode *data, unsigned int index, int *state, G_GNUC_UNUSED GList **list, int get_entry ) static char *get_display_data(const Mode *data, unsigned int index, int *state,
{ G_GNUC_UNUSED GList **list, int get_entry) {
Mode *sw = (Mode *)data; Mode *sw = (Mode *)data;
DmenuModePrivateData *pd = (DmenuModePrivateData *)mode_get_private_data(sw); DmenuModePrivateData *pd = (DmenuModePrivateData *)mode_get_private_data(sw);
DmenuScriptEntry *retv = (DmenuScriptEntry *)pd->cmd_list; DmenuScriptEntry *retv = (DmenuScriptEntry *)pd->cmd_list;
for (unsigned int i = 0; i < pd->num_active_list; i++) { for (unsigned int i = 0; i < pd->num_active_list; i++) {
unsigned int start = get_index ( pd->cmd_list_length, pd->active_list[i].start ); unsigned int start =
get_index(pd->cmd_list_length, pd->active_list[i].start);
unsigned int stop = get_index(pd->cmd_list_length, pd->active_list[i].stop); unsigned int stop = get_index(pd->cmd_list_length, pd->active_list[i].stop);
if (index >= start && index <= stop) { if (index >= start && index <= stop) {
*state |= ACTIVE; *state |= ACTIVE;
} }
} }
for (unsigned int i = 0; i < pd->num_urgent_list; i++) { for (unsigned int i = 0; i < pd->num_urgent_list; i++) {
unsigned int start = get_index ( pd->cmd_list_length, pd->urgent_list[i].start ); unsigned int start =
get_index(pd->cmd_list_length, pd->urgent_list[i].start);
unsigned int stop = get_index(pd->cmd_list_length, pd->urgent_list[i].stop); unsigned int stop = get_index(pd->cmd_list_length, pd->urgent_list[i].stop);
if (index >= start && index <= stop) { if (index >= start && index <= stop) {
*state |= URGENT; *state |= URGENT;
@@ -291,8 +296,7 @@ static char *get_display_data ( const Mode *data, unsigned int index, int *state
return get_entry ? dmenu_format_output_string(pd, retv[index].entry) : NULL; return get_entry ? dmenu_format_output_string(pd, retv[index].entry) : NULL;
} }
static void dmenu_mode_free ( Mode *sw ) static void dmenu_mode_free(Mode *sw) {
{
if (mode_get_private_data(sw) == NULL) { if (mode_get_private_data(sw) == NULL) {
return; return;
} }
@@ -333,9 +337,7 @@ static void dmenu_mode_free ( Mode *sw )
#include "mode-private.h" #include "mode-private.h"
/** dmenu Mode object. */ /** dmenu Mode object. */
Mode dmenu_mode = Mode dmenu_mode = {.name = "dmenu",
{
.name = "dmenu",
.cfg_name_key = "display-combi", .cfg_name_key = "display-combi",
._init = dmenu_mode_init, ._init = dmenu_mode_init,
._get_num_entries = dmenu_mode_get_num_entries, ._get_num_entries = dmenu_mode_get_num_entries,
@@ -349,11 +351,9 @@ Mode dmenu_mode =
._get_message = dmenu_get_message, ._get_message = dmenu_get_message,
.private_data = NULL, .private_data = NULL,
.free = NULL, .free = NULL,
.display_name = "dmenu" .display_name = "dmenu"};
};
static int dmenu_mode_init ( Mode *sw ) static int dmenu_mode_init(Mode *sw) {
{
if (mode_get_private_data(sw) != NULL) { if (mode_get_private_data(sw) != NULL) {
return TRUE; return TRUE;
} }
@@ -394,8 +394,11 @@ static int dmenu_mode_init ( Mode *sw )
Property *p = rofi_theme_property_create(P_INTEGER); Property *p = rofi_theme_property_create(P_INTEGER);
p->name = g_strdup("lines"); p->name = g_strdup("lines");
p->value.i = lines; p->value.i = lines;
ThemeWidget *widget = rofi_theme_find_or_create_name ( rofi_theme, "listview" ); ThemeWidget *widget =
GHashTable *table = g_hash_table_new_full ( g_str_hash, g_str_equal, NULL, (GDestroyNotify) rofi_theme_property_free ); rofi_theme_find_or_create_name(rofi_theme, "listview");
GHashTable *table =
g_hash_table_new_full(g_str_hash, g_str_equal, NULL,
(GDestroyNotify)rofi_theme_property_free);
g_hash_table_replace(table, p->name, p); g_hash_table_replace(table, p->name, p);
rofi_theme_widget_add_properties(widget, table); rofi_theme_widget_add_properties(widget, table);
@@ -426,7 +429,9 @@ static int dmenu_mode_init ( Mode *sw )
char *estr = rofi_expand_path(str); char *estr = rofi_expand_path(str);
fd = open(str, O_RDONLY); fd = open(str, O_RDONLY);
if (fd < 0) { if (fd < 0) {
char *msg = g_markup_printf_escaped ( "Failed to open file: <b>%s</b>:\n\t<i>%s</i>", estr, g_strerror ( errno ) ); char *msg = g_markup_printf_escaped(
"Failed to open file: <b>%s</b>:\n\t<i>%s</i>", estr,
g_strerror(errno));
rofi_view_error_dialog(msg, TRUE); rofi_view_error_dialog(msg, TRUE);
g_free(msg); g_free(msg);
g_free(estr); g_free(estr);
@@ -434,10 +439,12 @@ static int dmenu_mode_init ( Mode *sw )
} }
g_free(estr); g_free(estr);
} }
// If input is stdin, and a tty, do not read as rofi grabs input and therefore blocks. // If input is stdin, and a tty, do not read as rofi grabs input and therefore
// blocks.
if (!(fd == STDIN_FILENO && isatty(fd) == 1)) { if (!(fd == STDIN_FILENO && isatty(fd) == 1)) {
pd->cancel = g_cancellable_new(); pd->cancel = g_cancellable_new();
pd->cancel_source = g_cancellable_connect ( pd->cancel, G_CALLBACK ( async_read_cancel ), pd, NULL ); pd->cancel_source = g_cancellable_connect(
pd->cancel, G_CALLBACK(async_read_cancel), pd, NULL);
pd->input_stream = g_unix_input_stream_new(fd, fd != STDIN_FILENO); pd->input_stream = g_unix_input_stream_new(fd, fd != STDIN_FILENO);
pd->data_input_stream = g_data_input_stream_new(pd->input_stream); pd->data_input_stream = g_data_input_stream_new(pd->input_stream);
} }
@@ -450,15 +457,16 @@ static int dmenu_mode_init ( Mode *sw )
return TRUE; return TRUE;
} }
static int dmenu_token_match ( const Mode *sw, rofi_int_matcher **tokens, unsigned int index ) static int dmenu_token_match(const Mode *sw, rofi_int_matcher **tokens,
{ unsigned int index) {
DmenuModePrivateData *rmpd = (DmenuModePrivateData *) mode_get_private_data ( sw ); DmenuModePrivateData *rmpd =
(DmenuModePrivateData *)mode_get_private_data(sw);
/** Strip out the markup when matching. */ /** Strip out the markup when matching. */
char *esc = NULL; char *esc = NULL;
if (rmpd->do_markup) { if (rmpd->do_markup) {
pango_parse_markup ( rmpd->cmd_list[index].entry, -1, 0, NULL, &esc, NULL, NULL ); pango_parse_markup(rmpd->cmd_list[index].entry, -1, 0, NULL, &esc, NULL,
} NULL);
else { } else {
esc = rmpd->cmd_list[index].entry; esc = rmpd->cmd_list[index].entry;
} }
if (esc) { if (esc) {
@@ -485,16 +493,15 @@ static int dmenu_token_match ( const Mode *sw, rofi_int_matcher **tokens, unsign
} }
return FALSE; return FALSE;
} }
static char *dmenu_get_message ( const Mode *sw ) static char *dmenu_get_message(const Mode *sw) {
{
DmenuModePrivateData *pd = (DmenuModePrivateData *)mode_get_private_data(sw); DmenuModePrivateData *pd = (DmenuModePrivateData *)mode_get_private_data(sw);
if (pd->message) { if (pd->message) {
return g_strdup(pd->message); return g_strdup(pd->message);
} }
return NULL; return NULL;
} }
static cairo_surface_t *dmenu_get_icon ( const Mode *sw, unsigned int selected_line, int height ) static cairo_surface_t *dmenu_get_icon(const Mode *sw,
{ unsigned int selected_line, int height) {
DmenuModePrivateData *pd = (DmenuModePrivateData *)mode_get_private_data(sw); DmenuModePrivateData *pd = (DmenuModePrivateData *)mode_get_private_data(sw);
g_return_val_if_fail(pd->cmd_list != NULL, NULL); g_return_val_if_fail(pd->cmd_list != NULL, NULL);
DmenuScriptEntry *dr = &(pd->cmd_list[selected_line]); DmenuScriptEntry *dr = &(pd->cmd_list[selected_line]);
@@ -508,15 +515,12 @@ static cairo_surface_t *dmenu_get_icon ( const Mode *sw, unsigned int selected_l
return rofi_icon_fetcher_get(dr->icon_fetch_uid); return rofi_icon_fetcher_get(dr->icon_fetch_uid);
} }
static void dmenu_finish ( RofiViewState *state, int retv ) static void dmenu_finish(RofiViewState *state, int retv) {
{
if (retv == FALSE) { if (retv == FALSE) {
rofi_set_return_code(EXIT_FAILURE); rofi_set_return_code(EXIT_FAILURE);
} } else if (retv >= 10) {
else if ( retv >= 10 ) {
rofi_set_return_code(retv); rofi_set_return_code(retv);
} } else {
else {
rofi_set_return_code(EXIT_SUCCESS); rofi_set_return_code(EXIT_SUCCESS);
} }
rofi_view_set_active(NULL); rofi_view_set_active(NULL);
@@ -524,8 +528,7 @@ static void dmenu_finish ( RofiViewState *state, int retv )
mode_destroy(&dmenu_mode); mode_destroy(&dmenu_mode);
} }
static void dmenu_print_results ( DmenuModePrivateData *pd, const char *input ) static void dmenu_print_results(DmenuModePrivateData *pd, const char *input) {
{
DmenuScriptEntry *cmd_list = pd->cmd_list; DmenuScriptEntry *cmd_list = pd->cmd_list;
int seen = FALSE; int seen = FALSE;
if (pd->selected_list != NULL) { if (pd->selected_list != NULL) {
@@ -545,15 +548,16 @@ static void dmenu_print_results ( DmenuModePrivateData *pd, const char *input )
} }
} }
static void dmenu_finalize ( RofiViewState *state ) static void dmenu_finalize(RofiViewState *state) {
{
int retv = FALSE; int retv = FALSE;
DmenuModePrivateData *pd = (DmenuModePrivateData *) rofi_view_get_mode ( state )->private_data; DmenuModePrivateData *pd =
(DmenuModePrivateData *)rofi_view_get_mode(state)->private_data;
unsigned int cmd_list_length = pd->cmd_list_length; unsigned int cmd_list_length = pd->cmd_list_length;
DmenuScriptEntry *cmd_list = pd->cmd_list; DmenuScriptEntry *cmd_list = pd->cmd_list;
char *input = g_strdup(rofi_view_get_user_input(state)); char *input = g_strdup(rofi_view_get_user_input(state));
pd->selected_line = rofi_view_get_selected_line ( state );; pd->selected_line = rofi_view_get_selected_line(state);
;
MenuReturn mretv = rofi_view_get_return_value(state); MenuReturn mretv = rofi_view_get_return_value(state);
unsigned int next_pos = rofi_view_get_next_position(state); unsigned int next_pos = rofi_view_get_next_position(state);
int restart = 0; int restart = 0;
@@ -567,27 +571,28 @@ static void dmenu_finalize ( RofiViewState *state )
if ((mretv & MENU_CANCEL) == MENU_CANCEL) { if ((mretv & MENU_CANCEL) == MENU_CANCEL) {
// In no custom mode we allow canceling. // In no custom mode we allow canceling.
restart = (find_arg("-only-match") >= 0); restart = (find_arg("-only-match") >= 0);
} } else if (pd->selected_line != UINT32_MAX) {
else if ( pd->selected_line != UINT32_MAX ) {
if ((mretv & MENU_CUSTOM_ACTION) && pd->multi_select) { if ((mretv & MENU_CUSTOM_ACTION) && pd->multi_select) {
restart = TRUE; restart = TRUE;
if (pd->selected_list == NULL) { if (pd->selected_list == NULL) {
pd->selected_list = g_malloc0 ( sizeof ( uint32_t ) * ( pd->cmd_list_length / 32 + 1 ) ); pd->selected_list =
g_malloc0(sizeof(uint32_t) * (pd->cmd_list_length / 32 + 1));
} }
pd->selected_count += ( bitget ( pd->selected_list, pd->selected_line ) ? ( -1 ) : ( 1 ) ); pd->selected_count +=
(bitget(pd->selected_list, pd->selected_line) ? (-1) : (1));
bittoggle(pd->selected_list, pd->selected_line); bittoggle(pd->selected_list, pd->selected_line);
// Move to next line. // Move to next line.
pd->selected_line = MIN(next_pos, cmd_list_length - 1); pd->selected_line = MIN(next_pos, cmd_list_length - 1);
if (pd->selected_count > 0) { if (pd->selected_count > 0) {
char *str = g_strdup_printf ( "%u/%u", pd->selected_count, pd->cmd_list_length ); char *str =
g_strdup_printf("%u/%u", pd->selected_count, pd->cmd_list_length);
rofi_view_set_overlay(state, str); rofi_view_set_overlay(state, str);
g_free(str); g_free(str);
} } else {
else {
rofi_view_set_overlay(state, NULL); rofi_view_set_overlay(state, NULL);
} }
} } else if ((mretv & (MENU_OK | MENU_CUSTOM_COMMAND)) &&
else if ( ( mretv & ( MENU_OK | MENU_CUSTOM_COMMAND ) ) && cmd_list[pd->selected_line].entry != NULL ) { cmd_list[pd->selected_line].entry != NULL) {
if (cmd_list[pd->selected_line].nonselectable == TRUE) { if (cmd_list[pd->selected_line].nonselectable == TRUE) {
g_free(input); g_free(input);
return; return;
@@ -600,8 +605,7 @@ static void dmenu_finalize ( RofiViewState *state )
g_free(input); g_free(input);
dmenu_finish(state, retv); dmenu_finish(state, retv);
return; return;
} } else {
else {
pd->selected_line = next_pos - 1; pd->selected_line = next_pos - 1;
} }
} }
@@ -616,7 +620,8 @@ static void dmenu_finalize ( RofiViewState *state )
// We normally do not want to restart the loop. // We normally do not want to restart the loop.
restart = FALSE; restart = FALSE;
// Normal mode // Normal mode
if ( ( mretv & MENU_OK ) && pd->selected_line != UINT32_MAX && cmd_list[pd->selected_line].entry != NULL ) { if ((mretv & MENU_OK) && pd->selected_line != UINT32_MAX &&
cmd_list[pd->selected_line].entry != NULL) {
// Check if entry is non-selectable. // Check if entry is non-selectable.
if (cmd_list[pd->selected_line].nonselectable == TRUE) { if (cmd_list[pd->selected_line].nonselectable == TRUE) {
g_free(input); g_free(input);
@@ -625,22 +630,23 @@ static void dmenu_finalize ( RofiViewState *state )
if ((mretv & MENU_CUSTOM_ACTION) && pd->multi_select) { if ((mretv & MENU_CUSTOM_ACTION) && pd->multi_select) {
restart = TRUE; restart = TRUE;
if (pd->selected_list == NULL) { if (pd->selected_list == NULL) {
pd->selected_list = g_malloc0 ( sizeof ( uint32_t ) * ( pd->cmd_list_length / 32 + 1 ) ); pd->selected_list =
g_malloc0(sizeof(uint32_t) * (pd->cmd_list_length / 32 + 1));
} }
pd->selected_count += ( bitget ( pd->selected_list, pd->selected_line ) ? ( -1 ) : ( 1 ) ); pd->selected_count +=
(bitget(pd->selected_list, pd->selected_line) ? (-1) : (1));
bittoggle(pd->selected_list, pd->selected_line); bittoggle(pd->selected_list, pd->selected_line);
// Move to next line. // Move to next line.
pd->selected_line = MIN(next_pos, cmd_list_length - 1); pd->selected_line = MIN(next_pos, cmd_list_length - 1);
if (pd->selected_count > 0) { if (pd->selected_count > 0) {
char *str = g_strdup_printf ( "%u/%u", pd->selected_count, pd->cmd_list_length ); char *str =
g_strdup_printf("%u/%u", pd->selected_count, pd->cmd_list_length);
rofi_view_set_overlay(state, str); rofi_view_set_overlay(state, str);
g_free(str); g_free(str);
} } else {
else {
rofi_view_set_overlay(state, NULL); rofi_view_set_overlay(state, NULL);
} }
} } else {
else {
dmenu_print_results(pd, input); dmenu_print_results(pd, input);
} }
retv = TRUE; retv = TRUE;
@@ -662,22 +668,21 @@ static void dmenu_finalize ( RofiViewState *state )
if (restart) { if (restart) {
rofi_view_restart(state); rofi_view_restart(state);
rofi_view_set_selected_line(state, pd->selected_line); rofi_view_set_selected_line(state, pd->selected_line);
} } else {
else {
dmenu_finish(state, retv); dmenu_finish(state, retv);
} }
} }
int dmenu_switcher_dialog ( void ) int dmenu_switcher_dialog(void) {
{
mode_init(&dmenu_mode); mode_init(&dmenu_mode);
MenuFlags menu_flags = MENU_NORMAL; MenuFlags menu_flags = MENU_NORMAL;
DmenuModePrivateData *pd = (DmenuModePrivateData *)dmenu_mode.private_data; DmenuModePrivateData *pd = (DmenuModePrivateData *)dmenu_mode.private_data;
int async = TRUE; int async = TRUE;
// For now these only work in sync mode. // For now these only work in sync mode.
if ( find_arg ( "-sync" ) >= 0 || find_arg ( "-dump" ) >= 0 || find_arg ( "-select" ) >= 0 if (find_arg("-sync") >= 0 || find_arg("-dump") >= 0 ||
|| find_arg ( "-no-custom" ) >= 0 || find_arg ( "-only-match" ) >= 0 || config.auto_select || find_arg("-select") >= 0 || find_arg("-no-custom") >= 0 ||
find_arg("-only-match") >= 0 || config.auto_select ||
find_arg("-selected-row") >= 0) { find_arg("-selected-row") >= 0) {
async = FALSE; async = FALSE;
} }
@@ -688,8 +693,7 @@ int dmenu_switcher_dialog ( void )
unsigned int pre_read = 25; unsigned int pre_read = 25;
find_arg_uint("-async-pre-read", &pre_read); find_arg_uint("-async-pre-read", &pre_read);
async = get_dmenu_async(pd, pre_read); async = get_dmenu_async(pd, pre_read);
} } else {
else {
get_dmenu_sync(pd); get_dmenu_sync(pd);
} }
} }
@@ -736,11 +740,13 @@ int dmenu_switcher_dialog ( void )
helper_tokenize_free(tokens); helper_tokenize_free(tokens);
} }
if (find_arg("-dump") >= 0) { if (find_arg("-dump") >= 0) {
rofi_int_matcher **tokens = helper_tokenize ( config.filter ? config.filter : "", config.case_sensitive ); rofi_int_matcher **tokens = helper_tokenize(
config.filter ? config.filter : "", config.case_sensitive);
unsigned int i = 0; unsigned int i = 0;
for (i = 0; i < cmd_list_length; i++) { for (i = 0; i < cmd_list_length; i++) {
if (tokens == NULL || helper_token_match(tokens, cmd_list[i].entry)) { if (tokens == NULL || helper_token_match(tokens, cmd_list[i].entry)) {
rofi_output_formatted_line ( pd->format, cmd_list[i].entry, i, config.filter ); rofi_output_formatted_line(pd->format, cmd_list[i].entry, i,
config.filter);
} }
} }
helper_tokenize_free(tokens); helper_tokenize_free(tokens);
@@ -749,7 +755,8 @@ int dmenu_switcher_dialog ( void )
return TRUE; return TRUE;
} }
find_arg_str("-p", &(dmenu_mode.display_name)); find_arg_str("-p", &(dmenu_mode.display_name));
RofiViewState *state = rofi_view_create ( &dmenu_mode, input, menu_flags, dmenu_finalize ); RofiViewState *state =
rofi_view_create(&dmenu_mode, input, menu_flags, dmenu_finalize);
if (find_arg("-keep-right") >= 0) { if (find_arg("-keep-right") >= 0) {
rofi_view_ellipsize_start(state); rofi_view_ellipsize_start(state);
@@ -764,27 +771,48 @@ int dmenu_switcher_dialog ( void )
return FALSE; return FALSE;
} }
void print_dmenu_options ( void ) void print_dmenu_options(void) {
{
int is_term = isatty(fileno(stdout)); int is_term = isatty(fileno(stdout));
print_help_msg ( "-mesg", "[string]", "Print a small user message under the prompt (uses pango markup)", NULL, is_term ); print_help_msg(
print_help_msg ( "-p", "[string]", "Prompt to display left of entry field", NULL, is_term ); "-mesg", "[string]",
"Print a small user message under the prompt (uses pango markup)", NULL,
is_term);
print_help_msg("-p", "[string]", "Prompt to display left of entry field",
NULL, is_term);
print_help_msg("-selected-row", "[integer]", "Select row", NULL, is_term); print_help_msg("-selected-row", "[integer]", "Select row", NULL, is_term);
print_help_msg("-format", "[string]", "Output format string", "s", is_term); print_help_msg("-format", "[string]", "Output format string", "s", is_term);
print_help_msg ( "-u", "[list]", "List of row indexes to mark urgent", NULL, is_term ); print_help_msg("-u", "[list]", "List of row indexes to mark urgent", NULL,
print_help_msg ( "-a", "[list]", "List of row indexes to mark active", NULL, is_term ); is_term);
print_help_msg ( "-l", "[integer] ", "Number of rows to display", NULL, is_term ); print_help_msg("-a", "[list]", "List of row indexes to mark active", NULL,
print_help_msg ( "-window-title", "[string] ", "Set the dmenu window title", NULL, is_term ); is_term);
print_help_msg("-l", "[integer] ", "Number of rows to display", NULL,
is_term);
print_help_msg("-window-title", "[string] ", "Set the dmenu window title",
NULL, is_term);
print_help_msg("-i", "", "Set filter to be case insensitive", NULL, is_term); print_help_msg("-i", "", "Set filter to be case insensitive", NULL, is_term);
print_help_msg ( "-only-match", "", "Force selection to be given entry, disallow no match", NULL, is_term ); print_help_msg("-only-match", "",
print_help_msg ( "-no-custom", "", "Don't accept custom entry, allow no match", NULL, is_term ); "Force selection to be given entry, disallow no match", NULL,
print_help_msg ( "-select", "[string]", "Select the first row that matches", NULL, is_term ); is_term);
print_help_msg ( "-password", "", "Do not show what the user inputs. Show '*' instead.", NULL, is_term ); print_help_msg("-no-custom", "", "Don't accept custom entry, allow no match",
print_help_msg ( "-markup-rows", "", "Allow and render pango markup as input data.", NULL, is_term ); NULL, is_term);
print_help_msg("-select", "[string]", "Select the first row that matches",
NULL, is_term);
print_help_msg("-password", "",
"Do not show what the user inputs. Show '*' instead.", NULL,
is_term);
print_help_msg("-markup-rows", "",
"Allow and render pango markup as input data.", NULL, is_term);
print_help_msg("-sep", "[char]", "Element separator.", "'\\n'", is_term); print_help_msg("-sep", "[char]", "Element separator.", "'\\n'", is_term);
print_help_msg ( "-input", "[filename]", "Read input from file instead from standard input.", NULL, is_term ); print_help_msg("-input", "[filename]",
print_help_msg ( "-sync", "", "Force dmenu to first read all input data, then show dialog.", NULL, is_term ); "Read input from file instead from standard input.", NULL,
print_help_msg ( "-async-pre-read", "[number]", "Read several entries blocking before switching to async mode", "25", is_term ); is_term);
print_help_msg ( "-w", "windowid", "Position over window with X11 windowid.", NULL, is_term ); print_help_msg("-sync", "",
"Force dmenu to first read all input data, then show dialog.",
NULL, is_term);
print_help_msg("-async-pre-read", "[number]",
"Read several entries blocking before switching to async mode",
"25", is_term);
print_help_msg("-w", "windowid", "Position over window with X11 windowid.",
NULL, is_term);
print_help_msg("-keep-right", "", "Set ellipsize to end.", NULL, is_term); print_help_msg("-keep-right", "", "Set ellipsize to end.", NULL, is_term);
} }

File diff suppressed because it is too large Load Diff

View File

@@ -23,25 +23,25 @@
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/ */
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <errno.h> #include <errno.h>
#include <gmodule.h>
#include <gio/gio.h> #include <gio/gio.h>
#include <gmodule.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <dirent.h> #include <dirent.h>
#include <sys/stat.h>
#include <sys/types.h>
#include "mode.h"
#include "theme.h"
#include "helper.h"
#include "mode-private.h"
#include "dialogs/filebrowser.h" #include "dialogs/filebrowser.h"
#include "rofi.h" #include "helper.h"
#include "history.h" #include "history.h"
#include "mode-private.h"
#include "mode.h"
#include "rofi.h"
#include "theme.h"
#include <stdint.h> #include <stdint.h>
@@ -52,8 +52,7 @@
/** /**
* The internal data structure holding the private data of the TEST Mode. * The internal data structure holding the private data of the TEST Mode.
*/ */
enum FBFileType enum FBFileType {
{
UP, UP,
DIRECTORY, DIRECTORY,
RFILE, RFILE,
@@ -63,8 +62,7 @@ enum FBFileType
/** /**
* Possible sorting methods * Possible sorting methods
*/ */
enum FBSortingMethod enum FBSortingMethod {
{
FB_SORT_NAME, FB_SORT_NAME,
FB_SORT_TIME, FB_SORT_TIME,
}; };
@@ -72,22 +70,15 @@ enum FBSortingMethod
/** /**
* Type of time to sort by * Type of time to sort by
*/ */
enum FBSortingTime enum FBSortingTime {
{
FB_MTIME, FB_MTIME,
FB_ATIME, FB_ATIME,
FB_CTIME, FB_CTIME,
}; };
/** Icons to use for the file type */ /** Icons to use for the file type */
const char *icon_name[NUM_FILE_TYPES] = const char *icon_name[NUM_FILE_TYPES] = {"go-up", "folder", "gtk-file"};
{ typedef struct {
"go-up",
"folder",
"gtk-file"
};
typedef struct
{
char *name; char *name;
char *path; char *path;
enum FBFileType type; enum FBFileType type;
@@ -96,15 +87,13 @@ typedef struct
time_t time; time_t time;
} FBFile; } FBFile;
typedef struct typedef struct {
{
GFile *current_dir; GFile *current_dir;
FBFile *array; FBFile *array;
unsigned int array_length; unsigned int array_length;
} FileBrowserModePrivateData; } FileBrowserModePrivateData;
struct struct {
{
enum FBSortingMethod sorting_method; enum FBSortingMethod sorting_method;
enum FBSortingTime sorting_time; enum FBSortingTime sorting_time;
gboolean directories_first; gboolean directories_first;
@@ -114,8 +103,7 @@ struct
.directories_first = TRUE, .directories_first = TRUE,
}; };
static void free_list ( FileBrowserModePrivateData *pd ) static void free_list(FileBrowserModePrivateData *pd) {
{
for (unsigned int i = 0; i < pd->array_length; i++) { for (unsigned int i = 0; i < pd->array_length; i++) {
FBFile *fb = &(pd->array[i]); FBFile *fb = &(pd->array[i]);
g_free(fb->name); g_free(fb->name);
@@ -125,11 +113,11 @@ static void free_list ( FileBrowserModePrivateData *pd )
pd->array = NULL; pd->array = NULL;
pd->array_length = 0; pd->array_length = 0;
} }
#include <sys/types.h>
#include <dirent.h> #include <dirent.h>
#include <sys/types.h>
static gint compare_name ( gconstpointer a, gconstpointer b, G_GNUC_UNUSED gpointer data ) static gint compare_name(gconstpointer a, gconstpointer b,
{ G_GNUC_UNUSED gpointer data) {
FBFile *fa = (FBFile *)a; FBFile *fa = (FBFile *)a;
FBFile *fb = (FBFile *)b; FBFile *fb = (FBFile *)b;
@@ -140,8 +128,8 @@ static gint compare_name ( gconstpointer a, gconstpointer b, G_GNUC_UNUSED gpoin
return g_strcmp0(fa->name, fb->name); return g_strcmp0(fa->name, fb->name);
} }
static gint compare_time ( gconstpointer a, gconstpointer b, G_GNUC_UNUSED gpointer data ) static gint compare_time(gconstpointer a, gconstpointer b,
{ G_GNUC_UNUSED gpointer data) {
FBFile *fa = (FBFile *)a; FBFile *fa = (FBFile *)a;
FBFile *fb = (FBFile *)b; FBFile *fb = (FBFile *)b;
@@ -160,12 +148,10 @@ static gint compare_time ( gconstpointer a, gconstpointer b, G_GNUC_UNUSED gpoin
return fb->time - fa->time; return fb->time - fa->time;
} }
static gint compare ( gconstpointer a, gconstpointer b, gpointer data ) static gint compare(gconstpointer a, gconstpointer b, gpointer data) {
{
GCompareDataFunc comparator = NULL; GCompareDataFunc comparator = NULL;
switch ( file_browser_config.sorting_method ) switch (file_browser_config.sorting_method) {
{
case FB_SORT_NAME: case FB_SORT_NAME:
comparator = compare_name; comparator = compare_name;
break; break;
@@ -180,10 +166,8 @@ static gint compare ( gconstpointer a, gconstpointer b, gpointer data )
return comparator(a, b, data); return comparator(a, b, data);
} }
static time_t get_time ( const struct stat *statbuf ) static time_t get_time(const struct stat *statbuf) {
{ switch (file_browser_config.sorting_time) {
switch ( file_browser_config.sorting_time )
{
case FB_MTIME: case FB_MTIME:
return statbuf->st_mtim.tv_sec; return statbuf->st_mtim.tv_sec;
case FB_ATIME: case FB_ATIME:
@@ -195,25 +179,23 @@ static time_t get_time ( const struct stat *statbuf )
} }
} }
static void set_time ( FBFile *file ) static void set_time(FBFile *file) {
{
gchar *path = g_filename_from_utf8(file->path, -1, NULL, NULL, NULL); gchar *path = g_filename_from_utf8(file->path, -1, NULL, NULL, NULL);
struct stat statbuf; struct stat statbuf;
if (stat(path, &statbuf) == 0) { if (stat(path, &statbuf) == 0) {
file->time = get_time(&statbuf); file->time = get_time(&statbuf);
} } else {
else {
g_warning("Failed to stat file: %s, %s", path, strerror(errno)); g_warning("Failed to stat file: %s, %s", path, strerror(errno));
} }
g_free(path); g_free(path);
} }
static void get_file_browser ( Mode *sw ) static void get_file_browser(Mode *sw) {
{ FileBrowserModePrivateData *pd =
FileBrowserModePrivateData *pd = (FileBrowserModePrivateData *) mode_get_private_data ( sw ); (FileBrowserModePrivateData *)mode_get_private_data(sw);
/** /**
* Get the entries to display. * Get the entries to display.
* this gets called on plugin initialization. * this gets called on plugin initialization.
@@ -224,7 +206,8 @@ static void get_file_browser ( Mode *sw )
struct dirent *rd = NULL; struct dirent *rd = NULL;
while ((rd = readdir(dir)) != NULL) { while ((rd = readdir(dir)) != NULL) {
if (g_strcmp0(rd->d_name, "..") == 0) { if (g_strcmp0(rd->d_name, "..") == 0) {
pd->array = g_realloc ( pd->array, ( pd->array_length + 1 ) * sizeof ( FBFile ) ); pd->array =
g_realloc(pd->array, (pd->array_length + 1) * sizeof(FBFile));
// Rofi expects utf-8, so lets convert the filename. // Rofi expects utf-8, so lets convert the filename.
pd->array[pd->array_length].name = g_strdup(".."); pd->array[pd->array_length].name = g_strdup("..");
pd->array[pd->array_length].path = NULL; pd->array[pd->array_length].path = NULL;
@@ -235,12 +218,11 @@ static void get_file_browser ( Mode *sw )
pd->array_length++; pd->array_length++;
continue; continue;
} }
else if ( rd->d_name[0] == '.' ) { if (rd->d_name[0] == '.') {
continue; continue;
} }
switch ( rd->d_type ) switch (rd->d_type) {
{
case DT_BLK: case DT_BLK:
case DT_CHR: case DT_CHR:
case DT_FIFO: case DT_FIFO:
@@ -250,11 +232,15 @@ static void get_file_browser ( Mode *sw )
break; break;
case DT_REG: case DT_REG:
case DT_DIR: case DT_DIR:
pd->array = g_realloc ( pd->array, ( pd->array_length + 1 ) * sizeof ( FBFile ) ); pd->array =
g_realloc(pd->array, (pd->array_length + 1) * sizeof(FBFile));
// Rofi expects utf-8, so lets convert the filename. // Rofi expects utf-8, so lets convert the filename.
pd->array[pd->array_length].name = g_filename_to_utf8 ( rd->d_name, -1, NULL, NULL, NULL ); pd->array[pd->array_length].name =
pd->array[pd->array_length].path = g_build_filename ( cdir, rd->d_name, NULL ); g_filename_to_utf8(rd->d_name, -1, NULL, NULL, NULL);
pd->array[pd->array_length].type = ( rd->d_type == DT_DIR ) ? DIRECTORY : RFILE; pd->array[pd->array_length].path =
g_build_filename(cdir, rd->d_name, NULL);
pd->array[pd->array_length].type =
(rd->d_type == DT_DIR) ? DIRECTORY : RFILE;
pd->array[pd->array_length].icon_fetch_uid = 0; pd->array[pd->array_length].icon_fetch_uid = 0;
pd->array[pd->array_length].link = FALSE; pd->array[pd->array_length].link = FALSE;
@@ -265,34 +251,37 @@ static void get_file_browser ( Mode *sw )
pd->array_length++; pd->array_length++;
break; break;
case DT_LNK: case DT_LNK:
pd->array = g_realloc ( pd->array, ( pd->array_length + 1 ) * sizeof ( FBFile ) ); pd->array =
g_realloc(pd->array, (pd->array_length + 1) * sizeof(FBFile));
// Rofi expects utf-8, so lets convert the filename. // Rofi expects utf-8, so lets convert the filename.
pd->array[pd->array_length].name = g_filename_to_utf8 ( rd->d_name, -1, NULL, NULL, NULL ); pd->array[pd->array_length].name =
pd->array[pd->array_length].path = g_build_filename ( cdir, rd->d_name, NULL ); g_filename_to_utf8(rd->d_name, -1, NULL, NULL, NULL);
pd->array[pd->array_length].path =
g_build_filename(cdir, rd->d_name, NULL);
pd->array[pd->array_length].icon_fetch_uid = 0; pd->array[pd->array_length].icon_fetch_uid = 0;
pd->array[pd->array_length].link = TRUE; pd->array[pd->array_length].link = TRUE;
// Default to file. // Default to file.
pd->array[pd->array_length].type = RFILE; pd->array[pd->array_length].type = RFILE;
{ {
// If we have link, use a stat to fine out what it is, if we fail, we mark it as file. // If we have link, use a stat to fine out what it is, if we fail, we
// mark it as file.
// TODO have a 'broken link' mode? // TODO have a 'broken link' mode?
// Convert full path to right encoding. // Convert full path to right encoding.
char *file = g_filename_from_utf8 ( pd->array[pd->array_length].path, -1, NULL, NULL, NULL ); char *file = g_filename_from_utf8(pd->array[pd->array_length].path,
-1, NULL, NULL, NULL);
if (file) { if (file) {
struct stat statbuf; struct stat statbuf;
if (stat(file, &statbuf) == 0) { if (stat(file, &statbuf) == 0) {
if (S_ISDIR(statbuf.st_mode)) { if (S_ISDIR(statbuf.st_mode)) {
pd->array[pd->array_length].type = DIRECTORY; pd->array[pd->array_length].type = DIRECTORY;
} } else if (S_ISREG(statbuf.st_mode)) {
else if ( S_ISREG ( statbuf.st_mode ) ) {
pd->array[pd->array_length].type = RFILE; pd->array[pd->array_length].type = RFILE;
} }
if (file_browser_config.sorting_method == FB_SORT_TIME) { if (file_browser_config.sorting_method == FB_SORT_TIME) {
pd->array[pd->array_length].time = get_time(&statbuf); pd->array[pd->array_length].time = get_time(&statbuf);
} }
} } else {
else {
g_warning("Failed to stat file: %s, %s", file, strerror(errno)); g_warning("Failed to stat file: %s, %s", file, strerror(errno));
} }
@@ -308,8 +297,7 @@ static void get_file_browser ( Mode *sw )
g_qsort_with_data(pd->array, pd->array_length, sizeof(FBFile), compare, NULL); g_qsort_with_data(pd->array, pd->array_length, sizeof(FBFile), compare, NULL);
} }
static void file_browser_mode_init_config ( Mode *sw ) static void file_browser_mode_init_config(Mode *sw) {
{
char *msg = NULL; char *msg = NULL;
gboolean found_error = FALSE; gboolean found_error = FALSE;
@@ -319,23 +307,20 @@ static void file_browser_mode_init_config ( Mode *sw )
if (p != NULL && p->type == P_STRING) { if (p != NULL && p->type == P_STRING) {
if (g_strcmp0(p->value.s, "name") == 0) { if (g_strcmp0(p->value.s, "name") == 0) {
file_browser_config.sorting_method = FB_SORT_NAME; file_browser_config.sorting_method = FB_SORT_NAME;
} } else if (g_strcmp0(p->value.s, "mtime") == 0) {
else if ( g_strcmp0 ( p->value.s, "mtime" ) == 0 ) {
file_browser_config.sorting_method = FB_SORT_TIME; file_browser_config.sorting_method = FB_SORT_TIME;
file_browser_config.sorting_time = FB_MTIME; file_browser_config.sorting_time = FB_MTIME;
} } else if (g_strcmp0(p->value.s, "atime") == 0) {
else if ( g_strcmp0 ( p->value.s, "atime" ) == 0 ) {
file_browser_config.sorting_method = FB_SORT_TIME; file_browser_config.sorting_method = FB_SORT_TIME;
file_browser_config.sorting_time = FB_ATIME; file_browser_config.sorting_time = FB_ATIME;
} } else if (g_strcmp0(p->value.s, "ctime") == 0) {
else if ( g_strcmp0 ( p->value.s, "ctime" ) == 0 ) {
file_browser_config.sorting_method = FB_SORT_TIME; file_browser_config.sorting_method = FB_SORT_TIME;
file_browser_config.sorting_time = FB_CTIME; file_browser_config.sorting_time = FB_CTIME;
} } else {
else {
found_error = TRUE; found_error = TRUE;
msg = g_strdup_printf ( "\"%s\" is not a valid filebrowser sorting method", p->value.s ); msg = g_strdup_printf("\"%s\" is not a valid filebrowser sorting method",
p->value.s);
} }
} }
@@ -352,20 +337,22 @@ static void file_browser_mode_init_config ( Mode *sw )
} }
static void file_browser_mode_init_current_dir(Mode *sw) { static void file_browser_mode_init_current_dir(Mode *sw) {
FileBrowserModePrivateData *pd = (FileBrowserModePrivateData *) mode_get_private_data ( sw ); FileBrowserModePrivateData *pd =
(FileBrowserModePrivateData *)mode_get_private_data(sw);
ThemeWidget *wid = rofi_config_find_widget(sw->name, NULL, TRUE); ThemeWidget *wid = rofi_config_find_widget(sw->name, NULL, TRUE);
Property *p = rofi_theme_find_property(wid, P_STRING, "directory", TRUE); Property *p = rofi_theme_find_property(wid, P_STRING, "directory", TRUE);
gboolean config_has_valid_dir = p != NULL && p->type == P_STRING gboolean config_has_valid_dir = p != NULL && p->type == P_STRING &&
&& g_file_test ( p->value.s, G_FILE_TEST_IS_DIR ); g_file_test(p->value.s, G_FILE_TEST_IS_DIR);
if (config_has_valid_dir) { if (config_has_valid_dir) {
pd->current_dir = g_file_new_for_path(p->value.s); pd->current_dir = g_file_new_for_path(p->value.s);
} else { } else {
char *current_dir = NULL; char *current_dir = NULL;
char *cache_file = g_build_filename ( cache_dir, FILEBROWSER_CACHE_FILE, NULL ); char *cache_file =
g_build_filename(cache_dir, FILEBROWSER_CACHE_FILE, NULL);
if (g_file_get_contents(cache_file, &current_dir, NULL, NULL)) { if (g_file_get_contents(cache_file, &current_dir, NULL, NULL)) {
if (g_file_test(current_dir, G_FILE_TEST_IS_DIR)) { if (g_file_test(current_dir, G_FILE_TEST_IS_DIR)) {
@@ -379,14 +366,12 @@ static void file_browser_mode_init_current_dir ( Mode *sw ) {
g_free(cache_file); g_free(cache_file);
} }
if (pd->current_dir == NULL) { if (pd->current_dir == NULL) {
pd->current_dir = g_file_new_for_path(g_get_home_dir()); pd->current_dir = g_file_new_for_path(g_get_home_dir());
} }
} }
static int file_browser_mode_init ( Mode *sw ) static int file_browser_mode_init(Mode *sw) {
{
/** /**
* Called on startup when enabled (in modi list) * Called on startup when enabled (in modi list)
*/ */
@@ -402,29 +387,26 @@ static int file_browser_mode_init ( Mode *sw )
} }
return TRUE; return TRUE;
} }
static unsigned int file_browser_mode_get_num_entries ( const Mode *sw ) static unsigned int file_browser_mode_get_num_entries(const Mode *sw) {
{ const FileBrowserModePrivateData *pd =
const FileBrowserModePrivateData *pd = (const FileBrowserModePrivateData *) mode_get_private_data ( sw ); (const FileBrowserModePrivateData *)mode_get_private_data(sw);
return pd->array_length; return pd->array_length;
} }
static ModeMode file_browser_mode_result ( Mode *sw, int mretv, char **input, unsigned int selected_line ) static ModeMode file_browser_mode_result(Mode *sw, int mretv, char **input,
{ unsigned int selected_line) {
ModeMode retv = MODE_EXIT; ModeMode retv = MODE_EXIT;
FileBrowserModePrivateData *pd = (FileBrowserModePrivateData *) mode_get_private_data ( sw ); FileBrowserModePrivateData *pd =
(FileBrowserModePrivateData *)mode_get_private_data(sw);
if (mretv & MENU_NEXT) { if (mretv & MENU_NEXT) {
retv = NEXT_DIALOG; retv = NEXT_DIALOG;
} } else if (mretv & MENU_PREVIOUS) {
else if ( mretv & MENU_PREVIOUS ) {
retv = PREVIOUS_DIALOG; retv = PREVIOUS_DIALOG;
} } else if (mretv & MENU_QUICK_SWITCH) {
else if ( mretv & MENU_QUICK_SWITCH ) {
retv = (mretv & MENU_LOWER_MASK); retv = (mretv & MENU_LOWER_MASK);
} } else if (mretv & MENU_CUSTOM_COMMAND) {
else if ( mretv & MENU_CUSTOM_COMMAND ) {
retv = (mretv & MENU_LOWER_MASK); retv = (mretv & MENU_LOWER_MASK);
} } else if ((mretv & MENU_OK)) {
else if ( ( mretv & MENU_OK ) ) {
if (selected_line < pd->array_length) { if (selected_line < pd->array_length) {
if (pd->array[selected_line].type == UP) { if (pd->array[selected_line].type == UP) {
GFile *new = g_file_get_parent(pd->current_dir); GFile *new = g_file_get_parent(pd->current_dir);
@@ -435,8 +417,7 @@ static ModeMode file_browser_mode_result ( Mode *sw, int mretv, char **input, un
get_file_browser(sw); get_file_browser(sw);
return RESET_DIALOG; return RESET_DIALOG;
} }
} } else if (pd->array[selected_line].type == DIRECTORY) {
else if ( pd->array[selected_line].type == DIRECTORY ) {
char *path = g_build_filename(cache_dir, FILEBROWSER_CACHE_FILE, NULL); char *path = g_build_filename(cache_dir, FILEBROWSER_CACHE_FILE, NULL);
g_file_set_contents(path, pd->array[selected_line].path, -1, NULL); g_file_set_contents(path, pd->array[selected_line].path, -1, NULL);
g_free(path); g_free(path);
@@ -446,9 +427,9 @@ static ModeMode file_browser_mode_result ( Mode *sw, int mretv, char **input, un
free_list(pd); free_list(pd);
get_file_browser(sw); get_file_browser(sw);
return RESET_DIALOG; return RESET_DIALOG;
} } else if (pd->array[selected_line].type == RFILE) {
else if ( pd->array[selected_line].type == RFILE ) { char *d = g_filename_from_utf8(pd->array[selected_line].path, -1, NULL,
char *d = g_filename_from_utf8 ( pd->array[selected_line].path, -1, NULL, NULL, NULL ); NULL, NULL);
char *d_esc = g_shell_quote(d); char *d_esc = g_shell_quote(d);
char *cmd = g_strdup_printf("xdg-open %s", d_esc); char *cmd = g_strdup_printf("xdg-open %s", d_esc);
g_free(d_esc); g_free(d_esc);
@@ -461,8 +442,7 @@ static ModeMode file_browser_mode_result ( Mode *sw, int mretv, char **input, un
} }
} }
retv = RELOAD_DIALOG; retv = RELOAD_DIALOG;
} } else if ((mretv & MENU_CUSTOM_INPUT) && *input) {
else if ( ( mretv & MENU_CUSTOM_INPUT ) && *input ) {
char *p = rofi_expand_path(*input); char *p = rofi_expand_path(*input);
char *dir = g_filename_from_utf8(p, -1, NULL, NULL, NULL); char *dir = g_filename_from_utf8(p, -1, NULL, NULL, NULL);
g_free(p); g_free(p);
@@ -478,16 +458,15 @@ static ModeMode file_browser_mode_result ( Mode *sw, int mretv, char **input, un
} }
g_free(dir); g_free(dir);
retv = RELOAD_DIALOG; retv = RELOAD_DIALOG;
} } else if ((mretv & MENU_ENTRY_DELETE) == MENU_ENTRY_DELETE) {
else if ( ( mretv & MENU_ENTRY_DELETE ) == MENU_ENTRY_DELETE ) {
retv = RELOAD_DIALOG; retv = RELOAD_DIALOG;
} }
return retv; return retv;
} }
static void file_browser_mode_destroy ( Mode *sw ) static void file_browser_mode_destroy(Mode *sw) {
{ FileBrowserModePrivateData *pd =
FileBrowserModePrivateData *pd = (FileBrowserModePrivateData *) mode_get_private_data ( sw ); (FileBrowserModePrivateData *)mode_get_private_data(sw);
if (pd != NULL) { if (pd != NULL) {
g_object_unref(pd->current_dir); g_object_unref(pd->current_dir);
free_list(pd); free_list(pd);
@@ -496,9 +475,12 @@ static void file_browser_mode_destroy ( Mode *sw )
} }
} }
static char *_get_display_value ( const Mode *sw, unsigned int selected_line, G_GNUC_UNUSED int *state, G_GNUC_UNUSED GList **attr_list, int get_entry ) static char *_get_display_value(const Mode *sw, unsigned int selected_line,
{ G_GNUC_UNUSED int *state,
FileBrowserModePrivateData *pd = (FileBrowserModePrivateData *) mode_get_private_data ( sw ); G_GNUC_UNUSED GList **attr_list,
int get_entry) {
FileBrowserModePrivateData *pd =
(FileBrowserModePrivateData *)mode_get_private_data(sw);
// Only return the string if requested, otherwise only set state. // Only return the string if requested, otherwise only set state.
if (!get_entry) { if (!get_entry) {
@@ -507,16 +489,11 @@ static char *_get_display_value ( const Mode *sw, unsigned int selected_line, G_
if (pd->array[selected_line].type == UP) { if (pd->array[selected_line].type == UP) {
return g_strdup(" .."); return g_strdup(" ..");
} }
else {
if (pd->array[selected_line].link) { if (pd->array[selected_line].link) {
return g_strconcat("@", pd->array[selected_line].name, NULL); return g_strconcat("@", pd->array[selected_line].name, NULL);
} }
else {
return g_strdup(pd->array[selected_line].name); return g_strdup(pd->array[selected_line].name);
} }
}
return g_strdup ( "n/a" );
}
/** /**
* @param sw The mode object. * @param sw The mode object.
@@ -527,17 +504,19 @@ static char *_get_display_value ( const Mode *sw, unsigned int selected_line, G_
* *
* @returns try when a match. * @returns try when a match.
*/ */
static int file_browser_token_match ( const Mode *sw, rofi_int_matcher **tokens, unsigned int index ) static int file_browser_token_match(const Mode *sw, rofi_int_matcher **tokens,
{ unsigned int index) {
FileBrowserModePrivateData *pd = (FileBrowserModePrivateData *) mode_get_private_data ( sw ); FileBrowserModePrivateData *pd =
(FileBrowserModePrivateData *)mode_get_private_data(sw);
// Call default matching function. // Call default matching function.
return helper_token_match(tokens, pd->array[index].name); return helper_token_match(tokens, pd->array[index].name);
} }
static cairo_surface_t *_get_icon ( const Mode *sw, unsigned int selected_line, int height ) static cairo_surface_t *_get_icon(const Mode *sw, unsigned int selected_line,
{ int height) {
FileBrowserModePrivateData *pd = (FileBrowserModePrivateData *) mode_get_private_data ( sw ); FileBrowserModePrivateData *pd =
(FileBrowserModePrivateData *)mode_get_private_data(sw);
g_return_val_if_fail(pd->array != NULL, NULL); g_return_val_if_fail(pd->array != NULL, NULL);
FBFile *dr = &(pd->array[selected_line]); FBFile *dr = &(pd->array[selected_line]);
if (dr->icon_fetch_uid > 0) { if (dr->icon_fetch_uid > 0) {
@@ -545,35 +524,34 @@ static cairo_surface_t *_get_icon ( const Mode *sw, unsigned int selected_line,
} }
if (rofi_icon_fetcher_file_is_image(dr->path)) { if (rofi_icon_fetcher_file_is_image(dr->path)) {
dr->icon_fetch_uid = rofi_icon_fetcher_query(dr->path, height); dr->icon_fetch_uid = rofi_icon_fetcher_query(dr->path, height);
} } else {
else {
dr->icon_fetch_uid = rofi_icon_fetcher_query(icon_name[dr->type], height); dr->icon_fetch_uid = rofi_icon_fetcher_query(icon_name[dr->type], height);
} }
return rofi_icon_fetcher_get(dr->icon_fetch_uid); return rofi_icon_fetcher_get(dr->icon_fetch_uid);
} }
static char * _get_message ( const Mode *sw ) static char *_get_message(const Mode *sw) {
{ FileBrowserModePrivateData *pd =
FileBrowserModePrivateData *pd = (FileBrowserModePrivateData *) mode_get_private_data ( sw ); (FileBrowserModePrivateData *)mode_get_private_data(sw);
if (pd->current_dir) { if (pd->current_dir) {
char *dirname = g_file_get_parse_name(pd->current_dir); char *dirname = g_file_get_parse_name(pd->current_dir);
char *str = g_markup_printf_escaped ( "<b>Current directory:</b> %s", dirname ); char *str =
g_markup_printf_escaped("<b>Current directory:</b> %s", dirname);
g_free(dirname); g_free(dirname);
return str; return str;
} }
return "n/a"; return "n/a";
} }
static char *_get_completion ( const Mode *sw, unsigned int index ) static char *_get_completion(const Mode *sw, unsigned int index) {
{ FileBrowserModePrivateData *pd =
FileBrowserModePrivateData *pd = (FileBrowserModePrivateData *) mode_get_private_data ( sw ); (FileBrowserModePrivateData *)mode_get_private_data(sw);
char *d = g_strescape(pd->array[index].path, NULL); char *d = g_strescape(pd->array[index].path, NULL);
return d; return d;
} }
Mode *create_new_file_browser ( void ) Mode *create_new_file_browser(void) {
{
Mode *sw = g_malloc0(sizeof(Mode)); Mode *sw = g_malloc0(sizeof(Mode));
*sw = file_browser_mode; *sw = file_browser_mode;
@@ -583,20 +561,18 @@ Mode *create_new_file_browser ( void )
} }
#if 1 #if 1
ModeMode file_browser_mode_completer ( Mode *sw, int mretv, char **input, unsigned int selected_line, char **path ) ModeMode file_browser_mode_completer(Mode *sw, int mretv, char **input,
{ unsigned int selected_line, char **path) {
ModeMode retv = MODE_EXIT; ModeMode retv = MODE_EXIT;
FileBrowserModePrivateData *pd = (FileBrowserModePrivateData *) mode_get_private_data ( sw ); FileBrowserModePrivateData *pd =
(FileBrowserModePrivateData *)mode_get_private_data(sw);
if (mretv & MENU_NEXT) { if (mretv & MENU_NEXT) {
retv = NEXT_DIALOG; retv = NEXT_DIALOG;
} } else if (mretv & MENU_PREVIOUS) {
else if ( mretv & MENU_PREVIOUS ) {
retv = PREVIOUS_DIALOG; retv = PREVIOUS_DIALOG;
} } else if (mretv & MENU_QUICK_SWITCH) {
else if ( mretv & MENU_QUICK_SWITCH ) {
retv = (mretv & MENU_LOWER_MASK); retv = (mretv & MENU_LOWER_MASK);
} } else if ((mretv & MENU_OK)) {
else if ( ( mretv & MENU_OK ) ) {
if (selected_line < pd->array_length) { if (selected_line < pd->array_length) {
if (pd->array[selected_line].type == UP) { if (pd->array[selected_line].type == UP) {
GFile *new = g_file_get_parent(pd->current_dir); GFile *new = g_file_get_parent(pd->current_dir);
@@ -607,23 +583,20 @@ ModeMode file_browser_mode_completer ( Mode *sw, int mretv, char **input, unsign
get_file_browser(sw); get_file_browser(sw);
return RESET_DIALOG; return RESET_DIALOG;
} }
} } else if (pd->array[selected_line].type == DIRECTORY) {
else if ( pd->array[selected_line].type == DIRECTORY ) {
GFile *new = g_file_new_for_path(pd->array[selected_line].path); GFile *new = g_file_new_for_path(pd->array[selected_line].path);
g_object_unref(pd->current_dir); g_object_unref(pd->current_dir);
pd->current_dir = new; pd->current_dir = new;
free_list(pd); free_list(pd);
get_file_browser(sw); get_file_browser(sw);
return RESET_DIALOG; return RESET_DIALOG;
} } else if (pd->array[selected_line].type == RFILE) {
else if ( pd->array[selected_line].type == RFILE ) {
*path = g_strescape(pd->array[selected_line].path, NULL); *path = g_strescape(pd->array[selected_line].path, NULL);
return MODE_EXIT; return MODE_EXIT;
} }
} }
retv = RELOAD_DIALOG; retv = RELOAD_DIALOG;
} } else if ((mretv & MENU_CUSTOM_INPUT) && *input) {
else if ( ( mretv & MENU_CUSTOM_INPUT ) && *input ) {
char *p = rofi_expand_path(*input); char *p = rofi_expand_path(*input);
char *dir = g_filename_from_utf8(p, -1, NULL, NULL, NULL); char *dir = g_filename_from_utf8(p, -1, NULL, NULL, NULL);
g_free(p); g_free(p);
@@ -639,16 +612,14 @@ ModeMode file_browser_mode_completer ( Mode *sw, int mretv, char **input, unsign
} }
g_free(dir); g_free(dir);
retv = RELOAD_DIALOG; retv = RELOAD_DIALOG;
} } else if ((mretv & MENU_ENTRY_DELETE) == MENU_ENTRY_DELETE) {
else if ( ( mretv & MENU_ENTRY_DELETE ) == MENU_ENTRY_DELETE ) {
retv = RELOAD_DIALOG; retv = RELOAD_DIALOG;
} }
return retv; return retv;
} }
#endif #endif
Mode file_browser_mode = Mode file_browser_mode = {
{
.display_name = NULL, .display_name = NULL,
.abi_version = ABI_VERSION, .abi_version = ABI_VERSION,
.name = "filebrowser", .name = "filebrowser",

View File

@@ -26,38 +26,35 @@
*/ */
#include <config.h> #include <config.h>
#include <stdlib.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h>
#include <unistd.h> #include <dirent.h>
#include <errno.h>
#include <limits.h> #include <limits.h>
#include <signal.h> #include <signal.h>
#include <sys/types.h>
#include <dirent.h>
#include <strings.h>
#include <string.h> #include <string.h>
#include <errno.h> #include <strings.h>
#include <sys/types.h>
#include <unistd.h>
#include "dialogs/help-keys.h"
#include "helper.h"
#include "rofi.h" #include "rofi.h"
#include "settings.h" #include "settings.h"
#include "helper.h"
#include "xrmoptions.h"
#include "dialogs/help-keys.h"
#include "widgets/textbox.h" #include "widgets/textbox.h"
#include "xrmoptions.h"
typedef struct typedef struct {
{
char **messages; char **messages;
unsigned int messages_length; unsigned int messages_length;
} KeysHelpModePrivateData; } KeysHelpModePrivateData;
static void get_apps ( KeysHelpModePrivateData *pd ) static void get_apps(KeysHelpModePrivateData *pd) {
{
pd->messages = config_parser_return_display_help(&(pd->messages_length)); pd->messages = config_parser_return_display_help(&(pd->messages_length));
} }
static int help_keys_mode_init ( Mode *sw ) static int help_keys_mode_init(Mode *sw) {
{
if (mode_get_private_data(sw) == NULL) { if (mode_get_private_data(sw) == NULL) {
KeysHelpModePrivateData *pd = g_malloc0(sizeof(*pd)); KeysHelpModePrivateData *pd = g_malloc0(sizeof(*pd));
mode_set_private_data(sw, (void *)pd); mode_set_private_data(sw, (void *)pd);
@@ -66,20 +63,19 @@ static int help_keys_mode_init ( Mode *sw )
return TRUE; return TRUE;
} }
static ModeMode help_keys_mode_result ( G_GNUC_UNUSED Mode *sw, static ModeMode
int mretv, help_keys_mode_result(G_GNUC_UNUSED Mode *sw, int mretv,
G_GNUC_UNUSED char **input, G_GNUC_UNUSED char **input,
G_GNUC_UNUSED unsigned int selected_line ) G_GNUC_UNUSED unsigned int selected_line) {
{
if (mretv & MENU_CUSTOM_COMMAND) { if (mretv & MENU_CUSTOM_COMMAND) {
int retv = (mretv & MENU_LOWER_MASK); int retv = (mretv & MENU_LOWER_MASK);
return retv; return retv;
} }
return MODE_EXIT; return MODE_EXIT;
} }
static void help_keys_mode_destroy ( Mode *sw ) static void help_keys_mode_destroy(Mode *sw) {
{ KeysHelpModePrivateData *rmpd =
KeysHelpModePrivateData *rmpd = (KeysHelpModePrivateData *) mode_get_private_data ( sw ); (KeysHelpModePrivateData *)mode_get_private_data(sw);
if (rmpd != NULL) { if (rmpd != NULL) {
g_strfreev(rmpd->messages); g_strfreev(rmpd->messages);
g_free(rmpd); g_free(rmpd);
@@ -87,34 +83,32 @@ static void help_keys_mode_destroy ( Mode *sw )
} }
} }
static char *_get_display_value ( const Mode *sw, unsigned int selected_line, int *state, G_GNUC_UNUSED GList **list, int get_entry ) static char *_get_display_value(const Mode *sw, unsigned int selected_line,
{ int *state, G_GNUC_UNUSED GList **list,
KeysHelpModePrivateData *pd = (KeysHelpModePrivateData *) mode_get_private_data ( sw ); int get_entry) {
KeysHelpModePrivateData *pd =
(KeysHelpModePrivateData *)mode_get_private_data(sw);
*state |= MARKUP; *state |= MARKUP;
if (!get_entry) { if (!get_entry) {
return NULL; return NULL;
} }
return g_strdup(pd->messages[selected_line]); return g_strdup(pd->messages[selected_line]);
} }
static int help_keys_token_match ( const Mode *data, static int help_keys_token_match(const Mode *data, rofi_int_matcher **tokens,
rofi_int_matcher **tokens, unsigned int index) {
unsigned int index KeysHelpModePrivateData *rmpd =
) (KeysHelpModePrivateData *)mode_get_private_data(data);
{
KeysHelpModePrivateData *rmpd = (KeysHelpModePrivateData *) mode_get_private_data ( data );
return helper_token_match(tokens, rmpd->messages[index]); return helper_token_match(tokens, rmpd->messages[index]);
} }
static unsigned int help_keys_mode_get_num_entries ( const Mode *sw ) static unsigned int help_keys_mode_get_num_entries(const Mode *sw) {
{ const KeysHelpModePrivateData *pd =
const KeysHelpModePrivateData *pd = (const KeysHelpModePrivateData *) mode_get_private_data ( sw ); (const KeysHelpModePrivateData *)mode_get_private_data(sw);
return pd->messages_length; return pd->messages_length;
} }
#include "mode-private.h" #include "mode-private.h"
Mode help_keys_mode = Mode help_keys_mode = {.name = "keys",
{
.name = "keys",
.cfg_name_key = "display-keys", .cfg_name_key = "display-keys",
._init = help_keys_mode_init, ._init = help_keys_mode_init,
._get_num_entries = help_keys_mode_get_num_entries, ._get_num_entries = help_keys_mode_get_num_entries,
@@ -124,5 +118,4 @@ Mode help_keys_mode =
._get_completion = NULL, ._get_completion = NULL,
._get_display_value = _get_display_value, ._get_display_value = _get_display_value,
.private_data = NULL, .private_data = NULL,
.free = NULL .free = NULL};
};

View File

@@ -34,36 +34,35 @@
#define G_LOG_DOMAIN "Dialogs.Run" #define G_LOG_DOMAIN "Dialogs.Run"
#include <config.h> #include <config.h>
#include <stdlib.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h>
#include <unistd.h> #include <dirent.h>
#include <errno.h>
#include <limits.h> #include <limits.h>
#include <signal.h> #include <signal.h>
#include <sys/types.h>
#include <dirent.h>
#include <strings.h>
#include <string.h> #include <string.h>
#include <errno.h> #include <strings.h>
#include <sys/types.h>
#include <unistd.h>
#include "rofi.h" #include "dialogs/filebrowser.h"
#include "settings.h" #include "dialogs/run.h"
#include "helper.h" #include "helper.h"
#include "history.h" #include "history.h"
#include "dialogs/run.h" #include "rofi.h"
#include "dialogs/filebrowser.h" #include "settings.h"
#include "mode-private.h" #include "mode-private.h"
#include "timings.h"
#include "rofi-icon-fetcher.h" #include "rofi-icon-fetcher.h"
#include "timings.h"
/** /**
* Name of the history file where previously chosen commands are stored. * Name of the history file where previously chosen commands are stored.
*/ */
#define RUN_CACHE_FILE "rofi-3.runcache" #define RUN_CACHE_FILE "rofi-3.runcache"
typedef struct typedef struct {
{
char *entry; char *entry;
uint32_t icon_fetch_uid; uint32_t icon_fetch_uid;
/* Surface holding the icon. */ /* Surface holding the icon. */
@@ -73,8 +72,7 @@ typedef struct
/** /**
* The internal data structure holding the private data of the Run Mode. * The internal data structure holding the private data of the Run Mode.
*/ */
typedef struct typedef struct {
{
/** list of available commands. */ /** list of available commands. */
RunEntry *cmd_list; RunEntry *cmd_list;
/** Length of the #cmd_list. */ /** Length of the #cmd_list. */
@@ -98,8 +96,7 @@ typedef struct
* *
* Execute command and add to history. * Execute command and add to history.
*/ */
static gboolean exec_cmd ( const char *cmd, int run_in_term ) static gboolean exec_cmd(const char *cmd, int run_in_term) {
{
GError *error = NULL; GError *error = NULL;
if (!cmd || !cmd[0]) { if (!cmd || !cmd[0]) {
return FALSE; return FALSE;
@@ -107,7 +104,8 @@ static gboolean exec_cmd ( const char *cmd, int run_in_term )
gsize lf_cmd_size = 0; gsize lf_cmd_size = 0;
gchar *lf_cmd = g_locale_from_utf8(cmd, -1, NULL, &lf_cmd_size, &error); gchar *lf_cmd = g_locale_from_utf8(cmd, -1, NULL, &lf_cmd_size, &error);
if (error != NULL) { if (error != NULL) {
g_warning ( "Failed to convert command to locale encoding: %s", error->message ); g_warning("Failed to convert command to locale encoding: %s",
error->message);
g_error_free(error); g_error_free(error);
return FALSE; return FALSE;
} }
@@ -115,7 +113,8 @@ static gboolean exec_cmd ( const char *cmd, int run_in_term )
char *path = g_build_filename(cache_dir, RUN_CACHE_FILE, NULL); char *path = g_build_filename(cache_dir, RUN_CACHE_FILE, NULL);
RofiHelperExecuteContext context = {.name = NULL}; RofiHelperExecuteContext context = {.name = NULL};
// FIXME: assume startup notification support for terminals // FIXME: assume startup notification support for terminals
if ( helper_execute_command ( NULL, lf_cmd, run_in_term, run_in_term ? &context : NULL ) ) { if (helper_execute_command(NULL, lf_cmd, run_in_term,
run_in_term ? &context : NULL)) {
/** /**
* This happens in non-critical time (After launching app) * This happens in non-critical time (After launching app)
* It is allowed to be a bit slower. * It is allowed to be a bit slower.
@@ -126,21 +125,18 @@ static gboolean exec_cmd ( const char *cmd, int run_in_term )
g_free(lf_cmd); g_free(lf_cmd);
return TRUE; return TRUE;
} }
else {
history_remove(path, cmd); history_remove(path, cmd);
g_free(path); g_free(path);
g_free(lf_cmd); g_free(lf_cmd);
return FALSE; return FALSE;
} }
}
/** /**
* @param cmd The command to remove from history * @param cmd The command to remove from history
* *
* Remove command from history. * Remove command from history.
*/ */
static void delete_entry ( const RunEntry *cmd ) static void delete_entry(const RunEntry *cmd) {
{
char *path = g_build_filename(cache_dir, RUN_CACHE_FILE, NULL); char *path = g_build_filename(cache_dir, RUN_CACHE_FILE, NULL);
history_remove(path, cmd->entry); history_remove(path, cmd->entry);
@@ -155,20 +151,20 @@ static void delete_entry ( const RunEntry *cmd )
* *
* Function used for sorting. * Function used for sorting.
* *
* @returns returns less then, equal to and greater than zero is a is less than, is a match or greater than b. * @returns returns less then, equal to and greater than zero is a is less than,
* is a match or greater than b.
*/ */
static int sort_func ( const void *a, const void *b, G_GNUC_UNUSED void *data ) static int sort_func(const void *a, const void *b, G_GNUC_UNUSED void *data) {
{
const RunEntry *astr = (const RunEntry *)a; const RunEntry *astr = (const RunEntry *)a;
const RunEntry *bstr = (const RunEntry *)b; const RunEntry *bstr = (const RunEntry *)b;
if (astr->entry == NULL && bstr->entry == NULL) { if (astr->entry == NULL && bstr->entry == NULL) {
return 0; return 0;
} }
else if ( astr->entry == NULL ) { if (astr->entry == NULL) {
return 1; return 1;
} }
else if ( bstr->entry == NULL ) { if (bstr->entry == NULL) {
return -1; return -1;
} }
return g_strcmp0(astr->entry, bstr->entry); return g_strcmp0(astr->entry, bstr->entry);
@@ -177,8 +173,8 @@ static int sort_func ( const void *a, const void *b, G_GNUC_UNUSED void *data )
/** /**
* External spider to get list of executables. * External spider to get list of executables.
*/ */
static RunEntry * get_apps_external ( RunEntry *retv, unsigned int *length, unsigned int num_favorites ) static RunEntry *get_apps_external(RunEntry *retv, unsigned int *length,
{ unsigned int num_favorites) {
int fd = execute_generator(config.run_list_command); int fd = execute_generator(config.run_list_command);
if (fd >= 0) { if (fd >= 0) {
FILE *inp = fdopen(fd, "r"); FILE *inp = fdopen(fd, "r");
@@ -231,8 +227,7 @@ static RunEntry * get_apps_external ( RunEntry *retv, unsigned int *length, unsi
/** /**
* Internal spider used to get list of executables. * Internal spider used to get list of executables.
*/ */
static RunEntry * get_apps ( unsigned int *length ) static RunEntry *get_apps(unsigned int *length) {
{
GError *error = NULL; GError *error = NULL;
RunEntry *retv = NULL; RunEntry *retv = NULL;
unsigned int num_favorites = 0; unsigned int num_favorites = 0;
@@ -270,7 +265,8 @@ static RunEntry * get_apps ( unsigned int *length )
const char *const sep = ":"; const char *const sep = ":";
char *strtok_savepointer = NULL; char *strtok_savepointer = NULL;
for ( const char *dirname = strtok_r ( path, sep, &strtok_savepointer ); dirname != NULL; dirname = strtok_r ( NULL, sep, &strtok_savepointer ) ) { for (const char *dirname = strtok_r(path, sep, &strtok_savepointer);
dirname != NULL; dirname = strtok_r(NULL, sep, &strtok_savepointer)) {
char *fpath = rofi_expand_path(dirname); char *fpath = rofi_expand_path(dirname);
DIR *dir = opendir(fpath); DIR *dir = opendir(fpath);
g_debug("Checking path %s for executable.", fpath); g_debug("Checking path %s for executable.", fpath);
@@ -281,7 +277,8 @@ static RunEntry * get_apps ( unsigned int *length )
gsize dirn_len = 0; gsize dirn_len = 0;
gchar *dirn = g_locale_to_utf8(dirname, -1, NULL, &dirn_len, &error); gchar *dirn = g_locale_to_utf8(dirname, -1, NULL, &dirn_len, &error);
if (error != NULL) { if (error != NULL) {
g_debug ( "Failed to convert directory name to UTF-8: %s", error->message ); g_debug("Failed to convert directory name to UTF-8: %s",
error->message);
g_clear_error(&error); g_clear_error(&error);
closedir(dir); closedir(dir);
continue; continue;
@@ -290,7 +287,8 @@ static RunEntry * get_apps ( unsigned int *length )
g_free(dirn); g_free(dirn);
while ((dent = readdir(dir)) != NULL) { while ((dent = readdir(dir)) != NULL) {
if ( dent->d_type != DT_REG && dent->d_type != DT_LNK && dent->d_type != DT_UNKNOWN ) { if (dent->d_type != DT_REG && dent->d_type != DT_LNK &&
dent->d_type != DT_UNKNOWN) {
continue; continue;
} }
// Skip dot files. // Skip dot files.
@@ -307,7 +305,8 @@ static RunEntry * get_apps ( unsigned int *length )
} }
gsize name_len; gsize name_len;
gchar *name = g_filename_to_utf8 ( dent->d_name, -1, NULL, &name_len, &error ); gchar *name =
g_filename_to_utf8(dent->d_name, -1, NULL, &name_len, &error);
if (error != NULL) { if (error != NULL) {
g_debug("Failed to convert filename to UTF-8: %s", error->message); g_debug("Failed to convert filename to UTF-8: %s", error->message);
g_clear_error(&error); g_clear_error(&error);
@@ -353,7 +352,8 @@ static RunEntry * get_apps ( unsigned int *length )
} }
// TODO: check this is still fast enough. (takes 1ms on laptop.) // TODO: check this is still fast enough. (takes 1ms on laptop.)
if ((*length) > num_favorites) { if ((*length) > num_favorites) {
g_qsort_with_data ( &(retv[num_favorites]), ( *length ) - num_favorites, sizeof ( RunEntry ), sort_func, NULL ); g_qsort_with_data(&(retv[num_favorites]), (*length) - num_favorites,
sizeof(RunEntry), sort_func, NULL);
} }
g_free(path); g_free(path);
@@ -367,9 +367,8 @@ static RunEntry * get_apps ( unsigned int *length )
} }
if ((*length) > num_favorites) { if ((*length) > num_favorites) {
g_qsort_with_data ( &(retv[num_favorites]), ( *length ) - num_favorites, sizeof ( RunEntry ), g_qsort_with_data(&(retv[num_favorites]), (*length) - num_favorites,
sort_func, sizeof(RunEntry), sort_func, NULL);
NULL );
} }
// Reduce array length; // Reduce array length;
(*length) -= removed; (*length) -= removed;
@@ -378,8 +377,7 @@ static RunEntry * get_apps ( unsigned int *length )
return retv; return retv;
} }
static int run_mode_init ( Mode *sw ) static int run_mode_init(Mode *sw) {
{
if (sw->private_data == NULL) { if (sw->private_data == NULL) {
RunModePrivateData *pd = g_malloc0(sizeof(*pd)); RunModePrivateData *pd = g_malloc0(sizeof(*pd));
sw->private_data = (void *)pd; sw->private_data = (void *)pd;
@@ -390,8 +388,7 @@ static int run_mode_init ( Mode *sw )
return TRUE; return TRUE;
} }
static void run_mode_destroy ( Mode *sw ) static void run_mode_destroy(Mode *sw) {
{
RunModePrivateData *rmpd = (RunModePrivateData *)sw->private_data; RunModePrivateData *rmpd = (RunModePrivateData *)sw->private_data;
if (rmpd != NULL) { if (rmpd != NULL) {
for (unsigned int i = 0; i < rmpd->cmd_list_length; i++) { for (unsigned int i = 0; i < rmpd->cmd_list_length; i++) {
@@ -409,8 +406,7 @@ static void run_mode_destroy ( Mode *sw )
} }
} }
static unsigned int run_mode_get_num_entries ( const Mode *sw ) static unsigned int run_mode_get_num_entries(const Mode *sw) {
{
const RunModePrivateData *rmpd = (const RunModePrivateData *)sw->private_data; const RunModePrivateData *rmpd = (const RunModePrivateData *)sw->private_data;
if (rmpd->file_complete) { if (rmpd->file_complete) {
return rmpd->completer->_get_num_entries(rmpd->completer); return rmpd->completer->_get_num_entries(rmpd->completer);
@@ -418,8 +414,8 @@ static unsigned int run_mode_get_num_entries ( const Mode *sw )
return rmpd->cmd_list_length; return rmpd->cmd_list_length;
} }
static ModeMode run_mode_result ( Mode *sw, int mretv, char **input, unsigned int selected_line ) static ModeMode run_mode_result(Mode *sw, int mretv, char **input,
{ unsigned int selected_line) {
RunModePrivateData *rmpd = (RunModePrivateData *)sw->private_data; RunModePrivateData *rmpd = (RunModePrivateData *)sw->private_data;
ModeMode retv = MODE_EXIT; ModeMode retv = MODE_EXIT;
@@ -436,23 +432,21 @@ static ModeMode run_mode_result ( Mode *sw, int mretv, char **input, unsigned in
(*input) = g_strdup(rmpd->old_input); (*input) = g_strdup(rmpd->old_input);
} }
rmpd->file_complete = FALSE; rmpd->file_complete = FALSE;
} } else if ((mretv & MENU_CANCEL)) {
else if ( (mretv&MENU_CANCEL) ) {
retv = MODE_EXIT; retv = MODE_EXIT;
} } else {
else {
char *path = NULL; char *path = NULL;
retv = file_browser_mode_completer ( rmpd->completer, mretv, input, selected_line, &path ); retv = file_browser_mode_completer(rmpd->completer, mretv, input,
selected_line, &path);
if (retv == MODE_EXIT) { if (retv == MODE_EXIT) {
if (path == NULL) { if (path == NULL) {
exec_cmd(rmpd->cmd_list[rmpd->selected_line].entry, run_in_term); exec_cmd(rmpd->cmd_list[rmpd->selected_line].entry, run_in_term);
} } else {
else { char *arg = g_strdup_printf(
char *arg= g_strdup_printf ( "%s '%s'", rmpd->cmd_list[rmpd->selected_line].entry, path); "%s '%s'", rmpd->cmd_list[rmpd->selected_line].entry, path);
exec_cmd(arg, run_in_term); exec_cmd(arg, run_in_term);
g_free(arg); g_free(arg);
} }
} }
g_free(path); g_free(path);
} }
@@ -463,24 +457,22 @@ static ModeMode run_mode_result ( Mode *sw, int mretv, char **input, unsigned in
if (!exec_cmd(rmpd->cmd_list[selected_line].entry, run_in_term)) { if (!exec_cmd(rmpd->cmd_list[selected_line].entry, run_in_term)) {
retv = RELOAD_DIALOG; retv = RELOAD_DIALOG;
} }
} } else if ((mretv & MENU_CUSTOM_INPUT) && *input != NULL &&
else if ( ( mretv & MENU_CUSTOM_INPUT ) && *input != NULL && *input[0] != '\0' ) { *input[0] != '\0') {
if (!exec_cmd(*input, run_in_term)) { if (!exec_cmd(*input, run_in_term)) {
retv = RELOAD_DIALOG; retv = RELOAD_DIALOG;
} }
} } else if ((mretv & MENU_ENTRY_DELETE) &&
else if ( ( mretv & MENU_ENTRY_DELETE ) && rmpd->cmd_list[selected_line].entry ) { rmpd->cmd_list[selected_line].entry) {
delete_entry(&(rmpd->cmd_list[selected_line])); delete_entry(&(rmpd->cmd_list[selected_line]));
// Clear the list. // Clear the list.
retv = RELOAD_DIALOG; retv = RELOAD_DIALOG;
run_mode_destroy(sw); run_mode_destroy(sw);
run_mode_init(sw); run_mode_init(sw);
} } else if (mretv & MENU_CUSTOM_COMMAND) {
else if ( mretv & MENU_CUSTOM_COMMAND ) {
retv = (mretv & MENU_LOWER_MASK); retv = (mretv & MENU_LOWER_MASK);
} } else if ((mretv & MENU_COMPLETE)) {
else if ( ( mretv& MENU_COMPLETE) ) {
retv = RELOAD_DIALOG; retv = RELOAD_DIALOG;
if (selected_line < rmpd->cmd_list_length) { if (selected_line < rmpd->cmd_list_length) {
rmpd->selected_line = selected_line; rmpd->selected_line = selected_line;
@@ -488,7 +480,8 @@ static ModeMode run_mode_result ( Mode *sw, int mretv, char **input, unsigned in
g_free(rmpd->old_input); g_free(rmpd->old_input);
rmpd->old_input = g_strdup(*input); rmpd->old_input = g_strdup(*input);
if ( *input ) g_free (*input); if (*input)
g_free(*input);
*input = g_strdup(rmpd->old_completer_input); *input = g_strdup(rmpd->old_completer_input);
rmpd->file_complete = TRUE; rmpd->file_complete = TRUE;
@@ -497,53 +490,56 @@ static ModeMode run_mode_result ( Mode *sw, int mretv, char **input, unsigned in
return retv; return retv;
} }
static char *_get_display_value ( const Mode *sw, unsigned int selected_line, G_GNUC_UNUSED int *state, G_GNUC_UNUSED GList **list, int get_entry ) static char *_get_display_value(const Mode *sw, unsigned int selected_line,
{ G_GNUC_UNUSED int *state,
G_GNUC_UNUSED GList **list, int get_entry) {
const RunModePrivateData *rmpd = (const RunModePrivateData *)sw->private_data; const RunModePrivateData *rmpd = (const RunModePrivateData *)sw->private_data;
if (rmpd->file_complete) { if (rmpd->file_complete) {
return rmpd->completer->_get_display_value (rmpd->completer, selected_line, state, list, get_entry ); return rmpd->completer->_get_display_value(rmpd->completer, selected_line,
state, list, get_entry);
} }
return get_entry ? g_strdup(rmpd->cmd_list[selected_line].entry) : NULL; return get_entry ? g_strdup(rmpd->cmd_list[selected_line].entry) : NULL;
} }
static int run_token_match ( const Mode *sw, rofi_int_matcher **tokens, unsigned int index ) static int run_token_match(const Mode *sw, rofi_int_matcher **tokens,
{ unsigned int index) {
const RunModePrivateData *rmpd = (const RunModePrivateData *)sw->private_data; const RunModePrivateData *rmpd = (const RunModePrivateData *)sw->private_data;
if (rmpd->file_complete) { if (rmpd->file_complete) {
return rmpd->completer->_token_match(rmpd->completer, tokens, index); return rmpd->completer->_token_match(rmpd->completer, tokens, index);
} }
return helper_token_match(tokens, rmpd->cmd_list[index].entry); return helper_token_match(tokens, rmpd->cmd_list[index].entry);
} }
static char *run_get_message ( const Mode *sw ) static char *run_get_message(const Mode *sw) {
{
RunModePrivateData *pd = sw->private_data; RunModePrivateData *pd = sw->private_data;
if (pd->file_complete) { if (pd->file_complete) {
if (pd->selected_line < pd->cmd_list_length) { if (pd->selected_line < pd->cmd_list_length) {
char *msg = mode_get_message(pd->completer); char *msg = mode_get_message(pd->completer);
if (msg) { if (msg) {
char *retv = g_strdup_printf("File complete for: %s\n%s", pd->cmd_list[pd->selected_line].entry, msg); char *retv =
g_strdup_printf("File complete for: %s\n%s",
pd->cmd_list[pd->selected_line].entry, msg);
g_free(msg); g_free(msg);
return retv; return retv;
} }
return g_strdup_printf("File complete for: %s", pd->cmd_list[pd->selected_line].entry); return g_strdup_printf("File complete for: %s",
pd->cmd_list[pd->selected_line].entry);
} }
} }
return NULL; return NULL;
} }
static cairo_surface_t *fallback_icon ( RunModePrivateData *pd, int height ) static cairo_surface_t *fallback_icon(RunModePrivateData *pd, int height) {
{
if (config.application_fallback_icon) { if (config.application_fallback_icon) {
// FALLBACK // FALLBACK
if (pd->fallback_icon_fetch_uid > 0) { if (pd->fallback_icon_fetch_uid > 0) {
return rofi_icon_fetcher_get(pd->fallback_icon_fetch_uid); return rofi_icon_fetcher_get(pd->fallback_icon_fetch_uid);
} }
pd->fallback_icon_fetch_uid = rofi_icon_fetcher_query ( config.application_fallback_icon, height ); pd->fallback_icon_fetch_uid =
rofi_icon_fetcher_query(config.application_fallback_icon, height);
} }
return NULL; return NULL;
} }
static cairo_surface_t *_get_icon ( const Mode *sw, unsigned int selected_line, int height ) static cairo_surface_t *_get_icon(const Mode *sw, unsigned int selected_line,
{ int height) {
RunModePrivateData *pd = (RunModePrivateData *)mode_get_private_data(sw); RunModePrivateData *pd = (RunModePrivateData *)mode_get_private_data(sw);
if (pd->file_complete) { if (pd->file_complete) {
return pd->completer->_get_icon(pd->completer, selected_line, height); return pd->completer->_get_icon(pd->completer, selected_line, height);
@@ -572,9 +568,7 @@ static cairo_surface_t *_get_icon ( const Mode *sw, unsigned int selected_line,
} }
#include "mode-private.h" #include "mode-private.h"
Mode run_mode = Mode run_mode = {.name = "run",
{
.name = "run",
.cfg_name_key = "display-run", .cfg_name_key = "display-run",
._init = run_mode_init, ._init = run_mode_init,
._get_num_entries = run_mode_get_num_entries, ._get_num_entries = run_mode_get_num_entries,
@@ -587,6 +581,5 @@ Mode run_mode =
._get_completion = NULL, ._get_completion = NULL,
._preprocess_input = NULL, ._preprocess_input = NULL,
.private_data = NULL, .private_data = NULL,
.free = NULL .free = NULL};
};
/** @}*/ /** @}*/

View File

@@ -28,18 +28,17 @@
/** The log domain of this dialog. */ /** The log domain of this dialog. */
#define G_LOG_DOMAIN "Dialogs.Script" #define G_LOG_DOMAIN "Dialogs.Script"
#include <config.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <strings.h>
#include <string.h>
#include <ctype.h>
#include <assert.h>
#include <errno.h>
#include "rofi.h"
#include "dialogs/script.h" #include "dialogs/script.h"
#include "helper.h" #include "helper.h"
#include "rofi.h"
#include <assert.h>
#include <ctype.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <unistd.h>
#include "widgets/textbox.h" #include "widgets/textbox.h"
@@ -49,8 +48,7 @@
#include "dialogs/dmenuscriptshared.h" #include "dialogs/dmenuscriptshared.h"
typedef struct typedef struct {
{
/** ID of the current script. */ /** ID of the current script. */
unsigned int id; unsigned int id;
/** List of visible items. */ /** List of visible items. */
@@ -78,8 +76,9 @@ typedef struct
/** /**
* Shared function between DMENU and Script mode. * Shared function between DMENU and Script mode.
*/ */
void dmenuscript_parse_entry_extras ( G_GNUC_UNUSED Mode *sw, DmenuScriptEntry *entry, char *buffer, G_GNUC_UNUSED size_t length ) void dmenuscript_parse_entry_extras(G_GNUC_UNUSED Mode *sw,
{ DmenuScriptEntry *entry, char *buffer,
G_GNUC_UNUSED size_t length) {
gchar **extras = g_strsplit(buffer, "\x1f", -1); gchar **extras = g_strsplit(buffer, "\x1f", -1);
gchar **extra; gchar **extra;
for (extra = extras; *extra != NULL && *(extra + 1) != NULL; extra += 2) { for (extra = extras; *extra != NULL && *(extra + 1) != NULL; extra += 2) {
@@ -87,18 +86,14 @@ void dmenuscript_parse_entry_extras ( G_GNUC_UNUSED Mode *sw, DmenuScriptEntry *
gchar *value = *(extra + 1); gchar *value = *(extra + 1);
if (strcasecmp(key, "icon") == 0) { if (strcasecmp(key, "icon") == 0) {
entry->icon_name = value; entry->icon_name = value;
} } else if (strcasecmp(key, "meta") == 0) {
else if ( strcasecmp ( key, "meta" ) == 0 ) {
entry->meta = value; entry->meta = value;
} } else if (strcasecmp(key, "info") == 0) {
else if ( strcasecmp ( key, "info" ) == 0 ) {
entry->info = value; entry->info = value;
} } else if (strcasecmp(key, "nonselectable") == 0) {
else if ( strcasecmp ( key, "nonselectable" ) == 0 ) {
entry->nonselectable = strcasecmp(value, "true") == 0; entry->nonselectable = strcasecmp(value, "true") == 0;
g_free(value); g_free(value);
} } else {
else {
g_free(value); g_free(value);
} }
g_free(key); g_free(key);
@@ -110,8 +105,7 @@ void dmenuscript_parse_entry_extras ( G_GNUC_UNUSED Mode *sw, DmenuScriptEntry *
* End of shared functions. * End of shared functions.
*/ */
static void parse_header_entry ( Mode *sw, char *line, ssize_t length ) static void parse_header_entry(Mode *sw, char *line, ssize_t length) {
{
ScriptModePrivateData *pd = (ScriptModePrivateData *)sw->private_data; ScriptModePrivateData *pd = (ScriptModePrivateData *)sw->private_data;
ssize_t length_key = 0; // strlen ( line ); ssize_t length_key = 0; // strlen ( line );
while (length_key < length && line[length_key] != '\x1f') { while (length_key < length && line[length_key] != '\x1f') {
@@ -124,35 +118,29 @@ static void parse_header_entry ( Mode *sw, char *line, ssize_t length )
if (strcasecmp(line, "message") == 0) { if (strcasecmp(line, "message") == 0) {
g_free(pd->message); g_free(pd->message);
pd->message = strlen(value) ? g_strdup(value) : NULL; pd->message = strlen(value) ? g_strdup(value) : NULL;
} } else if (strcasecmp(line, "prompt") == 0) {
else if ( strcasecmp ( line, "prompt" ) == 0 ) {
g_free(pd->prompt); g_free(pd->prompt);
pd->prompt = g_strdup(value); pd->prompt = g_strdup(value);
sw->display_name = pd->prompt; sw->display_name = pd->prompt;
} } else if (strcasecmp(line, "markup-rows") == 0) {
else if ( strcasecmp ( line, "markup-rows" ) == 0 ) {
pd->do_markup = (strcasecmp(value, "true") == 0); pd->do_markup = (strcasecmp(value, "true") == 0);
} } else if (strcasecmp(line, "urgent") == 0) {
else if ( strcasecmp ( line, "urgent" ) == 0 ) {
parse_ranges(value, &(pd->urgent_list), &(pd->num_urgent_list)); parse_ranges(value, &(pd->urgent_list), &(pd->num_urgent_list));
} } else if (strcasecmp(line, "active") == 0) {
else if ( strcasecmp ( line, "active" ) == 0 ) {
parse_ranges(value, &(pd->active_list), &(pd->num_active_list)); parse_ranges(value, &(pd->active_list), &(pd->num_active_list));
} } else if (strcasecmp(line, "delim") == 0) {
else if ( strcasecmp ( line, "delim" ) == 0 ) {
pd->delim = helper_parse_char(value); pd->delim = helper_parse_char(value);
} } else if (strcasecmp(line, "no-custom") == 0) {
else if ( strcasecmp ( line, "no-custom" ) == 0 ) {
pd->no_custom = (strcasecmp(value, "true") == 0); pd->no_custom = (strcasecmp(value, "true") == 0);
} } else if (strcasecmp(line, "use-hot-keys") == 0) {
else if ( strcasecmp ( line, "use-hot-keys" ) == 0 ) {
pd->use_hot_keys = (strcasecmp(value, "true") == 0); pd->use_hot_keys = (strcasecmp(value, "true") == 0);
} }
} }
} }
static DmenuScriptEntry *execute_executor ( Mode *sw, char *arg, unsigned int *length, int value, DmenuScriptEntry *entry ) static DmenuScriptEntry *execute_executor(Mode *sw, char *arg,
{ unsigned int *length, int value,
DmenuScriptEntry *entry) {
ScriptModePrivateData *pd = (ScriptModePrivateData *)sw->private_data; ScriptModePrivateData *pd = (ScriptModePrivateData *)sw->private_data;
int fd = -1; int fd = -1;
GError *error = NULL; GError *error = NULL;
@@ -180,11 +168,13 @@ static DmenuScriptEntry *execute_executor ( Mode *sw, char *arg, unsigned int *l
argv = g_realloc(argv, (argc + 2) * sizeof(char *)); argv = g_realloc(argv, (argc + 2) * sizeof(char *));
argv[argc] = g_strdup(arg); argv[argc] = g_strdup(arg);
argv[argc + 1] = NULL; argv[argc + 1] = NULL;
g_spawn_async_with_pipes ( NULL, argv, env, G_SPAWN_SEARCH_PATH, NULL, NULL, NULL, NULL, &fd, NULL, &error ); g_spawn_async_with_pipes(NULL, argv, env, G_SPAWN_SEARCH_PATH, NULL, NULL,
NULL, NULL, &fd, NULL, &error);
} }
g_strfreev(env); g_strfreev(env);
if (error != NULL) { if (error != NULL) {
char *msg = g_strdup_printf ( "Failed to execute: '%s'\nError: '%s'", (char *) sw->ed, error->message ); char *msg = g_strdup_printf("Failed to execute: '%s'\nError: '%s'",
(char *)sw->ed, error->message);
rofi_view_error_dialog(msg, FALSE); rofi_view_error_dialog(msg, FALSE);
g_free(msg); g_free(msg);
// print error. // print error.
@@ -198,15 +188,15 @@ static DmenuScriptEntry *execute_executor ( Mode *sw, char *arg, unsigned int *l
size_t buffer_length = 0; size_t buffer_length = 0;
ssize_t read_length = 0; ssize_t read_length = 0;
size_t actual_size = 0; size_t actual_size = 0;
while ( ( read_length = getdelim ( &buffer, &buffer_length, pd->delim, inp ) ) > 0 ) { while ((read_length = getdelim(&buffer, &buffer_length, pd->delim, inp)) >
0) {
// Filter out line-end. // Filter out line-end.
if (buffer[read_length - 1] == pd->delim) { if (buffer[read_length - 1] == pd->delim) {
buffer[read_length - 1] = '\0'; buffer[read_length - 1] = '\0';
} }
if (buffer[0] == '\0') { if (buffer[0] == '\0') {
parse_header_entry(sw, &buffer[1], read_length - 1); parse_header_entry(sw, &buffer[1], read_length - 1);
} } else {
else {
if (actual_size < ((*length) + 2)) { if (actual_size < ((*length) + 2)) {
actual_size += 256; actual_size += 256;
retv = g_realloc(retv, (actual_size) * sizeof(DmenuScriptEntry)); retv = g_realloc(retv, (actual_size) * sizeof(DmenuScriptEntry));
@@ -219,7 +209,9 @@ static DmenuScriptEntry *execute_executor ( Mode *sw, char *arg, unsigned int *l
retv[(*length)].icon_fetch_uid = 0; retv[(*length)].icon_fetch_uid = 0;
retv[(*length)].nonselectable = FALSE; retv[(*length)].nonselectable = FALSE;
if (buf_length > 0 && (read_length > (ssize_t)buf_length)) { if (buf_length > 0 && (read_length > (ssize_t)buf_length)) {
dmenuscript_parse_entry_extras ( sw, &( retv[( *length )] ), buffer + buf_length, read_length - buf_length ); dmenuscript_parse_entry_extras(sw, &(retv[(*length)]),
buffer + buf_length,
read_length - buf_length);
} }
retv[(*length) + 1].entry = NULL; retv[(*length) + 1].entry = NULL;
(*length)++; (*length)++;
@@ -238,8 +230,7 @@ static DmenuScriptEntry *execute_executor ( Mode *sw, char *arg, unsigned int *l
return retv; return retv;
} }
static void script_switcher_free ( Mode *sw ) static void script_switcher_free(Mode *sw) {
{
if (sw == NULL) { if (sw == NULL) {
return; return;
} }
@@ -248,8 +239,7 @@ static void script_switcher_free ( Mode *sw )
g_free(sw); g_free(sw);
} }
static int script_mode_init ( Mode *sw ) static int script_mode_init(Mode *sw) {
{
if (sw->private_data == NULL) { if (sw->private_data == NULL) {
ScriptModePrivateData *pd = g_malloc0(sizeof(*pd)); ScriptModePrivateData *pd = g_malloc0(sizeof(*pd));
pd->delim = '\n'; pd->delim = '\n';
@@ -258,14 +248,13 @@ static int script_mode_init ( Mode *sw )
} }
return TRUE; return TRUE;
} }
static unsigned int script_mode_get_num_entries ( const Mode *sw ) static unsigned int script_mode_get_num_entries(const Mode *sw) {
{ const ScriptModePrivateData *rmpd =
const ScriptModePrivateData *rmpd = (const ScriptModePrivateData *) sw->private_data; (const ScriptModePrivateData *)sw->private_data;
return rmpd->cmd_list_length; return rmpd->cmd_list_length;
} }
static void script_mode_reset_highlight ( Mode *sw ) static void script_mode_reset_highlight(Mode *sw) {
{
ScriptModePrivateData *rmpd = (ScriptModePrivateData *)sw->private_data; ScriptModePrivateData *rmpd = (ScriptModePrivateData *)sw->private_data;
rmpd->num_urgent_list = 0; rmpd->num_urgent_list = 0;
@@ -276,8 +265,8 @@ static void script_mode_reset_highlight ( Mode *sw )
rmpd->active_list = NULL; rmpd->active_list = NULL;
} }
static ModeMode script_mode_result ( Mode *sw, int mretv, char **input, unsigned int selected_line ) static ModeMode script_mode_result(Mode *sw, int mretv, char **input,
{ unsigned int selected_line) {
ScriptModePrivateData *rmpd = (ScriptModePrivateData *)sw->private_data; ScriptModePrivateData *rmpd = (ScriptModePrivateData *)sw->private_data;
ModeMode retv = MODE_EXIT; ModeMode retv = MODE_EXIT;
DmenuScriptEntry *new_list = NULL; DmenuScriptEntry *new_list = NULL;
@@ -287,35 +276,35 @@ static ModeMode script_mode_result ( Mode *sw, int mretv, char **input, unsigned
if (rmpd->use_hot_keys) { if (rmpd->use_hot_keys) {
script_mode_reset_highlight(sw); script_mode_reset_highlight(sw);
if (selected_line != UINT32_MAX) { if (selected_line != UINT32_MAX) {
new_list = execute_executor ( sw, rmpd->cmd_list[selected_line].entry, &new_length, 10 + ( mretv & MENU_LOWER_MASK ), &( rmpd->cmd_list[selected_line] ) ); new_list = execute_executor(sw, rmpd->cmd_list[selected_line].entry,
} &new_length, 10 + (mretv & MENU_LOWER_MASK),
else { &(rmpd->cmd_list[selected_line]));
} else {
if (rmpd->no_custom == FALSE) { if (rmpd->no_custom == FALSE) {
new_list = execute_executor ( sw, *input, &new_length, 10 + ( mretv & MENU_LOWER_MASK ), NULL ); new_list = execute_executor(sw, *input, &new_length,
} 10 + (mretv & MENU_LOWER_MASK), NULL);
else { } else {
return RELOAD_DIALOG; return RELOAD_DIALOG;
} }
} }
} } else {
else {
retv = (mretv & MENU_LOWER_MASK); retv = (mretv & MENU_LOWER_MASK);
return retv; return retv;
} }
} } else if ((mretv & MENU_OK) && rmpd->cmd_list[selected_line].entry != NULL) {
else if ( ( mretv & MENU_OK ) && rmpd->cmd_list[selected_line].entry != NULL ) {
if (rmpd->cmd_list[selected_line].nonselectable) { if (rmpd->cmd_list[selected_line].nonselectable) {
return RELOAD_DIALOG; return RELOAD_DIALOG;
} }
script_mode_reset_highlight(sw); script_mode_reset_highlight(sw);
new_list = execute_executor ( sw, rmpd->cmd_list[selected_line].entry, &new_length, 1, &( rmpd->cmd_list[selected_line] ) ); new_list =
} execute_executor(sw, rmpd->cmd_list[selected_line].entry, &new_length,
else if ( ( mretv & MENU_CUSTOM_INPUT ) && *input != NULL && *input[0] != '\0' ) { 1, &(rmpd->cmd_list[selected_line]));
} else if ((mretv & MENU_CUSTOM_INPUT) && *input != NULL &&
*input[0] != '\0') {
if (rmpd->no_custom == FALSE) { if (rmpd->no_custom == FALSE) {
script_mode_reset_highlight(sw); script_mode_reset_highlight(sw);
new_list = execute_executor(sw, *input, &new_length, 2, NULL); new_list = execute_executor(sw, *input, &new_length, 2, NULL);
} } else {
else {
return RELOAD_DIALOG; return RELOAD_DIALOG;
} }
} }
@@ -336,8 +325,7 @@ static ModeMode script_mode_result ( Mode *sw, int mretv, char **input, unsigned
return retv; return retv;
} }
static void script_mode_destroy ( Mode *sw ) static void script_mode_destroy(Mode *sw) {
{
ScriptModePrivateData *rmpd = (ScriptModePrivateData *)sw->private_data; ScriptModePrivateData *rmpd = (ScriptModePrivateData *)sw->private_data;
if (rmpd != NULL) { if (rmpd != NULL) {
for (unsigned int i = 0; i < rmpd->cmd_list_length; i++) { for (unsigned int i = 0; i < rmpd->cmd_list_length; i++) {
@@ -354,8 +342,7 @@ static void script_mode_destroy ( Mode *sw )
sw->private_data = NULL; sw->private_data = NULL;
} }
} }
static inline unsigned int get_index ( unsigned int length, int index ) static inline unsigned int get_index(unsigned int length, int index) {
{
if (index >= 0) { if (index >= 0) {
return index; return index;
} }
@@ -365,18 +352,21 @@ static inline unsigned int get_index ( unsigned int length, int index )
// Out of range. // Out of range.
return UINT_MAX; return UINT_MAX;
} }
static char *_get_display_value ( const Mode *sw, unsigned int selected_line, G_GNUC_UNUSED int *state, G_GNUC_UNUSED GList **list, int get_entry ) static char *_get_display_value(const Mode *sw, unsigned int selected_line,
{ G_GNUC_UNUSED int *state,
G_GNUC_UNUSED GList **list, int get_entry) {
ScriptModePrivateData *pd = sw->private_data; ScriptModePrivateData *pd = sw->private_data;
for (unsigned int i = 0; i < pd->num_active_list; i++) { for (unsigned int i = 0; i < pd->num_active_list; i++) {
unsigned int start = get_index ( pd->cmd_list_length, pd->active_list[i].start ); unsigned int start =
get_index(pd->cmd_list_length, pd->active_list[i].start);
unsigned int stop = get_index(pd->cmd_list_length, pd->active_list[i].stop); unsigned int stop = get_index(pd->cmd_list_length, pd->active_list[i].stop);
if (selected_line >= start && selected_line <= stop) { if (selected_line >= start && selected_line <= stop) {
*state |= ACTIVE; *state |= ACTIVE;
} }
} }
for (unsigned int i = 0; i < pd->num_urgent_list; i++) { for (unsigned int i = 0; i < pd->num_urgent_list; i++) {
unsigned int start = get_index ( pd->cmd_list_length, pd->urgent_list[i].start ); unsigned int start =
get_index(pd->cmd_list_length, pd->urgent_list[i].start);
unsigned int stop = get_index(pd->cmd_list_length, pd->urgent_list[i].stop); unsigned int stop = get_index(pd->cmd_list_length, pd->urgent_list[i].stop);
if (selected_line >= start && selected_line <= stop) { if (selected_line >= start && selected_line <= stop) {
*state |= URGENT; *state |= URGENT;
@@ -388,8 +378,8 @@ static char *_get_display_value ( const Mode *sw, unsigned int selected_line, G_
return get_entry ? g_strdup(pd->cmd_list[selected_line].entry) : NULL; return get_entry ? g_strdup(pd->cmd_list[selected_line].entry) : NULL;
} }
static int script_token_match ( const Mode *sw, rofi_int_matcher **tokens, unsigned int index ) static int script_token_match(const Mode *sw, rofi_int_matcher **tokens,
{ unsigned int index) {
ScriptModePrivateData *rmpd = sw->private_data; ScriptModePrivateData *rmpd = sw->private_data;
int match = 1; int match = 1;
if (tokens) { if (tokens) {
@@ -408,14 +398,14 @@ static int script_token_match ( const Mode *sw, rofi_int_matcher **tokens, unsig
} }
return match; return match;
} }
static char *script_get_message ( const Mode *sw ) static char *script_get_message(const Mode *sw) {
{
ScriptModePrivateData *pd = sw->private_data; ScriptModePrivateData *pd = sw->private_data;
return g_strdup(pd->message); return g_strdup(pd->message);
} }
static cairo_surface_t *script_get_icon ( const Mode *sw, unsigned int selected_line, int height ) static cairo_surface_t *
{ script_get_icon(const Mode *sw, unsigned int selected_line, int height) {
ScriptModePrivateData *pd = (ScriptModePrivateData *) mode_get_private_data ( sw ); ScriptModePrivateData *pd =
(ScriptModePrivateData *)mode_get_private_data(sw);
g_return_val_if_fail(pd->cmd_list != NULL, NULL); g_return_val_if_fail(pd->cmd_list != NULL, NULL);
DmenuScriptEntry *dr = &(pd->cmd_list[selected_line]); DmenuScriptEntry *dr = &(pd->cmd_list[selected_line]);
if (dr->icon_name == NULL) { if (dr->icon_name == NULL) {
@@ -429,18 +419,17 @@ static cairo_surface_t *script_get_icon ( const Mode *sw, unsigned int selected_
} }
#include "mode-private.h" #include "mode-private.h"
Mode *script_switcher_parse_setup ( const char *str ) Mode *script_switcher_parse_setup(const char *str) {
{
Mode *sw = g_malloc0(sizeof(*sw)); Mode *sw = g_malloc0(sizeof(*sw));
char *endp = NULL; char *endp = NULL;
char *parse = g_strdup(str); char *parse = g_strdup(str);
unsigned int index = 0; unsigned int index = 0;
const char *const sep = ":"; const char *const sep = ":";
for ( char *token = strtok_r ( parse, sep, &endp ); token != NULL; token = strtok_r ( NULL, sep, &endp ) ) { for (char *token = strtok_r(parse, sep, &endp); token != NULL;
token = strtok_r(NULL, sep, &endp)) {
if (index == 0) { if (index == 0) {
sw->name = g_strdup(token); sw->name = g_strdup(token);
} } else if (index == 1) {
else if ( index == 1 ) {
sw->ed = (void *)rofi_expand_path(token); sw->ed = (void *)rofi_expand_path(token);
} }
index++; index++;
@@ -455,18 +444,19 @@ Mode *script_switcher_parse_setup ( const char *str )
sw->_token_match = script_token_match; sw->_token_match = script_token_match;
sw->_get_message = script_get_message; sw->_get_message = script_get_message;
sw->_get_icon = script_get_icon; sw->_get_icon = script_get_icon;
sw->_get_completion = NULL, sw->_get_completion = NULL, sw->_preprocess_input = NULL,
sw->_preprocess_input = NULL,
sw->_get_display_value = _get_display_value; sw->_get_display_value = _get_display_value;
return sw; return sw;
} }
fprintf ( stderr, "The script command '%s' has %u options, but needs 2: <name>:<script>.", str, index ); fprintf(
stderr,
"The script command '%s' has %u options, but needs 2: <name>:<script>.",
str, index);
script_switcher_free(sw); script_switcher_free(sw);
return NULL; return NULL;
} }
gboolean script_switcher_is_valid ( const char *token ) gboolean script_switcher_is_valid(const char *token) {
{
return strchr(token, ':') != NULL; return strchr(token, ':') != NULL;
} }

View File

@@ -37,30 +37,29 @@
#include <config.h> #include <config.h>
#include <glib.h> #include <glib.h>
#include <stdlib.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <dirent.h>
#include <strings.h>
#include <string.h>
#include <ctype.h> #include <ctype.h>
#include <dirent.h>
#include <errno.h> #include <errno.h>
#include <helper.h>
#include <glob.h> #include <glob.h>
#include <helper.h>
#include <signal.h>
#include <string.h>
#include <strings.h>
#include <sys/types.h>
#include <unistd.h>
#include "dialogs/ssh.h"
#include "history.h"
#include "rofi.h" #include "rofi.h"
#include "settings.h" #include "settings.h"
#include "history.h"
#include "dialogs/ssh.h"
/** /**
* Holding an ssh entry. * Holding an ssh entry.
*/ */
typedef struct _SshEntry typedef struct _SshEntry {
{
/** SSH hostname */ /** SSH hostname */
char *hostname; char *hostname;
/** SSH port number */ /** SSH port number */
@@ -69,8 +68,7 @@ typedef struct _SshEntry
/** /**
* The internal data structure holding the private data of the SSH Mode. * The internal data structure holding the private data of the SSH Mode.
*/ */
typedef struct typedef struct {
{
GList *user_known_hosts; GList *user_known_hosts;
/** List if available ssh hosts.*/ /** List if available ssh hosts.*/
SshEntry *hosts_list; SshEntry *hosts_list;
@@ -96,18 +94,15 @@ typedef struct
* *
* @returns FALSE On failure, TRUE on success * @returns FALSE On failure, TRUE on success
*/ */
static int execshssh ( const SshEntry *entry ) static int execshssh(const SshEntry *entry) {
{
char **args = NULL; char **args = NULL;
int argsv = 0; int argsv = 0;
gchar *portstr = NULL; gchar *portstr = NULL;
if (entry->port > 0) { if (entry->port > 0) {
portstr = g_strdup_printf("%d", entry->port); portstr = g_strdup_printf("%d", entry->port);
} }
helper_parse_setup ( config.ssh_command, &args, &argsv, helper_parse_setup(config.ssh_command, &args, &argsv, "{host}",
"{host}", entry->hostname, entry->hostname, "{port}", portstr, (char *)0);
"{port}", portstr,
(char *) 0 );
g_free(portstr); g_free(portstr);
gsize l = strlen("Connecting to '' via rofi") + strlen(entry->hostname) + 1; gsize l = strlen("Connecting to '' via rofi") + strlen(entry->hostname) + 1;
@@ -128,8 +123,7 @@ static int execshssh ( const SshEntry *entry )
* *
* SSH into the selected host, if successful update history. * SSH into the selected host, if successful update history.
*/ */
static void exec_ssh ( const SshEntry *entry ) static void exec_ssh(const SshEntry *entry) {
{
if (!(entry->hostname) || !(entry->hostname[0])) { if (!(entry->hostname) || !(entry->hostname[0])) {
return; return;
} }
@@ -146,8 +140,7 @@ static void exec_ssh ( const SshEntry *entry )
char *store = g_strdup_printf("%s\x1F%d", entry->hostname, entry->port); char *store = g_strdup_printf("%s\x1F%d", entry->hostname, entry->port);
history_set(path, store); history_set(path, store);
g_free(store); g_free(store);
} } else {
else {
history_set(path, entry->hostname); history_set(path, entry->hostname);
} }
g_free(path); g_free(path);
@@ -158,8 +151,7 @@ static void exec_ssh ( const SshEntry *entry )
* *
* Remove host from history. * Remove host from history.
*/ */
static void delete_ssh ( const char *host ) static void delete_ssh(const char *host) {
{
if (!host || !host[0]) { if (!host || !host[0]) {
return; return;
} }
@@ -177,8 +169,8 @@ static void delete_ssh ( const char *host )
* *
* @returns updated list of hosts. * @returns updated list of hosts.
*/ */
static SshEntry *read_known_hosts_file ( const char *path, SshEntry * retv, unsigned int *length ) static SshEntry *read_known_hosts_file(const char *path, SshEntry *retv,
{ unsigned int *length) {
FILE *fd = fopen(path, "r"); FILE *fd = fopen(path, "r");
if (fd != NULL) { if (fd != NULL) {
char *buffer = NULL; char *buffer = NULL;
@@ -217,14 +209,13 @@ static SshEntry *read_known_hosts_file ( const char *path, SshEntry * retv, unsi
gint64 number = g_ascii_strtoll(&(end[2]), &endptr, 10); gint64 number = g_ascii_strtoll(&(end[2]), &endptr, 10);
if (errno != 0) { if (errno != 0) {
g_warning("Failed to parse port number: %s.", &(end[2])); g_warning("Failed to parse port number: %s.", &(end[2]));
} } else if (endptr == &(end[2])) {
else if ( endptr == &( end[2] ) ) { g_warning("Failed to parse port number: %s, invalid number.",
g_warning ( "Failed to parse port number: %s, invalid number.", &( end[2] ) ); &(end[2]));
} } else if (number < 0 || number > 65535) {
else if ( number < 0 || number > 65535 ) { g_warning("Failed to parse port number: %s, out of range.",
g_warning ( "Failed to parse port number: %s, out of range.", &( end[2] ) ); &(end[2]));
} } else {
else {
port = number; port = number;
} }
} }
@@ -257,8 +248,7 @@ static SshEntry *read_known_hosts_file ( const char *path, SshEntry * retv, unsi
if (fclose(fd) != 0) { if (fclose(fd) != 0) {
g_warning("Failed to close hosts file: '%s'", g_strerror(errno)); g_warning("Failed to close hosts file: '%s'", g_strerror(errno));
} }
} } else {
else {
g_debug("Failed to open KnownHostFile: '%s'", path); g_debug("Failed to open KnownHostFile: '%s'", path);
} }
@@ -273,8 +263,7 @@ static SshEntry *read_known_hosts_file ( const char *path, SshEntry * retv, unsi
* *
* @returns an updated list with the added hosts. * @returns an updated list with the added hosts.
*/ */
static SshEntry *read_hosts_file ( SshEntry * retv, unsigned int *length ) static SshEntry *read_hosts_file(SshEntry *retv, unsigned int *length) {
{
// Read the hosts file. // Read the hosts file.
FILE *fd = fopen("/etc/hosts", "r"); FILE *fd = fopen("/etc/hosts", "r");
if (fd != NULL) { if (fd != NULL) {
@@ -309,8 +298,7 @@ static SshEntry *read_hosts_file ( SshEntry * retv, unsigned int *length )
if (!found) { if (!found) {
// Add this host name to the list. // Add this host name to the list.
retv = g_realloc ( retv, retv = g_realloc(retv, ((*length) + 2) * sizeof(SshEntry));
( ( *length ) + 2 ) * sizeof ( SshEntry ) );
retv[(*length)].hostname = g_strdup(token); retv[(*length)].hostname = g_strdup(token);
retv[(*length)].port = 0; retv[(*length)].port = 0;
retv[(*length) + 1].hostname = NULL; retv[(*length) + 1].hostname = NULL;
@@ -340,20 +328,20 @@ static SshEntry *read_hosts_file ( SshEntry * retv, unsigned int *length )
return retv; return retv;
} }
static void add_known_hosts_file ( SSHModePrivateData *pd, const char *token ) static void add_known_hosts_file(SSHModePrivateData *pd, const char *token) {
{ GList *item =
GList *item = g_list_find_custom ( pd->user_known_hosts, token, (GCompareFunc) g_strcmp0 ); g_list_find_custom(pd->user_known_hosts, token, (GCompareFunc)g_strcmp0);
if (item == NULL) { if (item == NULL) {
g_debug("Add '%s' to UserKnownHost list", token); g_debug("Add '%s' to UserKnownHost list", token);
pd->user_known_hosts = g_list_append(pd->user_known_hosts, g_strdup(token)); pd->user_known_hosts = g_list_append(pd->user_known_hosts, g_strdup(token));
} } else {
else {
g_debug("File '%s' already in UserKnownHostsFile list", token); g_debug("File '%s' already in UserKnownHostsFile list", token);
} }
} }
static void parse_ssh_config_file ( SSHModePrivateData *pd, const char *filename, SshEntry **retv, unsigned int *length, unsigned int num_favorites ) static void parse_ssh_config_file(SSHModePrivateData *pd, const char *filename,
{ SshEntry **retv, unsigned int *length,
unsigned int num_favorites) {
FILE *fd = fopen(filename, "r"); FILE *fd = fopen(filename, "r");
g_debug("Parsing ssh config file: %s", filename); g_debug("Parsing ssh config file: %s", filename);
@@ -383,29 +371,27 @@ static void parse_ssh_config_file ( SSHModePrivateData *pd, const char *filename
char *dirname = g_path_get_dirname(filename); char *dirname = g_path_get_dirname(filename);
full_path = g_build_filename(dirname, path, NULL); full_path = g_build_filename(dirname, path, NULL);
g_free(dirname); g_free(dirname);
} } else {
else {
full_path = g_strdup(path); full_path = g_strdup(path);
} }
glob_t globbuf = {.gl_pathc = 0, .gl_pathv = NULL, .gl_offs = 0}; glob_t globbuf = {.gl_pathc = 0, .gl_pathv = NULL, .gl_offs = 0};
if (glob(full_path, 0, NULL, &globbuf) == 0) { if (glob(full_path, 0, NULL, &globbuf) == 0) {
for (size_t iter = 0; iter < globbuf.gl_pathc; iter++) { for (size_t iter = 0; iter < globbuf.gl_pathc; iter++) {
parse_ssh_config_file ( pd, globbuf.gl_pathv[iter], retv, length, num_favorites ); parse_ssh_config_file(pd, globbuf.gl_pathv[iter], retv, length,
num_favorites);
} }
} }
globfree(&globbuf); globfree(&globbuf);
g_free(full_path); g_free(full_path);
g_free(path); g_free(path);
} } else if (g_strcmp0(low_token, "userknownhostsfile") == 0) {
else if ( g_strcmp0 ( low_token, "userknownhostsfile" ) == 0 ) {
while ((token = strtok_r(NULL, SSH_TOKEN_DELIM, &strtok_pointer))) { while ((token = strtok_r(NULL, SSH_TOKEN_DELIM, &strtok_pointer))) {
g_debug("Found extra UserKnownHostsFile: %s", token); g_debug("Found extra UserKnownHostsFile: %s", token);
add_known_hosts_file(pd, token); add_known_hosts_file(pd, token);
} }
} } else if (g_strcmp0(low_token, "host") == 0) {
else if ( g_strcmp0 ( low_token, "host" ) == 0 ) {
// Now we know that this is a "Host" line. // Now we know that this is a "Host" line.
// The "Host" keyword is followed by one more host names separated // The "Host" keyword is followed by one more host names separated
// by whitespace; while host names may be quoted with double quotes // by whitespace; while host names may be quoted with double quotes
@@ -453,7 +439,8 @@ static void parse_ssh_config_file ( SSHModePrivateData *pd, const char *filename
} }
if (fclose(fd) != 0) { if (fclose(fd) != 0) {
g_warning ( "Failed to close ssh configuration file: '%s'", g_strerror ( errno ) ); g_warning("Failed to close ssh configuration file: '%s'",
g_strerror(errno));
} }
} }
} }
@@ -466,8 +453,7 @@ static void parse_ssh_config_file ( SSHModePrivateData *pd, const char *filename
* *
* @returns an array of strings containing all the hosts. * @returns an array of strings containing all the hosts.
*/ */
static SshEntry * get_ssh ( SSHModePrivateData *pd, unsigned int *length ) static SshEntry *get_ssh(SSHModePrivateData *pd, unsigned int *length) {
{
SshEntry *retv = NULL; SshEntry *retv = NULL;
unsigned int num_favorites = 0; unsigned int num_favorites = 0;
char *path; char *path;
@@ -490,14 +476,13 @@ static SshEntry * get_ssh ( SSHModePrivateData *pd, unsigned int *length )
gint64 number = g_ascii_strtoll(&(portstr[1]), &endptr, 10); gint64 number = g_ascii_strtoll(&(portstr[1]), &endptr, 10);
if (errno != 0) { if (errno != 0) {
g_warning("Failed to parse port number: %s.", &(portstr[1])); g_warning("Failed to parse port number: %s.", &(portstr[1]));
} } else if (endptr == &(portstr[1])) {
else if ( endptr == &( portstr[1] ) ) { g_warning("Failed to parse port number: %s, invalid number.",
g_warning ( "Failed to parse port number: %s, invalid number.", &( portstr[1] ) ); &(portstr[1]));
} } else if (number < 0 || number > 65535) {
else if ( number < 0 || number > 65535 ) { g_warning("Failed to parse port number: %s, out of range.",
g_warning ( "Failed to parse port number: %s, out of range.", &( portstr[1] ) ); &(portstr[1]));
} } else {
else {
port = number; port = number;
} }
} }
@@ -514,10 +499,12 @@ static SshEntry * get_ssh ( SSHModePrivateData *pd, unsigned int *length )
parse_ssh_config_file(pd, path, &retv, length, num_favorites); parse_ssh_config_file(pd, path, &retv, length, num_favorites);
if (config.parse_known_hosts == TRUE) { if (config.parse_known_hosts == TRUE) {
char *path = g_build_filename ( g_get_home_dir (), ".ssh", "known_hosts", NULL ); char *path =
g_build_filename(g_get_home_dir(), ".ssh", "known_hosts", NULL);
retv = read_known_hosts_file(path, retv, length); retv = read_known_hosts_file(path, retv, length);
g_free(path); g_free(path);
for ( GList *iter = g_list_first ( pd->user_known_hosts ); iter; iter = g_list_next ( iter ) ) { for (GList *iter = g_list_first(pd->user_known_hosts); iter;
iter = g_list_next(iter)) {
char *path = rofi_expand_path((const char *)iter->data); char *path = rofi_expand_path((const char *)iter->data);
retv = read_known_hosts_file((const char *)path, retv, length); retv = read_known_hosts_file((const char *)path, retv, length);
g_free(path); g_free(path);
@@ -538,8 +525,7 @@ static SshEntry * get_ssh ( SSHModePrivateData *pd, unsigned int *length )
* Initializes the SSH Mode private data object and * Initializes the SSH Mode private data object and
* loads the relevant ssh information. * loads the relevant ssh information.
*/ */
static int ssh_mode_init ( Mode *sw ) static int ssh_mode_init(Mode *sw) {
{
if (mode_get_private_data(sw) == NULL) { if (mode_get_private_data(sw) == NULL) {
SSHModePrivateData *pd = g_malloc0(sizeof(*pd)); SSHModePrivateData *pd = g_malloc0(sizeof(*pd));
mode_set_private_data(sw, (void *)pd); mode_set_private_data(sw, (void *)pd);
@@ -555,18 +541,18 @@ static int ssh_mode_init ( Mode *sw )
* *
* @returns the number of ssh entries. * @returns the number of ssh entries.
*/ */
static unsigned int ssh_mode_get_num_entries ( const Mode *sw ) static unsigned int ssh_mode_get_num_entries(const Mode *sw) {
{ const SSHModePrivateData *rmpd =
const SSHModePrivateData *rmpd = (const SSHModePrivateData *) mode_get_private_data ( sw ); (const SSHModePrivateData *)mode_get_private_data(sw);
return rmpd->hosts_list_length; return rmpd->hosts_list_length;
} }
/** /**
* @param sw Object handle to the SSH Mode object * @param sw Object handle to the SSH Mode object
* *
* Cleanup the SSH Mode. Free all allocated memory and NULL the private data pointer. * Cleanup the SSH Mode. Free all allocated memory and NULL the private data
* pointer.
*/ */
static void ssh_mode_destroy ( Mode *sw ) static void ssh_mode_destroy(Mode *sw) {
{
SSHModePrivateData *rmpd = (SSHModePrivateData *)mode_get_private_data(sw); SSHModePrivateData *rmpd = (SSHModePrivateData *)mode_get_private_data(sw);
if (rmpd != NULL) { if (rmpd != NULL) {
for (unsigned int i = 0; i < rmpd->hosts_list_length; i++) { for (unsigned int i = 0; i < rmpd->hosts_list_length; i++) {
@@ -589,25 +575,24 @@ static void ssh_mode_destroy ( Mode *sw )
* *
* @returns the next #ModeMode. * @returns the next #ModeMode.
*/ */
static ModeMode ssh_mode_result ( Mode *sw, int mretv, char **input, unsigned int selected_line ) static ModeMode ssh_mode_result(Mode *sw, int mretv, char **input,
{ unsigned int selected_line) {
ModeMode retv = MODE_EXIT; ModeMode retv = MODE_EXIT;
SSHModePrivateData *rmpd = (SSHModePrivateData *)mode_get_private_data(sw); SSHModePrivateData *rmpd = (SSHModePrivateData *)mode_get_private_data(sw);
if ((mretv & MENU_OK) && rmpd->hosts_list[selected_line].hostname != NULL) { if ((mretv & MENU_OK) && rmpd->hosts_list[selected_line].hostname != NULL) {
exec_ssh(&(rmpd->hosts_list[selected_line])); exec_ssh(&(rmpd->hosts_list[selected_line]));
} } else if ((mretv & MENU_CUSTOM_INPUT) && *input != NULL &&
else if ( ( mretv & MENU_CUSTOM_INPUT ) && *input != NULL && *input[0] != '\0' ) { *input[0] != '\0') {
SshEntry entry = {.hostname = *input, .port = 0}; SshEntry entry = {.hostname = *input, .port = 0};
exec_ssh(&entry); exec_ssh(&entry);
} } else if ((mretv & MENU_ENTRY_DELETE) &&
else if ( ( mretv & MENU_ENTRY_DELETE ) && rmpd->hosts_list[selected_line].hostname ) { rmpd->hosts_list[selected_line].hostname) {
delete_ssh(rmpd->hosts_list[selected_line].hostname); delete_ssh(rmpd->hosts_list[selected_line].hostname);
// Stay // Stay
retv = RELOAD_DIALOG; retv = RELOAD_DIALOG;
ssh_mode_destroy(sw); ssh_mode_destroy(sw);
ssh_mode_init(sw); ssh_mode_init(sw);
} } else if (mretv & MENU_CUSTOM_COMMAND) {
else if ( mretv & MENU_CUSTOM_COMMAND ) {
retv = (mretv & MENU_LOWER_MASK); retv = (mretv & MENU_LOWER_MASK);
} }
return retv; return retv;
@@ -625,8 +610,10 @@ static ModeMode ssh_mode_result ( Mode *sw, int mretv, char **input, unsigned in
* *
* @return the string as it should be displayed and the display state. * @return the string as it should be displayed and the display state.
*/ */
static char *_get_display_value ( const Mode *sw, unsigned int selected_line, G_GNUC_UNUSED int *state, G_GNUC_UNUSED GList **attr_list, int get_entry ) static char *_get_display_value(const Mode *sw, unsigned int selected_line,
{ G_GNUC_UNUSED int *state,
G_GNUC_UNUSED GList **attr_list,
int get_entry) {
SSHModePrivateData *rmpd = (SSHModePrivateData *)mode_get_private_data(sw); SSHModePrivateData *rmpd = (SSHModePrivateData *)mode_get_private_data(sw);
return get_entry ? g_strdup(rmpd->hosts_list[selected_line].hostname) : NULL; return get_entry ? g_strdup(rmpd->hosts_list[selected_line].hostname) : NULL;
} }
@@ -640,15 +627,13 @@ static char *_get_display_value ( const Mode *sw, unsigned int selected_line, G_
* *
* @returns TRUE if matches * @returns TRUE if matches
*/ */
static int ssh_token_match ( const Mode *sw, rofi_int_matcher **tokens, unsigned int index ) static int ssh_token_match(const Mode *sw, rofi_int_matcher **tokens,
{ unsigned int index) {
SSHModePrivateData *rmpd = (SSHModePrivateData *)mode_get_private_data(sw); SSHModePrivateData *rmpd = (SSHModePrivateData *)mode_get_private_data(sw);
return helper_token_match(tokens, rmpd->hosts_list[index].hostname); return helper_token_match(tokens, rmpd->hosts_list[index].hostname);
} }
#include "mode-private.h" #include "mode-private.h"
Mode ssh_mode = Mode ssh_mode = {.name = "ssh",
{
.name = "ssh",
.cfg_name_key = "display-ssh", .cfg_name_key = "display-ssh",
._init = ssh_mode_init, ._init = ssh_mode_init,
._get_num_entries = ssh_mode_get_num_entries, ._get_num_entries = ssh_mode_get_num_entries,
@@ -659,6 +644,5 @@ Mode ssh_mode =
._get_completion = NULL, ._get_completion = NULL,
._preprocess_input = NULL, ._preprocess_input = NULL,
.private_data = NULL, .private_data = NULL,
.free = NULL .free = NULL};
};
/**@}*/ /**@}*/

View File

@@ -32,33 +32,33 @@
#ifdef WINDOW_MODE #ifdef WINDOW_MODE
#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>
#include <unistd.h>
#include <strings.h>
#include <string.h>
#include <errno.h> #include <errno.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <strings.h>
#include <unistd.h>
#include <xcb/xcb.h> #include <xcb/xcb.h>
#include <xcb/xcb_atom.h>
#include <xcb/xcb_ewmh.h> #include <xcb/xcb_ewmh.h>
#include <xcb/xcb_icccm.h> #include <xcb/xcb_icccm.h>
#include <xcb/xcb_atom.h>
#include <glib.h> #include <glib.h>
#include "xcb-internal.h" #include "xcb-internal.h"
#include "xcb.h" #include "xcb.h"
#include "dialogs/window.h"
#include "helper.h"
#include "rofi.h" #include "rofi.h"
#include "settings.h" #include "settings.h"
#include "helper.h"
#include "widgets/textbox.h" #include "widgets/textbox.h"
#include "dialogs/window.h"
#include "timings.h" #include "timings.h"
#include "rofi-icon-fetcher.h"
#include "mode-private.h" #include "mode-private.h"
#include "rofi-icon-fetcher.h"
#define WINLIST 32 #define WINLIST 32
@@ -66,14 +66,12 @@
#define CLIENTWINDOWTYPE 10 #define CLIENTWINDOWTYPE 10
// Fields to match in window mode // Fields to match in window mode
typedef struct typedef struct {
{
char *field_name; char *field_name;
gboolean enabled; gboolean enabled;
} WinModeField; } WinModeField;
typedef enum typedef enum {
{
WIN_MATCH_FIELD_TITLE, WIN_MATCH_FIELD_TITLE,
WIN_MATCH_FIELD_CLASS, WIN_MATCH_FIELD_CLASS,
WIN_MATCH_FIELD_ROLE, WIN_MATCH_FIELD_ROLE,
@@ -83,18 +81,31 @@ typedef enum
} WinModeMatchingFields; } WinModeMatchingFields;
static WinModeField matching_window_fields[WIN_MATCH_NUM_FIELDS] = { static WinModeField matching_window_fields[WIN_MATCH_NUM_FIELDS] = {
{ .field_name = "title", .enabled = TRUE, }, {
{ .field_name = "class", .enabled = TRUE, }, .field_name = "title",
{ .field_name = "role", .enabled = TRUE, }, .enabled = TRUE,
{ .field_name = "name", .enabled = TRUE, }, },
{ .field_name = "desktop", .enabled = TRUE, } {
}; .field_name = "class",
.enabled = TRUE,
},
{
.field_name = "role",
.enabled = TRUE,
},
{
.field_name = "name",
.enabled = TRUE,
},
{
.field_name = "desktop",
.enabled = TRUE,
}};
static gboolean window_matching_fields_parsed = FALSE; static gboolean window_matching_fields_parsed = FALSE;
// a manageable window // a manageable window
typedef struct typedef struct {
{
xcb_window_t window; xcb_window_t window;
xcb_get_window_attributes_reply_t xattr; xcb_get_window_attributes_reply_t xattr;
char *title; char *title;
@@ -118,15 +129,13 @@ typedef struct
} client; } client;
// window lists // window lists
typedef struct typedef struct {
{
xcb_window_t *array; xcb_window_t *array;
client **data; client **data;
int len; int len;
} winlist; } winlist;
typedef struct typedef struct {
{
unsigned int id; unsigned int id;
winlist *ids; winlist *ids;
// Current window. // Current window.
@@ -147,8 +156,7 @@ winlist *cache_client = NULL;
* *
* @returns A new window list. * @returns A new window list.
*/ */
static winlist* winlist_new () static winlist *winlist_new() {
{
winlist *l = g_malloc(sizeof(winlist)); winlist *l = g_malloc(sizeof(winlist));
l->len = 0; l->len = 0;
l->array = g_malloc_n(WINLIST + 1, sizeof(xcb_window_t)); l->array = g_malloc_n(WINLIST + 1, sizeof(xcb_window_t));
@@ -165,10 +173,10 @@ static winlist* winlist_new ()
* *
* @returns 0 if failed, 1 is successful. * @returns 0 if failed, 1 is successful.
*/ */
static int winlist_append ( winlist *l, xcb_window_t w, client *d ) static int winlist_append(winlist *l, xcb_window_t w, client *d) {
{
if (l->len > 0 && !(l->len % WINLIST)) { if (l->len > 0 && !(l->len % WINLIST)) {
l->array = g_realloc ( l->array, sizeof ( xcb_window_t ) * ( l->len + WINLIST + 1 ) ); l->array =
g_realloc(l->array, sizeof(xcb_window_t) * (l->len + WINLIST + 1));
l->data = g_realloc(l->data, sizeof(client *) * (l->len + WINLIST + 1)); l->data = g_realloc(l->data, sizeof(client *) * (l->len + WINLIST + 1));
} }
// Make clang-check happy. // Make clang-check happy.
@@ -182,8 +190,7 @@ static int winlist_append ( winlist *l, xcb_window_t w, client *d )
return l->len - 1; return l->len - 1;
} }
static void client_free ( client *c ) static void client_free(client *c) {
{
if (c == NULL) { if (c == NULL) {
return; return;
} }
@@ -196,8 +203,7 @@ static void client_free ( client *c )
g_free(c->role); g_free(c->role);
g_free(c->wmdesktopstr); g_free(c->wmdesktopstr);
} }
static void winlist_empty ( winlist *l ) static void winlist_empty(winlist *l) {
{
while (l->len > 0) { while (l->len > 0) {
client *c = l->data[--l->len]; client *c = l->data[--l->len];
if (c != NULL) { if (c != NULL) {
@@ -212,8 +218,7 @@ static void winlist_empty ( winlist *l )
* *
* Free the winlist. * Free the winlist.
*/ */
static void winlist_free ( winlist *l ) static void winlist_free(winlist *l) {
{
if (l != NULL) { if (l != NULL) {
winlist_empty(l); winlist_empty(l);
g_free(l->array); g_free(l->array);
@@ -230,8 +235,7 @@ static void winlist_free ( winlist *l )
* *
* @returns -1 if failed, index is successful. * @returns -1 if failed, index is successful.
*/ */
static int winlist_find ( winlist *l, xcb_window_t w ) static int winlist_find(winlist *l, xcb_window_t w) {
{
// iterate backwards. Theory is: windows most often accessed will be // iterate backwards. Theory is: windows most often accessed will be
// nearer the end. Testing with kcachegrind seems to support this... // nearer the end. Testing with kcachegrind seems to support this...
int i; int i;
@@ -247,8 +251,7 @@ static int winlist_find ( winlist *l, xcb_window_t w )
/** /**
* Create empty X11 cache for windows and windows attributes. * Create empty X11 cache for windows and windows attributes.
*/ */
static void x11_cache_create ( void ) static void x11_cache_create(void) {
{
if (cache_client == NULL) { if (cache_client == NULL) {
cache_client = winlist_new(); cache_client = winlist_new();
} }
@@ -257,8 +260,7 @@ static void x11_cache_create ( void )
/** /**
* Free the cache. * Free the cache.
*/ */
static void x11_cache_free ( void ) static void x11_cache_free(void) {
{
winlist_free(cache_client); winlist_free(cache_client);
cache_client = NULL; cache_client = NULL;
} }
@@ -272,18 +274,19 @@ static void x11_cache_free ( void )
* *
* @returns a XWindowAttributes * @returns a XWindowAttributes
*/ */
static xcb_get_window_attributes_reply_t * window_get_attributes ( xcb_window_t w ) static xcb_get_window_attributes_reply_t *
{ window_get_attributes(xcb_window_t w) {
xcb_get_window_attributes_cookie_t c = xcb_get_window_attributes ( xcb->connection, w ); xcb_get_window_attributes_cookie_t c =
xcb_get_window_attributes_reply_t *r = xcb_get_window_attributes_reply ( xcb->connection, c, NULL ); xcb_get_window_attributes(xcb->connection, w);
xcb_get_window_attributes_reply_t *r =
xcb_get_window_attributes_reply(xcb->connection, c, NULL);
if (r) { if (r) {
return r; return r;
} }
return NULL; return NULL;
} }
// _NET_WM_STATE_* // _NET_WM_STATE_*
static int client_has_state ( client *c, xcb_atom_t state ) static int client_has_state(client *c, xcb_atom_t state) {
{
for (int i = 0; i < c->states; i++) { for (int i = 0; i < c->states; i++) {
if (c->state[i] == state) { if (c->state[i] == state) {
return 1; return 1;
@@ -292,8 +295,7 @@ static int client_has_state ( client *c, xcb_atom_t state )
return 0; return 0;
} }
static int client_has_window_type ( client *c, xcb_atom_t type ) static int client_has_window_type(client *c, xcb_atom_t type) {
{
for (int i = 0; i < c->window_types; i++) { for (int i = 0; i < c->window_types; i++) {
if (c->window_type[i] == type) { if (c->window_type[i] == type) {
return 1; return 1;
@@ -303,8 +305,7 @@ static int client_has_window_type ( client *c, xcb_atom_t type )
return 0; return 0;
} }
static client* window_client ( ModeModePrivateData *pd, xcb_window_t win ) static client *window_client(ModeModePrivateData *pd, xcb_window_t win) {
{
if (win == XCB_WINDOW_NONE) { if (win == XCB_WINDOW_NONE) {
return NULL; return NULL;
} }
@@ -331,13 +332,15 @@ static client* window_client ( ModeModePrivateData *pd, xcb_window_t win )
xcb_ewmh_get_atoms_reply_t states; xcb_ewmh_get_atoms_reply_t states;
if (xcb_ewmh_get_wm_state_reply(&xcb->ewmh, cky, &states, NULL)) { if (xcb_ewmh_get_wm_state_reply(&xcb->ewmh, cky, &states, NULL)) {
c->states = MIN(CLIENTSTATE, states.atoms_len); c->states = MIN(CLIENTSTATE, states.atoms_len);
memcpy ( c->state, states.atoms, MIN ( CLIENTSTATE, states.atoms_len ) * sizeof ( xcb_atom_t ) ); memcpy(c->state, states.atoms,
MIN(CLIENTSTATE, states.atoms_len) * sizeof(xcb_atom_t));
xcb_ewmh_get_atoms_reply_wipe(&states); xcb_ewmh_get_atoms_reply_wipe(&states);
} }
cky = xcb_ewmh_get_wm_window_type(&xcb->ewmh, win); cky = xcb_ewmh_get_wm_window_type(&xcb->ewmh, win);
if (xcb_ewmh_get_wm_window_type_reply(&xcb->ewmh, cky, &states, NULL)) { if (xcb_ewmh_get_wm_window_type_reply(&xcb->ewmh, cky, &states, NULL)) {
c->window_types = MIN(CLIENTWINDOWTYPE, states.atoms_len); c->window_types = MIN(CLIENTWINDOWTYPE, states.atoms_len);
memcpy ( c->window_type, states.atoms, MIN ( CLIENTWINDOWTYPE, states.atoms_len ) * sizeof ( xcb_atom_t ) ); memcpy(c->window_type, states.atoms,
MIN(CLIENTWINDOWTYPE, states.atoms_len) * sizeof(xcb_atom_t));
xcb_ewmh_get_atoms_reply_wipe(&states); xcb_ewmh_get_atoms_reply_wipe(&states);
} }
@@ -346,7 +349,8 @@ static client* window_client ( ModeModePrivateData *pd, xcb_window_t win )
tmp_title = window_get_text_prop(c->window, XCB_ATOM_WM_NAME); tmp_title = window_get_text_prop(c->window, XCB_ATOM_WM_NAME);
} }
c->title = g_markup_escape_text(tmp_title, -1); c->title = g_markup_escape_text(tmp_title, -1);
pd->title_len = MAX ( c->title ? g_utf8_strlen ( c->title, -1 ) : 0, pd->title_len ); pd->title_len =
MAX(c->title ? g_utf8_strlen(c->title, -1) : 0, pd->title_len);
g_free(tmp_title); g_free(tmp_title);
char *tmp_role = window_get_text_prop(c->window, netatoms[WM_WINDOW_ROLE]); char *tmp_role = window_get_text_prop(c->window, netatoms[WM_WINDOW_ROLE]);
@@ -363,7 +367,8 @@ static client* window_client ( ModeModePrivateData *pd, xcb_window_t win )
xcb_icccm_get_wm_class_reply_wipe(&wcr); xcb_icccm_get_wm_class_reply_wipe(&wcr);
} }
xcb_get_property_cookie_t cc = xcb_icccm_get_wm_hints ( xcb->connection, c->window ); xcb_get_property_cookie_t cc =
xcb_icccm_get_wm_hints(xcb->connection, c->window);
xcb_icccm_wm_hints_t r; xcb_icccm_wm_hints_t r;
if (xcb_icccm_get_wm_hints_reply(xcb->connection, cc, &r, NULL)) { if (xcb_icccm_get_wm_hints_reply(xcb->connection, cc, &r, NULL)) {
c->hint_flags = r.flags; c->hint_flags = r.flags;
@@ -373,8 +378,8 @@ static client* window_client ( ModeModePrivateData *pd, xcb_window_t win )
g_free(attr); g_free(attr);
return c; return c;
} }
static int window_match ( const Mode *sw, rofi_int_matcher **tokens, unsigned int index ) static int window_match(const Mode *sw, rofi_int_matcher **tokens,
{ unsigned int index) {
ModeModePrivateData *rmpd = (ModeModePrivateData *)mode_get_private_data(sw); ModeModePrivateData *rmpd = (ModeModePrivateData *)mode_get_private_data(sw);
int match = 1; int match = 1;
const winlist *ids = (winlist *)rmpd->ids; const winlist *ids = (winlist *)rmpd->ids;
@@ -388,25 +393,32 @@ static int window_match ( const Mode *sw, rofi_int_matcher **tokens, unsigned in
int test = 0; int test = 0;
// Dirty hack. Normally helper_token_match does _all_ the matching, // Dirty hack. Normally helper_token_match does _all_ the matching,
// Now we want it to match only one item at the time. // Now we want it to match only one item at the time.
// If hack not in place it would not match queries spanning multiple fields. // If hack not in place it would not match queries spanning multiple
// e.g. when searching 'title element' and 'class element' // fields. e.g. when searching 'title element' and 'class element'
rofi_int_matcher *ftokens[2] = {tokens[j], NULL}; rofi_int_matcher *ftokens[2] = {tokens[j], NULL};
if ( c->title != NULL && c->title[0] != '\0' && matching_window_fields[WIN_MATCH_FIELD_TITLE].enabled ) { if (c->title != NULL && c->title[0] != '\0' &&
matching_window_fields[WIN_MATCH_FIELD_TITLE].enabled) {
test = helper_token_match(ftokens, c->title); test = helper_token_match(ftokens, c->title);
} }
if ( test == tokens[j]->invert && c->class != NULL && c->class[0] != '\0' && matching_window_fields[WIN_MATCH_FIELD_CLASS].enabled ) { if (test == tokens[j]->invert && c->class != NULL &&
c->class[0] != '\0' &&
matching_window_fields[WIN_MATCH_FIELD_CLASS].enabled) {
test = helper_token_match(ftokens, c->class); test = helper_token_match(ftokens, c->class);
} }
if ( test == tokens[j]->invert && c->role != NULL && c->role[0] != '\0' && matching_window_fields[WIN_MATCH_FIELD_ROLE].enabled ) { if (test == tokens[j]->invert && c->role != NULL && c->role[0] != '\0' &&
matching_window_fields[WIN_MATCH_FIELD_ROLE].enabled) {
test = helper_token_match(ftokens, c->role); test = helper_token_match(ftokens, c->role);
} }
if ( test == tokens[j]->invert && c->name != NULL && c->name[0] != '\0' && matching_window_fields[WIN_MATCH_FIELD_NAME].enabled ) { if (test == tokens[j]->invert && c->name != NULL && c->name[0] != '\0' &&
matching_window_fields[WIN_MATCH_FIELD_NAME].enabled) {
test = helper_token_match(ftokens, c->name); test = helper_token_match(ftokens, c->name);
} }
if ( test == tokens[j]->invert && c->wmdesktopstr != NULL && c->wmdesktopstr[0] != '\0' && matching_window_fields[WIN_MATCH_FIELD_DESKTOP].enabled ) { if (test == tokens[j]->invert && c->wmdesktopstr != NULL &&
c->wmdesktopstr[0] != '\0' &&
matching_window_fields[WIN_MATCH_FIELD_DESKTOP].enabled) {
test = helper_token_match(ftokens, c->wmdesktopstr); test = helper_token_match(ftokens, c->wmdesktopstr);
} }
@@ -419,8 +431,7 @@ static int window_match ( const Mode *sw, rofi_int_matcher **tokens, unsigned in
return match; return match;
} }
static void window_mode_parse_fields () static void window_mode_parse_fields() {
{
window_matching_fields_parsed = TRUE; window_matching_fields_parsed = TRUE;
char *savept = NULL; char *savept = NULL;
// Make a copy, as strtok will modify it. // Make a copy, as strtok will modify it.
@@ -438,7 +449,6 @@ static void window_mode_parse_fields ()
} }
break; break;
} }
else {
gboolean matched = FALSE; gboolean matched = FALSE;
for (unsigned int i = 0; i < WIN_MATCH_NUM_FIELDS; i++) { for (unsigned int i = 0; i < WIN_MATCH_NUM_FIELDS; i++) {
const char *field_name = matching_window_fields[i].field_name; const char *field_name = matching_window_fields[i].field_name;
@@ -451,14 +461,13 @@ static void window_mode_parse_fields ()
g_warning("Invalid window field name :%s", token); g_warning("Invalid window field name :%s", token);
} }
} }
}
// Free string that was modified by strtok_r // Free string that was modified by strtok_r
g_free(switcher_str); g_free(switcher_str);
} }
static unsigned int window_mode_get_num_entries ( const Mode *sw ) static unsigned int window_mode_get_num_entries(const Mode *sw) {
{ const ModeModePrivateData *pd =
const ModeModePrivateData *pd = (const ModeModePrivateData *) mode_get_private_data ( sw ); (const ModeModePrivateData *)mode_get_private_data(sw);
return pd->ids ? pd->ids->len : 0; return pd->ids ? pd->ids->len : 0;
} }
@@ -467,8 +476,8 @@ static unsigned int window_mode_get_num_entries ( const Mode *sw )
* Is there a call for this? * Is there a call for this?
*/ */
const char *invalid_desktop_name = "n/a"; const char *invalid_desktop_name = "n/a";
static const char * _window_name_list_entry ( const char *str, uint32_t length, int entry ) static const char *_window_name_list_entry(const char *str, uint32_t length,
{ int entry) {
uint32_t offset = 0; uint32_t offset = 0;
int index = 0; int index = 0;
while (index < entry && offset < length) { while (index < entry && offset < length) {
@@ -482,8 +491,7 @@ static const char * _window_name_list_entry ( const char *str, uint32_t length,
} }
return &str[offset]; return &str[offset];
} }
static void _window_mode_load_data ( Mode *sw, unsigned int cd ) static void _window_mode_load_data(Mode *sw, unsigned int cd) {
{
ModeModePrivateData *pd = (ModeModePrivateData *)mode_get_private_data(sw); ModeModePrivateData *pd = (ModeModePrivateData *)mode_get_private_data(sw);
// find window list // find window list
xcb_window_t curr_win_id; xcb_window_t curr_win_id;
@@ -492,7 +500,8 @@ static void _window_mode_load_data ( Mode *sw, unsigned int cd )
// Create cache // Create cache
x11_cache_create(); x11_cache_create();
xcb_get_property_cookie_t c = xcb_ewmh_get_active_window ( &( xcb->ewmh ), xcb->screen_nbr ); xcb_get_property_cookie_t c =
xcb_ewmh_get_active_window(&(xcb->ewmh), xcb->screen_nbr);
if (!xcb_ewmh_get_active_window_reply(&xcb->ewmh, c, &curr_win_id, NULL)) { if (!xcb_ewmh_get_active_window_reply(&xcb->ewmh, c, &curr_win_id, NULL)) {
curr_win_id = 0; curr_win_id = 0;
} }
@@ -500,17 +509,19 @@ static void _window_mode_load_data ( Mode *sw, unsigned int cd )
// Get the current desktop. // Get the current desktop.
unsigned int current_desktop = 0; unsigned int current_desktop = 0;
c = xcb_ewmh_get_current_desktop(&xcb->ewmh, xcb->screen_nbr); c = xcb_ewmh_get_current_desktop(&xcb->ewmh, xcb->screen_nbr);
if ( !xcb_ewmh_get_current_desktop_reply ( &xcb->ewmh, c, &current_desktop, NULL ) ) { if (!xcb_ewmh_get_current_desktop_reply(&xcb->ewmh, c, &current_desktop,
NULL)) {
current_desktop = 0; current_desktop = 0;
} }
g_debug("Get list from: %d", xcb->screen_nbr); g_debug("Get list from: %d", xcb->screen_nbr);
c = xcb_ewmh_get_client_list_stacking(&xcb->ewmh, xcb->screen_nbr); c = xcb_ewmh_get_client_list_stacking(&xcb->ewmh, xcb->screen_nbr);
xcb_ewmh_get_windows_reply_t clients = { 0, }; xcb_ewmh_get_windows_reply_t clients = {
0,
};
if (xcb_ewmh_get_client_list_stacking_reply(&xcb->ewmh, c, &clients, NULL)) { if (xcb_ewmh_get_client_list_stacking_reply(&xcb->ewmh, c, &clients, NULL)) {
found = 1; found = 1;
} } else {
else {
c = xcb_ewmh_get_client_list(&xcb->ewmh, xcb->screen_nbr); c = xcb_ewmh_get_client_list(&xcb->ewmh, xcb->screen_nbr);
if (xcb_ewmh_get_client_list_reply(&xcb->ewmh, c, &clients, NULL)) { if (xcb_ewmh_get_client_list_reply(&xcb->ewmh, c, &clients, NULL)) {
found = 1; found = 1;
@@ -522,11 +533,13 @@ static void _window_mode_load_data ( Mode *sw, unsigned int cd )
if (clients.windows_len > 0) { if (clients.windows_len > 0) {
int i; int i;
// windows we actually display. May be slightly different to _NET_CLIENT_LIST_STACKING // windows we actually display. May be slightly different to
// if we happen to have a window destroyed while we're working... // _NET_CLIENT_LIST_STACKING if we happen to have a window destroyed while
// we're working...
pd->ids = winlist_new(); pd->ids = winlist_new();
xcb_get_property_cookie_t c = xcb_ewmh_get_desktop_names ( &xcb->ewmh, xcb->screen_nbr ); xcb_get_property_cookie_t c =
xcb_ewmh_get_desktop_names(&xcb->ewmh, xcb->screen_nbr);
xcb_ewmh_get_utf8_strings_reply_t names; xcb_ewmh_get_utf8_strings_reply_t names;
int has_names = FALSE; int has_names = FALSE;
if (xcb_ewmh_get_desktop_names_reply(&xcb->ewmh, c, &names, NULL)) { if (xcb_ewmh_get_desktop_names_reply(&xcb->ewmh, c, &names, NULL)) {
@@ -535,13 +548,14 @@ static void _window_mode_load_data ( Mode *sw, unsigned int cd )
// calc widths of fields // calc widths of fields
for (i = clients.windows_len - 1; i > -1; i--) { for (i = clients.windows_len - 1; i > -1; i--) {
client *c = window_client(pd, clients.windows[i]); client *c = window_client(pd, clients.windows[i]);
if ( ( c != NULL ) if ((c != NULL) && !c->xattr.override_redirect &&
&& !c->xattr.override_redirect !client_has_window_type(c, xcb->ewmh._NET_WM_WINDOW_TYPE_DOCK) &&
&& !client_has_window_type ( c, xcb->ewmh._NET_WM_WINDOW_TYPE_DOCK ) !client_has_window_type(c, xcb->ewmh._NET_WM_WINDOW_TYPE_DESKTOP) &&
&& !client_has_window_type ( c, xcb->ewmh._NET_WM_WINDOW_TYPE_DESKTOP ) !client_has_state(c, xcb->ewmh._NET_WM_STATE_SKIP_PAGER) &&
&& !client_has_state ( c, xcb->ewmh._NET_WM_STATE_SKIP_PAGER ) !client_has_state(c, xcb->ewmh._NET_WM_STATE_SKIP_TASKBAR)) {
&& !client_has_state ( c, xcb->ewmh._NET_WM_STATE_SKIP_TASKBAR ) ) { pd->clf_len =
pd->clf_len = MAX ( pd->clf_len, ( c->class != NULL ) ? ( g_utf8_strlen ( c->class, -1 ) ) : 0 ); MAX(pd->clf_len,
(c->class != NULL) ? (g_utf8_strlen(c->class, -1)) : 0);
if (client_has_state(c, xcb->ewmh._NET_WM_STATE_DEMANDS_ATTENTION)) { if (client_has_state(c, xcb->ewmh._NET_WM_STATE_DEMANDS_ATTENTION)) {
c->demands = TRUE; c->demands = TRUE;
@@ -558,9 +572,9 @@ static void _window_mode_load_data ( Mode *sw, unsigned int cd )
xcb_get_property_reply_t *r; xcb_get_property_reply_t *r;
c->wmdesktop = 0xFFFFFFFF; c->wmdesktop = 0xFFFFFFFF;
cookie = cookie = xcb_get_property(xcb->connection, 0, c->window,
xcb_get_property ( xcb->connection, 0, c->window, xcb->ewmh._NET_WM_DESKTOP, XCB_ATOM_CARDINAL, 0, xcb->ewmh._NET_WM_DESKTOP, XCB_ATOM_CARDINAL,
1 ); 0, 1);
r = xcb_get_property_reply(xcb->connection, cookie, NULL); r = xcb_get_property_reply(xcb->connection, cookie, NULL);
if (r) { if (r) {
if (r->type == XCB_ATOM_CARDINAL) { if (r->type == XCB_ATOM_CARDINAL) {
@@ -570,31 +584,37 @@ static void _window_mode_load_data ( Mode *sw, unsigned int cd )
} }
if (c->wmdesktop != 0xFFFFFFFF) { if (c->wmdesktop != 0xFFFFFFFF) {
if (has_names) { if (has_names) {
if ( ( current_window_manager & WM_PANGO_WORKSPACE_NAMES ) == WM_PANGO_WORKSPACE_NAMES ) { if ((current_window_manager & WM_PANGO_WORKSPACE_NAMES) ==
WM_PANGO_WORKSPACE_NAMES) {
char *output = NULL; char *output = NULL;
if ( pango_parse_markup ( _window_name_list_entry ( names.strings, names.strings_len, if (pango_parse_markup(_window_name_list_entry(names.strings,
c->wmdesktop ), -1, 0, NULL, &output, NULL, NULL ) ) { names.strings_len,
c->wmdesktopstr = g_strdup ( _window_name_list_entry ( names.strings, names.strings_len, c->wmdesktop ) ); c->wmdesktop),
-1, 0, NULL, &output, NULL, NULL)) {
c->wmdesktopstr = g_strdup(_window_name_list_entry(
names.strings, names.strings_len, c->wmdesktop));
c->wmdesktopstr_len = g_utf8_strlen(output, -1); c->wmdesktopstr_len = g_utf8_strlen(output, -1);
pd->wmdn_len = MAX(pd->wmdn_len, c->wmdesktopstr_len); pd->wmdn_len = MAX(pd->wmdn_len, c->wmdesktopstr_len);
g_free(output); g_free(output);
} } else {
else {
c->wmdesktopstr = g_strdup("Invalid name"); c->wmdesktopstr = g_strdup("Invalid name");
pd->wmdn_len = MAX ( pd->wmdn_len, g_utf8_strlen ( c->wmdesktopstr, -1 ) ); pd->wmdn_len =
MAX(pd->wmdn_len, g_utf8_strlen(c->wmdesktopstr, -1));
} }
} else {
c->wmdesktopstr = g_markup_escape_text(
_window_name_list_entry(names.strings, names.strings_len,
c->wmdesktop),
-1);
pd->wmdn_len =
MAX(pd->wmdn_len, g_utf8_strlen(c->wmdesktopstr, -1));
} }
else { } else {
c->wmdesktopstr = g_markup_escape_text ( _window_name_list_entry ( names.strings, names.strings_len, c->wmdesktop ), -1 );
pd->wmdn_len = MAX ( pd->wmdn_len, g_utf8_strlen ( c->wmdesktopstr, -1 ) );
}
}
else {
c->wmdesktopstr = g_strdup_printf("%u", (uint32_t)c->wmdesktop); c->wmdesktopstr = g_strdup_printf("%u", (uint32_t)c->wmdesktop);
pd->wmdn_len = MAX ( pd->wmdn_len, g_utf8_strlen ( c->wmdesktopstr, -1 ) ); pd->wmdn_len =
MAX(pd->wmdn_len, g_utf8_strlen(c->wmdesktopstr, -1));
} }
} } else {
else {
c->wmdesktopstr = g_strdup(""); c->wmdesktopstr = g_strdup("");
pd->wmdn_len = MAX(pd->wmdn_len, g_utf8_strlen(c->wmdesktopstr, -1)); pd->wmdn_len = MAX(pd->wmdn_len, g_utf8_strlen(c->wmdesktopstr, -1));
} }
@@ -611,8 +631,7 @@ static void _window_mode_load_data ( Mode *sw, unsigned int cd )
} }
xcb_ewmh_get_windows_reply_wipe(&clients); xcb_ewmh_get_windows_reply_wipe(&clients);
} }
static int window_mode_init ( Mode *sw ) static int window_mode_init(Mode *sw) {
{
if (mode_get_private_data(sw) == NULL) { if (mode_get_private_data(sw) == NULL) {
ModeModePrivateData *pd = g_malloc0(sizeof(*pd)); ModeModePrivateData *pd = g_malloc0(sizeof(*pd));
pd->window_regex = g_regex_new("{[-\\w]+(:-?[0-9]+)?}", 0, 0, NULL); pd->window_regex = g_regex_new("{[-\\w]+(:-?[0-9]+)?}", 0, 0, NULL);
@@ -624,8 +643,7 @@ static int window_mode_init ( Mode *sw )
} }
return TRUE; return TRUE;
} }
static int window_mode_init_cd ( Mode *sw ) static int window_mode_init_cd(Mode *sw) {
{
if (mode_get_private_data(sw) == NULL) { if (mode_get_private_data(sw) == NULL) {
ModeModePrivateData *pd = g_malloc0(sizeof(*pd)); ModeModePrivateData *pd = g_malloc0(sizeof(*pd));
pd->window_regex = g_regex_new("{[-\\w]+(:-?[0-9]+)?}", 0, 0, NULL); pd->window_regex = g_regex_new("{[-\\w]+(:-?[0-9]+)?}", 0, 0, NULL);
@@ -638,8 +656,7 @@ static int window_mode_init_cd ( Mode *sw )
return TRUE; return TRUE;
} }
static inline int act_on_window ( xcb_window_t window ) static inline int act_on_window(xcb_window_t window) {
{
int retv = TRUE; int retv = TRUE;
char **args = NULL; char **args = NULL;
int argc = 0; int argc = 0;
@@ -647,12 +664,16 @@ static inline int act_on_window ( xcb_window_t window )
g_snprintf(window_regex, sizeof window_regex, "%d", window); g_snprintf(window_regex, sizeof window_regex, "%d", window);
helper_parse_setup ( config.window_command, &args, &argc, "{window}", window_regex, (char *) 0 ); helper_parse_setup(config.window_command, &args, &argc, "{window}",
window_regex, (char *)0);
GError *error = NULL; GError *error = NULL;
g_spawn_async ( NULL, args, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL, NULL, &error ); g_spawn_async(NULL, args, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL, NULL,
&error);
if (error != NULL) { if (error != NULL) {
char *msg = g_strdup_printf ( "Failed to execute action for window: '%s'\nError: '%s'", window_regex, error->message ); char *msg = g_strdup_printf(
"Failed to execute action for window: '%s'\nError: '%s'", window_regex,
error->message);
rofi_view_error_dialog(msg, FALSE); rofi_view_error_dialog(msg, FALSE);
g_free(msg); g_free(msg);
// print error. // print error.
@@ -665,16 +686,15 @@ static inline int act_on_window ( xcb_window_t window )
return retv; return retv;
} }
static ModeMode window_mode_result ( Mode *sw, int mretv, G_GNUC_UNUSED char **input, static ModeMode window_mode_result(Mode *sw, int mretv,
unsigned int selected_line ) G_GNUC_UNUSED char **input,
{ unsigned int selected_line) {
ModeModePrivateData *rmpd = (ModeModePrivateData *)mode_get_private_data(sw); ModeModePrivateData *rmpd = (ModeModePrivateData *)mode_get_private_data(sw);
ModeMode retv = MODE_EXIT; ModeMode retv = MODE_EXIT;
if ((mretv & (MENU_OK))) { if ((mretv & (MENU_OK))) {
if (mretv & MENU_CUSTOM_ACTION) { if (mretv & MENU_CUSTOM_ACTION) {
act_on_window(rmpd->ids->array[selected_line]); act_on_window(rmpd->ids->array[selected_line]);
} } else {
else {
// Disable reverting input focus to previous window. // Disable reverting input focus to previous window.
xcb->focus_revert = 0; xcb->focus_revert = 0;
rofi_view_hide(); rofi_view_hide();
@@ -685,12 +705,15 @@ static ModeMode window_mode_result ( Mode *sw, int mretv, G_GNUC_UNUSED char **i
xcb_get_property_reply_t *r; xcb_get_property_reply_t *r;
// Get the current desktop. // Get the current desktop.
unsigned int current_desktop = 0; unsigned int current_desktop = 0;
xcb_get_property_cookie_t c = xcb_ewmh_get_current_desktop ( &xcb->ewmh, xcb->screen_nbr ); xcb_get_property_cookie_t c =
if ( !xcb_ewmh_get_current_desktop_reply ( &xcb->ewmh, c, &current_desktop, NULL ) ) { xcb_ewmh_get_current_desktop(&xcb->ewmh, xcb->screen_nbr);
if (!xcb_ewmh_get_current_desktop_reply(&xcb->ewmh, c, &current_desktop,
NULL)) {
current_desktop = 0; current_desktop = 0;
} }
cookie = xcb_get_property ( xcb->connection, 0, rmpd->ids->array[selected_line], cookie = xcb_get_property(
xcb->connection, 0, rmpd->ids->array[selected_line],
xcb->ewmh._NET_WM_DESKTOP, XCB_ATOM_CARDINAL, 0, 1); xcb->ewmh._NET_WM_DESKTOP, XCB_ATOM_CARDINAL, 0, 1);
r = xcb_get_property_reply(xcb->connection, cookie, NULL); r = xcb_get_property_reply(xcb->connection, cookie, NULL);
if (r && r->type == XCB_ATOM_CARDINAL) { if (r && r->type == XCB_ATOM_CARDINAL) {
@@ -704,58 +727,65 @@ static ModeMode window_mode_result ( Mode *sw, int mretv, G_GNUC_UNUSED char **i
// If we have to switch the desktop, do // If we have to switch the desktop, do
if (wmdesktop != current_desktop) { if (wmdesktop != current_desktop) {
xcb_ewmh_request_change_current_desktop ( &xcb->ewmh, xcb_ewmh_request_change_current_desktop(&xcb->ewmh, xcb->screen_nbr,
xcb->screen_nbr, wmdesktop, XCB_CURRENT_TIME ); wmdesktop, XCB_CURRENT_TIME);
} }
} }
// Activate the window // Activate the window
xcb_ewmh_request_change_active_window ( &xcb->ewmh, xcb->screen_nbr, rmpd->ids->array[selected_line], xcb_ewmh_request_change_active_window(
XCB_EWMH_CLIENT_SOURCE_TYPE_OTHER, &xcb->ewmh, xcb->screen_nbr, rmpd->ids->array[selected_line],
XCB_CURRENT_TIME, rofi_view_get_window () ); XCB_EWMH_CLIENT_SOURCE_TYPE_OTHER, XCB_CURRENT_TIME,
rofi_view_get_window());
xcb_flush(xcb->connection); xcb_flush(xcb->connection);
} }
} } else if ((mretv & (MENU_ENTRY_DELETE)) == MENU_ENTRY_DELETE) {
else if ( ( mretv & ( MENU_ENTRY_DELETE ) ) == MENU_ENTRY_DELETE ) { xcb_ewmh_request_close_window(
xcb_ewmh_request_close_window ( &( xcb->ewmh ), xcb->screen_nbr, rmpd->ids->array[selected_line], XCB_CURRENT_TIME, XCB_EWMH_CLIENT_SOURCE_TYPE_OTHER ); &(xcb->ewmh), xcb->screen_nbr, rmpd->ids->array[selected_line],
XCB_CURRENT_TIME, XCB_EWMH_CLIENT_SOURCE_TYPE_OTHER);
xcb_flush(xcb->connection); xcb_flush(xcb->connection);
ThemeWidget *wid = rofi_config_find_widget(sw->name, NULL, TRUE); ThemeWidget *wid = rofi_config_find_widget(sw->name, NULL, TRUE);
Property *p = rofi_theme_find_property ( wid, P_BOOLEAN, "close-on-delete", TRUE ); Property *p =
rofi_theme_find_property(wid, P_BOOLEAN, "close-on-delete", TRUE);
if (p && p->type == P_BOOLEAN && p->value.b == FALSE) { if (p && p->type == P_BOOLEAN && p->value.b == FALSE) {
// Force a reload. // Force a reload.
client_free(rmpd->ids->data[selected_line]); client_free(rmpd->ids->data[selected_line]);
g_free(rmpd->ids->data[selected_line]); g_free(rmpd->ids->data[selected_line]);
memmove(&(rmpd->ids->array[selected_line]), &(rmpd->ids->array[selected_line+1]), rmpd->ids->len-selected_line); memmove(&(rmpd->ids->array[selected_line]),
memmove(&(rmpd->ids->data[selected_line]), &(rmpd->ids->data[selected_line+1]), rmpd->ids->len-selected_line); &(rmpd->ids->array[selected_line + 1]),
rmpd->ids->len - selected_line);
memmove(&(rmpd->ids->data[selected_line]),
&(rmpd->ids->data[selected_line + 1]),
rmpd->ids->len - selected_line);
rmpd->ids->len--; rmpd->ids->len--;
retv = RELOAD_DIALOG; retv = RELOAD_DIALOG;
} }
} } else if ((mretv & MENU_CUSTOM_INPUT) && *input != NULL &&
else if ( ( mretv & MENU_CUSTOM_INPUT ) && *input != NULL && *input[0] != '\0' ) { *input[0] != '\0') {
GError *error = NULL; GError *error = NULL;
gboolean run_in_term = ((mretv & MENU_CUSTOM_ACTION) == MENU_CUSTOM_ACTION); gboolean run_in_term = ((mretv & MENU_CUSTOM_ACTION) == MENU_CUSTOM_ACTION);
gsize lf_cmd_size = 0; gsize lf_cmd_size = 0;
gchar *lf_cmd = g_locale_from_utf8(*input, -1, NULL, &lf_cmd_size, &error); gchar *lf_cmd = g_locale_from_utf8(*input, -1, NULL, &lf_cmd_size, &error);
if (error != NULL) { if (error != NULL) {
g_warning ( "Failed to convert command to locale encoding: %s", error->message ); g_warning("Failed to convert command to locale encoding: %s",
error->message);
g_error_free(error); g_error_free(error);
return RELOAD_DIALOG; return RELOAD_DIALOG;
} }
RofiHelperExecuteContext context = {.name = NULL}; RofiHelperExecuteContext context = {.name = NULL};
if ( !helper_execute_command ( NULL, lf_cmd, run_in_term, run_in_term ? &context : NULL ) ) { if (!helper_execute_command(NULL, lf_cmd, run_in_term,
run_in_term ? &context : NULL)) {
retv = RELOAD_DIALOG; retv = RELOAD_DIALOG;
} }
g_free(lf_cmd); g_free(lf_cmd);
} } else if (mretv & MENU_CUSTOM_COMMAND) {
else if ( mretv & MENU_CUSTOM_COMMAND ) {
retv = (mretv & MENU_LOWER_MASK); retv = (mretv & MENU_LOWER_MASK);
} }
return retv; return retv;
} }
static void window_mode_destroy ( Mode *sw ) static void window_mode_destroy(Mode *sw) {
{
ModeModePrivateData *rmpd = (ModeModePrivateData *)mode_get_private_data(sw); ModeModePrivateData *rmpd = (ModeModePrivateData *)mode_get_private_data(sw);
if (rmpd != NULL) { if (rmpd != NULL) {
winlist_free(rmpd->ids); winlist_free(rmpd->ids);
@@ -766,14 +796,13 @@ static void window_mode_destroy ( Mode *sw )
mode_set_private_data(sw, NULL); mode_set_private_data(sw, NULL);
} }
} }
struct arg struct arg {
{
const ModeModePrivateData *pd; const ModeModePrivateData *pd;
client *c; client *c;
}; };
static void helper_eval_add_str ( GString *str, const char *input, int l, int max_len, int nc ) static void helper_eval_add_str(GString *str, const char *input, int l,
{ int max_len, int nc) {
// g_utf8 does not work with NULL string. // g_utf8 does not work with NULL string.
const char *input_nn = input ? input : ""; const char *input_nn = input ? input : "";
// Both l and max_len are in characters, not bytes. // Both l and max_len are in characters, not bytes.
@@ -781,15 +810,13 @@ static void helper_eval_add_str ( GString *str, const char *input, int l, int ma
if (l == 0) { if (l == 0) {
spaces = MAX(0, max_len - nc); spaces = MAX(0, max_len - nc);
g_string_append(str, input_nn); g_string_append(str, input_nn);
} } else {
else {
if (nc > l) { if (nc > l) {
int bl = g_utf8_offset_to_pointer(input_nn, l) - input_nn; int bl = g_utf8_offset_to_pointer(input_nn, l) - input_nn;
char *tmp = g_markup_escape_text(input_nn, bl); char *tmp = g_markup_escape_text(input_nn, bl);
g_string_append(str, tmp); g_string_append(str, tmp);
g_free(tmp); g_free(tmp);
} } else {
else {
spaces = l - nc; spaces = l - nc;
char *tmp = g_markup_escape_text(input_nn, -1); char *tmp = g_markup_escape_text(input_nn, -1);
g_string_append(str, tmp); g_string_append(str, tmp);
@@ -800,8 +827,8 @@ static void helper_eval_add_str ( GString *str, const char *input, int l, int ma
g_string_append_c(str, ' '); g_string_append_c(str, ' ');
} }
} }
static gboolean helper_eval_cb ( const GMatchInfo *info, GString *str, gpointer data ) static gboolean helper_eval_cb(const GMatchInfo *info, GString *str,
{ gpointer data) {
struct arg *d = (struct arg *)data; struct arg *d = (struct arg *)data;
gchar *match; gchar *match;
// Get the match // Get the match
@@ -815,35 +842,37 @@ static gboolean helper_eval_cb ( const GMatchInfo *info, GString *str, gpointer
} }
} }
if (match[1] == 'w') { if (match[1] == 'w') {
helper_eval_add_str ( str, d->c->wmdesktopstr, l, d->pd->wmdn_len, d->c->wmdesktopstr_len ); helper_eval_add_str(str, d->c->wmdesktopstr, l, d->pd->wmdn_len,
} d->c->wmdesktopstr_len);
else if ( match[1] == 'c' ) { } else if (match[1] == 'c') {
helper_eval_add_str ( str, d->c->class, l, d->pd->clf_len, g_utf8_strlen ( d->c->class, -1 ) ); helper_eval_add_str(str, d->c->class, l, d->pd->clf_len,
} g_utf8_strlen(d->c->class, -1));
else if ( match[1] == 't' ) { } else if (match[1] == 't') {
helper_eval_add_str ( str, d->c->title, l, d->pd->title_len, g_utf8_strlen ( d->c->title, -1 ) ); helper_eval_add_str(str, d->c->title, l, d->pd->title_len,
} g_utf8_strlen(d->c->title, -1));
else if ( match[1] == 'n' ) { } else if (match[1] == 'n') {
helper_eval_add_str ( str, d->c->name, l, d->pd->name_len, g_utf8_strlen ( d->c->name, -1 ) ); helper_eval_add_str(str, d->c->name, l, d->pd->name_len,
} g_utf8_strlen(d->c->name, -1));
else if ( match[1] == 'r' ) { } else if (match[1] == 'r') {
helper_eval_add_str ( str, d->c->role, l, d->pd->role_len, g_utf8_strlen ( d->c->role, -1 ) ); helper_eval_add_str(str, d->c->role, l, d->pd->role_len,
g_utf8_strlen(d->c->role, -1));
} }
g_free(match); g_free(match);
} }
return FALSE; return FALSE;
} }
static char * _generate_display_string ( const ModeModePrivateData *pd, client *c ) static char *_generate_display_string(const ModeModePrivateData *pd,
{ client *c) {
struct arg d = {pd, c}; struct arg d = {pd, c};
char *res = g_regex_replace_eval ( pd->window_regex, config.window_format, -1, 0, 0, char *res = g_regex_replace_eval(pd->window_regex, config.window_format, -1,
helper_eval_cb, &d, NULL ); 0, 0, helper_eval_cb, &d, NULL);
return g_strchomp(res); return g_strchomp(res);
} }
static char *_get_display_value ( const Mode *sw, unsigned int selected_line, int *state, G_GNUC_UNUSED GList **list, int get_entry ) static char *_get_display_value(const Mode *sw, unsigned int selected_line,
{ int *state, G_GNUC_UNUSED GList **list,
int get_entry) {
ModeModePrivateData *rmpd = mode_get_private_data(sw); ModeModePrivateData *rmpd = mode_get_private_data(sw);
client *c = window_client(rmpd, rmpd->ids->array[selected_line]); client *c = window_client(rmpd, rmpd->ids->array[selected_line]);
if (c == NULL) { if (c == NULL) {
@@ -869,8 +898,8 @@ static cairo_user_data_key_t data_key;
* \param height The height of the image * \param height The height of the image
* \param data The image's data in ARGB format, will be copied by this function. * \param data The image's data in ARGB format, will be copied by this function.
*/ */
static cairo_surface_t * draw_surface_from_data ( int width, int height, uint32_t *data ) static cairo_surface_t *draw_surface_from_data(int width, int height,
{ uint32_t *data) {
unsigned long int len = width * height; unsigned long int len = width * height;
unsigned long int i; unsigned long int i;
uint32_t *buffer = g_new0(uint32_t, len); uint32_t *buffer = g_new0(uint32_t, len);
@@ -886,18 +915,15 @@ static cairo_surface_t * draw_surface_from_data ( int width, int height, uint32_
buffer[i] = (a << 24) | (r << 16) | (g << 8) | b; buffer[i] = (a << 24) | (r << 16) | (g << 8) | b;
} }
surface = cairo_image_surface_create_for_data ( (unsigned char *) buffer, surface = cairo_image_surface_create_for_data(
CAIRO_FORMAT_ARGB32, (unsigned char *)buffer, CAIRO_FORMAT_ARGB32, width, height, width * 4);
width,
height,
width * 4 );
/* This makes sure that buffer will be freed */ /* This makes sure that buffer will be freed */
cairo_surface_set_user_data(surface, &data_key, buffer, g_free); cairo_surface_set_user_data(surface, &data_key, buffer, g_free);
return surface; return surface;
} }
static cairo_surface_t * ewmh_window_icon_from_reply ( xcb_get_property_reply_t *r, uint32_t preferred_size ) static cairo_surface_t *ewmh_window_icon_from_reply(xcb_get_property_reply_t *r,
{ uint32_t preferred_size) {
uint32_t *data, *end, *found_data = 0; uint32_t *data, *end, *found_data = 0;
uint32_t found_size = 0; uint32_t found_size = 0;
@@ -912,18 +938,20 @@ static cairo_surface_t * ewmh_window_icon_from_reply ( xcb_get_property_reply_t
end = data + r->length; end = data + r->length;
/* Goes over the icon data and picks the icon that best matches the size preference. /* Goes over the icon data and picks the icon that best matches the size
* In case the size match is not exact, picks the closest bigger size if present, * preference. In case the size match is not exact, picks the closest bigger
* closest smaller size otherwise. * size if present, closest smaller size otherwise.
*/ */
while (data + 1 < end) { while (data + 1 < end) {
/* check whether the data size specified by width and height fits into the array we got */ /* check whether the data size specified by width and height fits into the
* array we got */
uint64_t data_size = (uint64_t)data[0] * data[1]; uint64_t data_size = (uint64_t)data[0] * data[1];
if (data_size > (uint64_t)(end - data - 2)) { if (data_size > (uint64_t)(end - data - 2)) {
break; break;
} }
/* use the greater of the two dimensions to match against the preferred size */ /* use the greater of the two dimensions to match against the preferred size
*/
uint32_t size = MAX(data[0], data[1]); uint32_t size = MAX(data[0], data[1]);
/* pick the icon if it's a better match than the one we already have */ /* pick the icon if it's a better match than the one we already have */
@@ -931,9 +959,10 @@ static cairo_surface_t * ewmh_window_icon_from_reply ( xcb_get_property_reply_t
gboolean found_icon_too_large = found_size > preferred_size; gboolean found_icon_too_large = found_size > preferred_size;
gboolean icon_empty = data[0] == 0 || data[1] == 0; gboolean icon_empty = data[0] == 0 || data[1] == 0;
gboolean better_because_bigger = found_icon_too_small && size > found_size; gboolean better_because_bigger = found_icon_too_small && size > found_size;
gboolean better_because_smaller = found_icon_too_large && gboolean better_because_smaller =
size >= preferred_size && size < found_size; found_icon_too_large && size >= preferred_size && size < found_size;
if ( !icon_empty && ( better_because_bigger || better_because_smaller || found_size == 0 ) ) { if (!icon_empty &&
(better_because_bigger || better_because_smaller || found_size == 0)) {
found_data = data; found_data = data;
found_size = size; found_size = size;
} }
@@ -948,18 +977,19 @@ static cairo_surface_t * ewmh_window_icon_from_reply ( xcb_get_property_reply_t
return draw_surface_from_data(found_data[0], found_data[1], found_data + 2); return draw_surface_from_data(found_data[0], found_data[1], found_data + 2);
} }
/** Get NET_WM_ICON. */ /** Get NET_WM_ICON. */
static cairo_surface_t * get_net_wm_icon ( xcb_window_t xid, uint32_t preferred_size ) static cairo_surface_t *get_net_wm_icon(xcb_window_t xid,
{ uint32_t preferred_size) {
xcb_get_property_cookie_t cookie = xcb_get_property_unchecked( xcb_get_property_cookie_t cookie = xcb_get_property_unchecked(
xcb->connection, FALSE, xid, xcb->connection, FALSE, xid, xcb->ewmh._NET_WM_ICON, XCB_ATOM_CARDINAL, 0,
xcb->ewmh._NET_WM_ICON, XCB_ATOM_CARDINAL, 0, UINT32_MAX ); UINT32_MAX);
xcb_get_property_reply_t *r = xcb_get_property_reply ( xcb->connection, cookie, NULL ); xcb_get_property_reply_t *r =
xcb_get_property_reply(xcb->connection, cookie, NULL);
cairo_surface_t *surface = ewmh_window_icon_from_reply(r, preferred_size); cairo_surface_t *surface = ewmh_window_icon_from_reply(r, preferred_size);
free(r); free(r);
return surface; return surface;
} }
static cairo_surface_t *_get_icon ( const Mode *sw, unsigned int selected_line, int size ) static cairo_surface_t *_get_icon(const Mode *sw, unsigned int selected_line,
{ int size) {
ModeModePrivateData *rmpd = mode_get_private_data(sw); ModeModePrivateData *rmpd = mode_get_private_data(sw);
client *c = window_client(rmpd, rmpd->ids->array[selected_line]); client *c = window_client(rmpd, rmpd->ids->array[selected_line]);
if (config.window_thumbnail && c->thumbnail_checked == FALSE) { if (config.window_thumbnail && c->thumbnail_checked == FALSE) {
@@ -981,9 +1011,7 @@ static cairo_surface_t *_get_icon ( const Mode *sw, unsigned int selected_line,
} }
#include "mode-private.h" #include "mode-private.h"
Mode window_mode = Mode window_mode = {.name = "window",
{
.name = "window",
.cfg_name_key = "display-window", .cfg_name_key = "display-window",
._init = window_mode_init, ._init = window_mode_init,
._get_num_entries = window_mode_get_num_entries, ._get_num_entries = window_mode_get_num_entries,
@@ -995,11 +1023,8 @@ Mode window_mode =
._get_completion = NULL, ._get_completion = NULL,
._preprocess_input = NULL, ._preprocess_input = NULL,
.private_data = NULL, .private_data = NULL,
.free = NULL .free = NULL};
}; Mode window_mode_cd = {.name = "windowcd",
Mode window_mode_cd =
{
.name = "windowcd",
.cfg_name_key = "display-windowcd", .cfg_name_key = "display-windowcd",
._init = window_mode_init_cd, ._init = window_mode_init_cd,
._get_num_entries = window_mode_get_num_entries, ._get_num_entries = window_mode_get_num_entries,
@@ -1011,7 +1036,6 @@ Mode window_mode_cd =
._get_completion = NULL, ._get_completion = NULL,
._preprocess_input = NULL, ._preprocess_input = NULL,
.private_data = NULL, .private_data = NULL,
.free = NULL .free = NULL};
};
#endif // WINDOW_MODE #endif // WINDOW_MODE

View File

@@ -29,42 +29,37 @@
/** The log domain for this helper. */ /** The log domain for this helper. */
#define G_LOG_DOMAIN "Helper" #define G_LOG_DOMAIN "Helper"
#include <config.h> #include "config.h"
#include <stdio.h> #include "display.h"
#include <stdlib.h> #include "helper-theme.h"
#include <string.h> #include "rofi.h"
#include <limits.h> #include "settings.h"
#include <unistd.h> #include "view.h"
#include "xcb.h"
#include <ctype.h>
#include <errno.h> #include <errno.h>
#include <fcntl.h> #include <fcntl.h>
#include <glib.h> #include <glib.h>
#include <glib/gstdio.h> #include <glib/gstdio.h>
#include <sys/types.h> #include <limits.h>
#include <pango/pango-fontmap.h>
#include <pango/pango.h>
#include <pango/pangocairo.h>
#include <pwd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/file.h> #include <sys/file.h>
#include <sys/stat.h> #include <sys/stat.h>
#include <pwd.h> #include <sys/types.h>
#include <ctype.h> #include <unistd.h>
#include <pango/pango.h>
#include <pango/pango-fontmap.h>
#include <pango/pangocairo.h>
#include "display.h"
#include "xcb.h"
#include "helper.h"
#include "helper-theme.h"
#include "settings.h"
#include "rofi.h"
#include "view.h"
/** /**
* Textual description of positioning rofi. * Textual description of positioning rofi.
*/ */
const char *const monitor_position_entries[] = { const char *const monitor_position_entries[] = {
"on focused monitor", "on focused monitor", "on focused window", "at mouse pointer",
"on focused window", "on monitor with focused window", "on monitor that has mouse pointer"};
"at mouse pointer",
"on monitor with focused window",
"on monitor that has mouse pointer"
};
/** copy of the argc for use in commandline argument parser. */ /** copy of the argc for use in commandline argument parser. */
int stored_argc = 0; int stored_argc = 0;
/** copy of the argv pointer for use in the commandline argument parser */ /** copy of the argv pointer for use in the commandline argument parser */
@@ -72,14 +67,12 @@ char **stored_argv = NULL;
char *helper_string_replace_if_exists_v(char *string, GHashTable *h); char *helper_string_replace_if_exists_v(char *string, GHashTable *h);
void cmd_set_arguments ( int argc, char **argv ) void cmd_set_arguments(int argc, char **argv) {
{
stored_argc = argc; stored_argc = argc;
stored_argv = argv; stored_argv = argv;
} }
int helper_parse_setup ( char * string, char ***output, int *length, ... ) int helper_parse_setup(char *string, char ***output, int *length, ...) {
{
GError *error = NULL; GError *error = NULL;
GHashTable *h; GHashTable *h;
h = g_hash_table_new(g_str_hash, g_str_equal); h = g_hash_table_new(g_str_hash, g_str_equal);
@@ -113,7 +106,8 @@ int helper_parse_setup ( char * string, char ***output, int *length, ... )
g_free(res); g_free(res);
// Throw error if shell parsing fails. // Throw error if shell parsing fails.
if (error) { if (error) {
char *msg = g_strdup_printf ( "Failed to parse: '%s'\nError: '%s'", string, error->message ); char *msg = g_strdup_printf("Failed to parse: '%s'\nError: '%s'", string,
error->message);
rofi_view_error_dialog(msg, FALSE); rofi_view_error_dialog(msg, FALSE);
g_free(msg); g_free(msg);
// print error. // print error.
@@ -122,8 +116,7 @@ int helper_parse_setup ( char * string, char ***output, int *length, ... )
return FALSE; return FALSE;
} }
void helper_tokenize_free ( rofi_int_matcher ** tokens ) void helper_tokenize_free(rofi_int_matcher **tokens) {
{
for (size_t i = 0; tokens && tokens[i]; i++) { for (size_t i = 0; tokens && tokens[i]; i++) {
g_regex_unref((GRegex *)tokens[i]->regex); g_regex_unref((GRegex *)tokens[i]->regex);
g_free(tokens[i]); g_free(tokens[i]);
@@ -131,16 +124,14 @@ void helper_tokenize_free ( rofi_int_matcher ** tokens )
g_free(tokens); g_free(tokens);
} }
static gchar *glob_to_regex ( const char *input ) static gchar *glob_to_regex(const char *input) {
{
gchar *r = g_regex_escape_string(input, -1); gchar *r = g_regex_escape_string(input, -1);
size_t str_l = strlen(r); size_t str_l = strlen(r);
for (size_t i = 0; i < str_l; i++) { for (size_t i = 0; i < str_l; i++) {
if (r[i] == '\\') { if (r[i] == '\\') {
if (r[i + 1] == '*') { if (r[i + 1] == '*') {
r[i] = '.'; r[i] = '.';
} } else if (r[i + 1] == '?') {
else if ( r[i + 1] == '?' ) {
r[i + 1] = 'S'; r[i + 1] = 'S';
} }
i++; i++;
@@ -148,8 +139,7 @@ static gchar *glob_to_regex ( const char *input )
} }
return r; return r;
} }
static gchar *fuzzy_to_regex ( const char * input ) static gchar *fuzzy_to_regex(const char *input) {
{
GString *str = g_string_new(""); GString *str = g_string_new("");
gchar *r = g_regex_escape_string(input, -1); gchar *r = g_regex_escape_string(input, -1);
gchar *iter; gchar *iter;
@@ -157,8 +147,7 @@ static gchar *fuzzy_to_regex ( const char * input )
for (iter = r; iter && *iter != '\0'; iter = g_utf8_next_char(iter)) { for (iter = r; iter && *iter != '\0'; iter = g_utf8_next_char(iter)) {
if (first) { if (first) {
g_string_append(str, "("); g_string_append(str, "(");
} } else {
else {
g_string_append(str, ".*?("); g_string_append(str, ".*?(");
} }
if (*iter == '\\') { if (*iter == '\\') {
@@ -179,29 +168,31 @@ static gchar *fuzzy_to_regex ( const char * input )
return retv; return retv;
} }
static gchar *prefix_regex ( const char * input ) static gchar *prefix_regex(const char *input) {
{
gchar *r = g_regex_escape_string(input, -1); gchar *r = g_regex_escape_string(input, -1);
char *retv = g_strconcat("\\b", r, NULL); char *retv = g_strconcat("\\b", r, NULL);
g_free(r); g_free(r);
return retv; return retv;
} }
static char *utf8_helper_simplify_string ( const char *s ) static char *utf8_helper_simplify_string(const char *s) {
{ gunichar buf2[G_UNICHAR_MAX_DECOMPOSITION_LENGTH] = {
gunichar buf2[G_UNICHAR_MAX_DECOMPOSITION_LENGTH] = { 0, }; 0,
char buf[6] = { 0, }; };
char buf[6] = {
0,
};
// Compose the string in maximally composed form. // Compose the string in maximally composed form.
char *str = g_malloc0((g_utf8_strlen(s, 0) * 6 + 2)); char *str = g_malloc0((g_utf8_strlen(s, 0) * 6 + 2));
char *striter = str; char *striter = str;
for (const char *iter = s; iter && *iter; iter = g_utf8_next_char(iter)) { for (const char *iter = s; iter && *iter; iter = g_utf8_next_char(iter)) {
gunichar uc = g_utf8_get_char(iter); gunichar uc = g_utf8_get_char(iter);
int l = 0; int l = 0;
gsize dl = g_unichar_fully_decompose ( uc, FALSE, buf2, G_UNICHAR_MAX_DECOMPOSITION_LENGTH ); gsize dl = g_unichar_fully_decompose(uc, FALSE, buf2,
G_UNICHAR_MAX_DECOMPOSITION_LENGTH);
if (dl) { if (dl) {
l = g_unichar_to_utf8(buf2[0], buf); l = g_unichar_to_utf8(buf2[0], buf);
} } else {
else {
l = g_unichar_to_utf8(uc, buf); l = g_unichar_to_utf8(uc, buf);
} }
memcpy(striter, buf, l); memcpy(striter, buf, l);
@@ -212,23 +203,22 @@ static char *utf8_helper_simplify_string ( const char *s )
} }
// Macro for quickly generating regex for matching. // Macro for quickly generating regex for matching.
static inline GRegex * R ( const char *s, int case_sensitive ) static inline GRegex *R(const char *s, int case_sensitive) {
{
if (config.normalize_match) { if (config.normalize_match) {
char *str = utf8_helper_simplify_string(s); char *str = utf8_helper_simplify_string(s);
GRegex *r = g_regex_new ( str, G_REGEX_OPTIMIZE | ( ( case_sensitive ) ? 0 : G_REGEX_CASELESS ), 0, NULL ); GRegex *r = g_regex_new(
str, G_REGEX_OPTIMIZE | ((case_sensitive) ? 0 : G_REGEX_CASELESS), 0,
NULL);
g_free(str); g_free(str);
return r; return r;
} }
else { return g_regex_new(
return g_regex_new ( s, G_REGEX_OPTIMIZE | ( ( case_sensitive ) ? 0 : G_REGEX_CASELESS ), 0, NULL ); s, G_REGEX_OPTIMIZE | ((case_sensitive) ? 0 : G_REGEX_CASELESS), 0, NULL);
}
} }
static rofi_int_matcher * create_regex ( const char *input, int case_sensitive ) static rofi_int_matcher *create_regex(const char *input, int case_sensitive) {
{
GRegex *retv = NULL; GRegex *retv = NULL;
gchar *r; gchar *r;
rofi_int_matcher *rv = g_malloc0(sizeof(rofi_int_matcher)); rofi_int_matcher *rv = g_malloc0(sizeof(rofi_int_matcher));
@@ -236,8 +226,7 @@ static rofi_int_matcher * create_regex ( const char *input, int case_sensitive )
rv->invert = 1; rv->invert = 1;
input++; input++;
} }
switch ( config.matching_method ) switch (config.matching_method) {
{
case MM_GLOB: case MM_GLOB:
r = glob_to_regex(input); r = glob_to_regex(input);
retv = R(r, case_sensitive); retv = R(r, case_sensitive);
@@ -270,8 +259,7 @@ static rofi_int_matcher * create_regex ( const char *input, int case_sensitive )
rv->regex = retv; rv->regex = retv;
return rv; return rv;
} }
rofi_int_matcher **helper_tokenize ( const char *input, int case_sensitive ) rofi_int_matcher **helper_tokenize(const char *input, int case_sensitive) {
{
if (input == NULL) { if (input == NULL) {
return NULL; return NULL;
} }
@@ -297,7 +285,8 @@ rofi_int_matcher **helper_tokenize ( const char *input, int case_sensitive )
// Iterate over tokens. // Iterate over tokens.
// strtok should still be valid for utf8. // strtok should still be valid for utf8.
const char *const sep = " "; const char *const sep = " ";
for ( token = strtok_r ( str, sep, &saveptr ); token != NULL; token = strtok_r ( NULL, sep, &saveptr ) ) { for (token = strtok_r(str, sep, &saveptr); token != NULL;
token = strtok_r(NULL, sep, &saveptr)) {
retv = g_realloc(retv, sizeof(rofi_int_matcher *) * (num_tokens + 2)); retv = g_realloc(retv, sizeof(rofi_int_matcher *) * (num_tokens + 2));
retv[num_tokens] = create_regex(token, case_sensitive); retv[num_tokens] = create_regex(token, case_sensitive);
retv[num_tokens + 1] = NULL; retv[num_tokens + 1] = NULL;
@@ -309,8 +298,7 @@ rofi_int_matcher **helper_tokenize ( const char *input, int case_sensitive )
} }
// cli arg handling // cli arg handling
int find_arg ( const char * const key ) int find_arg(const char *const key) {
{
int i; int i;
for (i = 0; i < stored_argc && strcasecmp(stored_argv[i], key); i++) { for (i = 0; i < stored_argc && strcasecmp(stored_argv[i], key); i++) {
@@ -319,8 +307,7 @@ int find_arg ( const char * const key )
return i < stored_argc ? i : -1; return i < stored_argc ? i : -1;
} }
int find_arg_str ( const char * const key, char** val ) int find_arg_str(const char *const key, char **val) {
{
int i = find_arg(key); int i = find_arg(key);
if (val != NULL && i > 0 && i < stored_argc - 1) { if (val != NULL && i > 0 && i < stored_argc - 1) {
@@ -330,8 +317,7 @@ int find_arg_str ( const char * const key, char** val )
return FALSE; return FALSE;
} }
const char ** find_arg_strv ( const char *const key ) const char **find_arg_strv(const char *const key) {
{
const char **retv = NULL; const char **retv = NULL;
int length = 0; int length = 0;
for (int i = 0; i < stored_argc; i++) { for (int i = 0; i < stored_argc; i++) {
@@ -351,8 +337,7 @@ const char ** find_arg_strv ( const char *const key )
return retv; return retv;
} }
int find_arg_int ( const char * const key, int *val ) int find_arg_int(const char *const key, int *val) {
{
int i = find_arg(key); int i = find_arg(key);
if (val != NULL && i > 0 && i < (stored_argc - 1)) { if (val != NULL && i > 0 && i < (stored_argc - 1)) {
@@ -361,8 +346,7 @@ int find_arg_int ( const char * const key, int *val )
} }
return FALSE; return FALSE;
} }
int find_arg_uint ( const char * const key, unsigned int *val ) int find_arg_uint(const char *const key, unsigned int *val) {
{
int i = find_arg(key); int i = find_arg(key);
if (val != NULL && i > 0 && i < (stored_argc - 1)) { if (val != NULL && i > 0 && i < (stored_argc - 1)) {
@@ -372,8 +356,7 @@ int find_arg_uint ( const char * const key, unsigned int *val )
return FALSE; return FALSE;
} }
char helper_parse_char ( const char *arg ) char helper_parse_char(const char *arg) {
{
const size_t len = strlen(arg); const size_t len = strlen(arg);
// If the length is 1, it is not escaped. // If the length is 1, it is not escaped.
if (len == 1) { if (len == 1) {
@@ -381,26 +364,34 @@ char helper_parse_char ( const char *arg )
} }
// If the length is 2 and the first character is '\', we unescape it. // If the length is 2 and the first character is '\', we unescape it.
if (len == 2 && arg[0] == '\\') { if (len == 2 && arg[0] == '\\') {
switch ( arg[1] ) switch (arg[1]) {
{
// New line // New line
case 'n': return '\n'; case 'n':
return '\n';
// Bell // Bell
case 'a': return '\a'; case 'a':
return '\a';
// Backspace // Backspace
case 'b': return '\b'; case 'b':
return '\b';
// Tab // Tab
case 't': return '\t'; case 't':
return '\t';
// Vertical tab // Vertical tab
case 'v': return '\v'; case 'v':
return '\v';
// Form feed // Form feed
case 'f': return '\f'; case 'f':
return '\f';
// Carriage return // Carriage return
case 'r': return '\r'; case 'r':
return '\r';
// Forward slash // Forward slash
case '\\': return '\\'; case '\\':
return '\\';
// 0 line. // 0 line.
case '0': return '\0'; case '0':
return '\0';
default: default:
break; break;
} }
@@ -413,8 +404,7 @@ char helper_parse_char ( const char *arg )
return '\n'; return '\n';
} }
int find_arg_char ( const char * const key, char *val ) int find_arg_char(const char *const key, char *val) {
{
int i = find_arg(key); int i = find_arg(key);
if (val != NULL && i > 0 && i < (stored_argc - 1)) { if (val != NULL && i > 0 && i < (stored_argc - 1)) {
@@ -424,8 +414,10 @@ int find_arg_char ( const char * const key, char *val )
return FALSE; return FALSE;
} }
PangoAttrList *helper_token_match_get_pango_attr ( RofiHighlightColorStyle th, rofi_int_matcher**tokens, const char *input, PangoAttrList *retv ) PangoAttrList *helper_token_match_get_pango_attr(RofiHighlightColorStyle th,
{ rofi_int_matcher **tokens,
const char *input,
PangoAttrList *retv) {
// Disable highlighting for normalize match, not supported atm. // Disable highlighting for normalize match, not supported atm.
if (config.normalize_match) { if (config.normalize_match) {
return retv; return retv;
@@ -450,7 +442,8 @@ PangoAttrList *helper_token_match_get_pango_attr ( RofiHighlightColorStyle th, r
pango_attr_list_insert(retv, pa); pango_attr_list_insert(retv, pa);
} }
if (th.style & ROFI_HL_UNDERLINE) { if (th.style & ROFI_HL_UNDERLINE) {
PangoAttribute *pa = pango_attr_underline_new ( PANGO_UNDERLINE_SINGLE ); PangoAttribute *pa =
pango_attr_underline_new(PANGO_UNDERLINE_SINGLE);
pa->start_index = start; pa->start_index = start;
pa->end_index = end; pa->end_index = end;
pango_attr_list_insert(retv, pa); pango_attr_list_insert(retv, pa);
@@ -462,7 +455,8 @@ PangoAttrList *helper_token_match_get_pango_attr ( RofiHighlightColorStyle th, r
pango_attr_list_insert(retv, pa); pango_attr_list_insert(retv, pa);
} }
if (th.style & ROFI_HL_SMALL_CAPS) { if (th.style & ROFI_HL_SMALL_CAPS) {
PangoAttribute *pa = pango_attr_variant_new ( PANGO_VARIANT_SMALL_CAPS ); PangoAttribute *pa =
pango_attr_variant_new(PANGO_VARIANT_SMALL_CAPS);
pa->start_index = start; pa->start_index = start;
pa->end_index = end; pa->end_index = end;
pango_attr_list_insert(retv, pa); pango_attr_list_insert(retv, pa);
@@ -475,8 +469,7 @@ PangoAttrList *helper_token_match_get_pango_attr ( RofiHighlightColorStyle th, r
} }
if (th.style & ROFI_HL_COLOR) { if (th.style & ROFI_HL_COLOR) {
PangoAttribute *pa = pango_attr_foreground_new( PangoAttribute *pa = pango_attr_foreground_new(
th.color.red * 65535, th.color.red * 65535, th.color.green * 65535,
th.color.green * 65535,
th.color.blue * 65535); th.color.blue * 65535);
pa->start_index = start; pa->start_index = start;
pa->end_index = end; pa->end_index = end;
@@ -498,8 +491,7 @@ PangoAttrList *helper_token_match_get_pango_attr ( RofiHighlightColorStyle th, r
return retv; return retv;
} }
int helper_token_match ( rofi_int_matcher* const *tokens, const char *input ) int helper_token_match(rofi_int_matcher *const *tokens, const char *input) {
{
int match = TRUE; int match = TRUE;
// Do a tokenized match. // Do a tokenized match.
if (tokens) { if (tokens) {
@@ -510,8 +502,7 @@ int helper_token_match ( rofi_int_matcher* const *tokens, const char *input )
match ^= tokens[j]->invert; match ^= tokens[j]->invert;
} }
g_free(r); g_free(r);
} } else {
else {
for (int j = 0; match && tokens[j]; j++) { for (int j = 0; match && tokens[j]; j++) {
match = g_regex_match(tokens[j]->regex, input, 0, NULL); match = g_regex_match(tokens[j]->regex, input, 0, NULL);
match ^= tokens[j]->invert; match ^= tokens[j]->invert;
@@ -521,18 +512,19 @@ int helper_token_match ( rofi_int_matcher* const *tokens, const char *input )
return match; return match;
} }
int execute_generator ( const char * cmd ) int execute_generator(const char *cmd) {
{
char **args = NULL; char **args = NULL;
int argv = 0; int argv = 0;
helper_parse_setup(config.run_command, &args, &argv, "{cmd}", cmd, (char *)0); helper_parse_setup(config.run_command, &args, &argv, "{cmd}", cmd, (char *)0);
int fd = -1; int fd = -1;
GError *error = NULL; GError *error = NULL;
g_spawn_async_with_pipes ( NULL, args, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL, NULL, NULL, &fd, NULL, &error ); g_spawn_async_with_pipes(NULL, args, NULL, G_SPAWN_SEARCH_PATH, NULL, NULL,
NULL, NULL, &fd, NULL, &error);
if (error != NULL) { if (error != NULL) {
char *msg = g_strdup_printf ( "Failed to execute: '%s'\nError: '%s'", cmd, error->message ); char *msg = g_strdup_printf("Failed to execute: '%s'\nError: '%s'", cmd,
error->message);
rofi_view_error_dialog(msg, FALSE); rofi_view_error_dialog(msg, FALSE);
g_free(msg); g_free(msg);
// print error. // print error.
@@ -543,8 +535,7 @@ int execute_generator ( const char * cmd )
return fd; return fd;
} }
int create_pid_file ( const char *pidfile ) int create_pid_file(const char *pidfile) {
{
if (pidfile == NULL) { if (pidfile == NULL) {
return -1; return -1;
} }
@@ -582,8 +573,7 @@ int create_pid_file ( const char *pidfile )
return fd; return fd;
} }
void remove_pid_file ( int fd ) void remove_pid_file(int fd) {
{
if (fd >= 0) { if (fd >= 0) {
if (close(fd)) { if (close(fd)) {
g_warning("Failed to close pidfile: '%s'", g_strerror(errno)); g_warning("Failed to close pidfile: '%s'", g_strerror(errno));
@@ -591,13 +581,13 @@ void remove_pid_file ( int fd )
} }
} }
gboolean helper_validate_font ( PangoFontDescription *pfd, const char *font ) gboolean helper_validate_font(PangoFontDescription *pfd, const char *font) {
{
const char *fam = pango_font_description_get_family(pfd); const char *fam = pango_font_description_get_family(pfd);
int size = pango_font_description_get_size(pfd); int size = pango_font_description_get_size(pfd);
if (fam == NULL || size == 0) { if (fam == NULL || size == 0) {
g_debug("Pango failed to parse font: '%s'", font); g_debug("Pango failed to parse font: '%s'", font);
g_debug ( "Got family: <b>%s</b> at size: <b>%d</b>", fam ? fam : "{unknown}", size ); g_debug("Got family: <b>%s</b> at size: <b>%d</b>", fam ? fam : "{unknown}",
size);
return FALSE; return FALSE;
} }
return TRUE; return TRUE;
@@ -607,26 +597,26 @@ gboolean helper_validate_font ( PangoFontDescription *pfd, const char *font )
* Do some input validation, especially the first few could break things. * Do some input validation, especially the first few could break things.
* It is good to catch them beforehand. * It is good to catch them beforehand.
* *
* This functions exits the program with 1 when it finds an invalid configuration. * This functions exits the program with 1 when it finds an invalid
* configuration.
*/ */
int config_sanity_check ( void ) int config_sanity_check(void) {
{
int found_error = FALSE; int found_error = FALSE;
GString *msg = g_string_new ( GString *msg =
"<big><b>The configuration failed to validate:</b></big>\n" ); g_string_new("<big><b>The configuration failed to validate:</b></big>\n");
if (config.sorting_method) { if (config.sorting_method) {
if (g_strcmp0(config.sorting_method, "normal") == 0) { if (g_strcmp0(config.sorting_method, "normal") == 0) {
config.sorting_method_enum = SORT_NORMAL; config.sorting_method_enum = SORT_NORMAL;
} } else if (g_strcmp0(config.sorting_method, "levenshtein") == 0) {
else if ( g_strcmp0 ( config.sorting_method, "levenshtein" ) == 0 ) {
config.sorting_method_enum = SORT_NORMAL; config.sorting_method_enum = SORT_NORMAL;
} } else if (g_strcmp0(config.sorting_method, "fzf") == 0) {
else if ( g_strcmp0 ( config.sorting_method, "fzf" ) == 0 ) {
config.sorting_method_enum = SORT_FZF; config.sorting_method_enum = SORT_FZF;
} } else {
else { g_string_append_printf(
g_string_append_printf ( msg, "\t<b>config.sorting_method</b>=%s is not a valid sorting strategy.\nValid options are: normal or fzf.\n", msg,
"\t<b>config.sorting_method</b>=%s is not a valid sorting "
"strategy.\nValid options are: normal or fzf.\n",
config.sorting_method); config.sorting_method);
found_error = 1; found_error = 1;
} }
@@ -635,34 +625,37 @@ int config_sanity_check ( void )
if (config.matching) { if (config.matching) {
if (g_strcmp0(config.matching, "regex") == 0) { if (g_strcmp0(config.matching, "regex") == 0) {
config.matching_method = MM_REGEX; config.matching_method = MM_REGEX;
} } else if (g_strcmp0(config.matching, "glob") == 0) {
else if ( g_strcmp0 ( config.matching, "glob" ) == 0 ) {
config.matching_method = MM_GLOB; config.matching_method = MM_GLOB;
} } else if (g_strcmp0(config.matching, "fuzzy") == 0) {
else if ( g_strcmp0 ( config.matching, "fuzzy" ) == 0 ) {
config.matching_method = MM_FUZZY; config.matching_method = MM_FUZZY;
} } else if (g_strcmp0(config.matching, "normal") == 0) {
else if ( g_strcmp0 ( config.matching, "normal" ) == 0 ) { config.matching_method = MM_NORMAL;
config.matching_method = MM_NORMAL;; ;
} } else if (g_strcmp0(config.matching, "prefix") == 0) {
else if ( g_strcmp0 ( config.matching, "prefix" ) == 0 ) {
config.matching_method = MM_PREFIX; config.matching_method = MM_PREFIX;
} } else {
else { g_string_append_printf(msg,
g_string_append_printf ( msg, "\t<b>config.matching</b>=%s is not a valid matching strategy.\nValid options are: glob, regex, fuzzy, prefix or normal.\n", "\t<b>config.matching</b>=%s is not a valid "
"matching strategy.\nValid options are: glob, "
"regex, fuzzy, prefix or normal.\n",
config.matching); config.matching);
found_error = 1; found_error = 1;
} }
} }
if (config.element_height < 1) { if (config.element_height < 1) {
g_string_append_printf ( msg, "\t<b>config.element_height</b>=%d is invalid. An element needs to be at least 1 line high.\n", g_string_append_printf(msg,
"\t<b>config.element_height</b>=%d is invalid. An "
"element needs to be at least 1 line high.\n",
config.element_height); config.element_height);
config.element_height = 1; config.element_height = 1;
found_error = TRUE; found_error = TRUE;
} }
if (!(config.location >= 0 && config.location <= 8)) { if (!(config.location >= 0 && config.location <= 8)) {
g_string_append_printf ( msg, "\t<b>config.location</b>=%d is invalid. Value should be between %d and %d.\n", g_string_append_printf(msg,
"\t<b>config.location</b>=%d is invalid. Value "
"should be between %d and %d.\n",
config.location, 0, 8); config.location, 0, 8);
config.location = WL_CENTER; config.location = WL_CENTER;
found_error = 1; found_error = 1;
@@ -679,18 +672,23 @@ int config_sanity_check ( void )
name = monitor_position_entries[index - 1]; name = monitor_position_entries[index - 1];
} }
} }
g_string_append_printf ( msg, "\t<b>config.monitor</b>=%s Could not find monitor.\n", name ); g_string_append_printf(
msg, "\t<b>config.monitor</b>=%s Could not find monitor.\n", name);
found_error = TRUE; found_error = TRUE;
} }
} }
if (config.menu_font) { if (config.menu_font) {
PangoFontDescription *pfd = pango_font_description_from_string ( config.menu_font ); PangoFontDescription *pfd =
pango_font_description_from_string(config.menu_font);
const char *fam = pango_font_description_get_family(pfd); const char *fam = pango_font_description_get_family(pfd);
int size = pango_font_description_get_size(pfd); int size = pango_font_description_get_size(pfd);
if (fam == NULL || size == 0) { if (fam == NULL || size == 0) {
g_string_append_printf ( msg, "Pango failed to parse font: '%s'\n", config.menu_font ); g_string_append_printf(msg, "Pango failed to parse font: '%s'\n",
g_string_append_printf ( msg, "Got font family: <b>%s</b> at size <b>%d</b>\n", fam ? fam : "{unknown}", size ); config.menu_font);
g_string_append_printf(msg,
"Got font family: <b>%s</b> at size <b>%d</b>\n",
fam ? fam : "{unknown}", size);
config.menu_font = NULL; config.menu_font = NULL;
found_error = TRUE; found_error = TRUE;
} }
@@ -712,8 +710,7 @@ int config_sanity_check ( void )
return FALSE; return FALSE;
} }
char *rofi_expand_path ( const char *input ) char *rofi_expand_path(const char *input) {
{
char **str = g_strsplit(input, G_DIR_SEPARATOR_S, -1); char **str = g_strsplit(input, G_DIR_SEPARATOR_S, -1);
for (unsigned int i = 0; str && str[i]; i++) { for (unsigned int i = 0; str && str[i]; i++) {
// Replace ~ with current user homedir. // Replace ~ with current user homedir.
@@ -728,8 +725,7 @@ char *rofi_expand_path ( const char *input )
g_free(str[i]); g_free(str[i]);
str[i] = g_strdup(p->pw_dir); str[i] = g_strdup(p->pw_dir);
} }
} } else if (i == 0) {
else if ( i == 0 ) {
char *s = str[i]; char *s = str[i];
if (input[0] == G_DIR_SEPARATOR) { if (input[0] == G_DIR_SEPARATOR) {
str[i] = g_strdup_printf("%s%s", G_DIR_SEPARATOR_S, s); str[i] = g_strdup_printf("%s%s", G_DIR_SEPARATOR_S, s);
@@ -743,10 +739,11 @@ char *rofi_expand_path ( const char *input )
} }
/** Return the minimum value of a,b,c */ /** Return the minimum value of a,b,c */
#define MIN3( a, b, c ) ( ( a ) < ( b ) ? ( ( a ) < ( c ) ? ( a ) : ( c ) ) : ( ( b ) < ( c ) ? ( b ) : ( c ) ) ) #define MIN3(a, b, c) \
((a) < (b) ? ((a) < (c) ? (a) : (c)) : ((b) < (c) ? (b) : (c)))
unsigned int levenshtein ( const char *needle, const glong needlelen, const char *haystack, const glong haystacklen ) unsigned int levenshtein(const char *needle, const glong needlelen,
{ const char *haystack, const glong haystacklen) {
if (needlelen == G_MAXLONG) { if (needlelen == G_MAXLONG) {
// String to long, we cannot handle this. // String to long, we cannot handle this.
return UINT_MAX; return UINT_MAX;
@@ -755,8 +752,8 @@ unsigned int levenshtein ( const char *needle, const glong needlelen, const char
for (glong y = 0; y < needlelen; y++) { for (glong y = 0; y < needlelen; y++) {
column[y] = y; column[y] = y;
} }
// Removed out of the loop, otherwise static code analyzers think it is unset.. silly but true. // Removed out of the loop, otherwise static code analyzers think it is
// old loop: for ( glong y = 0; y <= needlelen; y++) // unset.. silly but true. old loop: for ( glong y = 0; y <= needlelen; y++)
column[needlelen] = needlelen; column[needlelen] = needlelen;
for (glong x = 1; x <= haystacklen; x++) { for (glong x = 1; x <= haystacklen; x++) {
const char *needles = needle; const char *needles = needle;
@@ -771,7 +768,8 @@ unsigned int levenshtein ( const char *needle, const glong needlelen, const char
needlec = g_unichar_tolower(needlec); needlec = g_unichar_tolower(needlec);
} }
unsigned int olddiag = column[y]; unsigned int olddiag = column[y];
column[y] = MIN3 ( column[y] + 1, column[y - 1] + 1, lastdiag + ( needlec == haystackc ? 0 : 1 ) ); column[y] = MIN3(column[y] + 1, column[y - 1] + 1,
lastdiag + (needlec == haystackc ? 0 : 1));
lastdiag = olddiag; lastdiag = olddiag;
needles = g_utf8_next_char(needles); needles = g_utf8_next_char(needles);
} }
@@ -780,14 +778,13 @@ unsigned int levenshtein ( const char *needle, const glong needlelen, const char
return column[needlelen]; return column[needlelen];
} }
char * rofi_latin_to_utf8_strdup ( const char *input, gssize length ) char *rofi_latin_to_utf8_strdup(const char *input, gssize length) {
{
gsize slength = 0; gsize slength = 0;
return g_convert_with_fallback ( input, length, "UTF-8", "latin1", "\uFFFD", NULL, &slength, NULL ); return g_convert_with_fallback(input, length, "UTF-8", "latin1", "\uFFFD",
NULL, &slength, NULL);
} }
gchar *rofi_escape_markup ( gchar *text ) gchar *rofi_escape_markup(gchar *text) {
{
if (text == NULL) { if (text == NULL) {
return NULL; return NULL;
} }
@@ -796,8 +793,7 @@ gchar *rofi_escape_markup ( gchar *text )
return ret; return ret;
} }
char * rofi_force_utf8 ( const gchar *data, ssize_t length ) char *rofi_force_utf8(const gchar *data, ssize_t length) {
{
if (data == NULL) { if (data == NULL) {
return NULL; return NULL;
} }
@@ -853,8 +849,7 @@ char * rofi_force_utf8 ( const gchar *data, ssize_t length )
/** /**
* Character classification. * Character classification.
*/ */
enum CharClass enum CharClass {
{
/* Lower case */ /* Lower case */
LOWER, LOWER,
/* Upper case */ /* Upper case */
@@ -870,8 +865,7 @@ enum CharClass
* *
* @returns the class of the character c. * @returns the class of the character c.
*/ */
static enum CharClass rofi_scorer_get_character_class ( gunichar c ) static enum CharClass rofi_scorer_get_character_class(gunichar c) {
{
if (g_unichar_islower(c)) { if (g_unichar_islower(c)) {
return LOWER; return LOWER;
} }
@@ -892,13 +886,11 @@ static enum CharClass rofi_scorer_get_character_class ( gunichar c )
* *
* @returns score of the transition. * @returns score of the transition.
*/ */
static int rofi_scorer_get_score_for ( enum CharClass prev, enum CharClass curr ) static int rofi_scorer_get_score_for(enum CharClass prev, enum CharClass curr) {
{
if (prev == NON_WORD && curr != NON_WORD) { if (prev == NON_WORD && curr != NON_WORD) {
return WORD_START_SCORE; return WORD_START_SCORE;
} }
if ( ( prev == LOWER && curr == UPPER ) || if ((prev == LOWER && curr == UPPER) || (prev != DIGIT && curr == DIGIT)) {
( prev != DIGIT && curr == DIGIT ) ) {
return CAMEL_SCORE; return CAMEL_SCORE;
} }
if (curr == NON_WORD) { if (curr == NON_WORD) {
@@ -907,8 +899,8 @@ static int rofi_scorer_get_score_for ( enum CharClass prev, enum CharClass curr
return 0; return 0;
} }
int rofi_scorer_fuzzy_evaluate ( const char *pattern, glong plen, const char *str, glong slen ) int rofi_scorer_fuzzy_evaluate(const char *pattern, glong plen, const char *str,
{ glong slen) {
if (slen > FUZZY_SCORER_MAX_LENGTH) { if (slen > FUZZY_SCORER_MAX_LENGTH) {
return -MIN_SCORE; return -MIN_SCORE;
} }
@@ -921,8 +913,8 @@ int rofi_scorer_fuzzy_evaluate ( const char *pattern, glong plen, const char *st
int *score = g_malloc_n(slen, sizeof(int)); int *score = g_malloc_n(slen, sizeof(int));
// dp[i]: maximum value by aligning pattern[0..pi] to str[0..si] // dp[i]: maximum value by aligning pattern[0..pi] to str[0..si]
int *dp = g_malloc_n(slen, sizeof(int)); int *dp = g_malloc_n(slen, sizeof(int));
// uleft: value of the upper left cell; ulefts: maximum value of uleft and cells on the left. The arbitrary initial // uleft: value of the upper left cell; ulefts: maximum value of uleft and
// values suppress warnings. // cells on the left. The arbitrary initial values suppress warnings.
int uleft = 0, ulefts = 0, left, lefts; int uleft = 0, ulefts = 0, left, lefts;
const gchar *pit = pattern, *sit; const gchar *pit = pattern, *sit;
enum CharClass prev = NON_WORD; enum CharClass prev = NON_WORD;
@@ -946,12 +938,11 @@ int rofi_scorer_fuzzy_evaluate ( const char *pattern, glong plen, const char *st
if (config.case_sensitive if (config.case_sensitive
? pc == sc ? pc == sc
: g_unichar_tolower(pc) == g_unichar_tolower(sc)) { : g_unichar_tolower(pc) == g_unichar_tolower(sc)) {
int t = score[si] * ( pstart ? PATTERN_START_MULTIPLIER : PATTERN_NON_START_MULTIPLIER ); int t = score[si] * (pstart ? PATTERN_START_MULTIPLIER
dp[si] = pfirst : PATTERN_NON_START_MULTIPLIER);
? LEADING_GAP_SCORE * si + t dp[si] = pfirst ? LEADING_GAP_SCORE * si + t
: MAX(uleft + CONSECUTIVE_SCORE, ulefts + t); : MAX(uleft + CONSECUTIVE_SCORE, ulefts + t);
} } else {
else {
dp[si] = MIN_SCORE; dp[si] = MIN_SCORE;
} }
uleft = left; uleft = left;
@@ -975,12 +966,11 @@ int rofi_scorer_fuzzy_evaluate ( const char *pattern, glong plen, const char *st
* *
* Compares the `G_NORMALIZE_ALL_COMPOSE` forms of the two strings. * Compares the `G_NORMALIZE_ALL_COMPOSE` forms of the two strings.
* *
* @returns less than, equal to, or greater than zero if the first `n` characters (not bytes) of `a` * @returns less than, equal to, or greater than zero if the first `n`
* are found, respectively, to be less than, to match, or be greater than the first `n` * characters (not bytes) of `a` are found, respectively, to be less than, to
* characters (not bytes) of `b`. * match, or be greater than the first `n` characters (not bytes) of `b`.
*/ */
int utf8_strncmp ( const char* a, const char* b, size_t n ) int utf8_strncmp(const char *a, const char *b, size_t n) {
{
char *na = g_utf8_normalize(a, -1, G_NORMALIZE_ALL_COMPOSE); char *na = g_utf8_normalize(a, -1, G_NORMALIZE_ALL_COMPOSE);
char *nb = g_utf8_normalize(b, -1, G_NORMALIZE_ALL_COMPOSE); char *nb = g_utf8_normalize(b, -1, G_NORMALIZE_ALL_COMPOSE);
*g_utf8_offset_to_pointer(na, n) = '\0'; *g_utf8_offset_to_pointer(na, n) = '\0';
@@ -991,8 +981,9 @@ int utf8_strncmp ( const char* a, const char* b, size_t n )
return r; return r;
} }
gboolean helper_execute ( const char *wd, char **args, const char *error_precmd, const char *error_cmd, RofiHelperExecuteContext *context ) gboolean helper_execute(const char *wd, char **args, const char *error_precmd,
{ const char *error_cmd,
RofiHelperExecuteContext *context) {
gboolean retv = TRUE; gboolean retv = TRUE;
GError *error = NULL; GError *error = NULL;
@@ -1001,9 +992,11 @@ gboolean helper_execute ( const char *wd, char **args, const char *error_precmd,
display_startup_notification(context, &child_setup, &user_data); display_startup_notification(context, &child_setup, &user_data);
g_spawn_async ( wd, args, NULL, G_SPAWN_SEARCH_PATH, child_setup, user_data, NULL, &error ); g_spawn_async(wd, args, NULL, G_SPAWN_SEARCH_PATH, child_setup, user_data,
NULL, &error);
if (error != NULL) { if (error != NULL) {
char *msg = g_strdup_printf ( "Failed to execute: '%s%s'\nError: '%s'", error_precmd, error_cmd, error->message ); char *msg = g_strdup_printf("Failed to execute: '%s%s'\nError: '%s'",
error_precmd, error_cmd, error->message);
rofi_view_error_dialog(msg, FALSE); rofi_view_error_dialog(msg, FALSE);
g_free(msg); g_free(msg);
// print error. // print error.
@@ -1016,16 +1009,18 @@ gboolean helper_execute ( const char *wd, char **args, const char *error_precmd,
return retv; return retv;
} }
gboolean helper_execute_command ( const char *wd, const char *cmd, gboolean run_in_term, RofiHelperExecuteContext *context ) gboolean helper_execute_command(const char *wd, const char *cmd,
{ gboolean run_in_term,
RofiHelperExecuteContext *context) {
char **args = NULL; char **args = NULL;
int argc = 0; int argc = 0;
if (run_in_term) { if (run_in_term) {
helper_parse_setup ( config.run_shell_command, &args, &argc, "{cmd}", cmd, (char *) 0 ); helper_parse_setup(config.run_shell_command, &args, &argc, "{cmd}", cmd,
} (char *)0);
else { } else {
helper_parse_setup ( config.run_command, &args, &argc, "{cmd}", cmd, (char *) 0 ); helper_parse_setup(config.run_command, &args, &argc, "{cmd}", cmd,
(char *)0);
} }
if (args == NULL) { if (args == NULL) {
@@ -1054,8 +1049,7 @@ gboolean helper_execute_command ( const char *wd, const char *cmd, gboolean run_
return helper_execute(wd, args, "", cmd, context); return helper_execute(wd, args, "", cmd, context);
} }
char *helper_get_theme_path ( const char *file, const char *ext ) char *helper_get_theme_path(const char *file, const char *ext) {
{
char *filename = rofi_expand_path(file); char *filename = rofi_expand_path(file);
g_debug("Opening theme, testing: %s\n", filename); g_debug("Opening theme, testing: %s\n", filename);
if (g_file_test(filename, G_FILE_TEST_EXISTS)) { if (g_file_test(filename, G_FILE_TEST_EXISTS)) {
@@ -1065,8 +1059,7 @@ char *helper_get_theme_path ( const char *file, const char *ext )
if (g_str_has_suffix(file, ext)) { if (g_str_has_suffix(file, ext)) {
filename = g_strdup(file); filename = g_strdup(file);
} } else {
else {
filename = g_strconcat(file, ext, NULL); filename = g_strconcat(file, ext, NULL);
} }
// Check config's themes directory. // Check config's themes directory.
@@ -1092,7 +1085,8 @@ char *helper_get_theme_path ( const char *file, const char *ext )
} }
const char *datadir = g_get_user_data_dir(); const char *datadir = g_get_user_data_dir();
if (datadir) { if (datadir) {
char *theme_path = g_build_filename ( datadir, "rofi", "themes", filename, NULL ); char *theme_path =
g_build_filename(datadir, "rofi", "themes", filename, NULL);
g_debug("Opening theme, testing: %s\n", theme_path); g_debug("Opening theme, testing: %s\n", theme_path);
if (theme_path) { if (theme_path) {
if (g_file_test(theme_path, G_FILE_TEST_EXISTS)) { if (g_file_test(theme_path, G_FILE_TEST_EXISTS)) {
@@ -1115,8 +1109,7 @@ char *helper_get_theme_path ( const char *file, const char *ext )
return filename; return filename;
} }
static gboolean parse_pair ( char *input, rofi_range_pair *item ) static gboolean parse_pair(char *input, rofi_range_pair *item) {
{
// Skip leading blanks. // Skip leading blanks.
while (input != NULL && isblank(*input)) { while (input != NULL && isblank(*input)) {
++input; ++input;
@@ -1130,7 +1123,8 @@ static gboolean parse_pair ( char *input, rofi_range_pair *item )
int pythonic = (strchr(input, ':') || input[0] == '-') ? 1 : 0; int pythonic = (strchr(input, ':') || input[0] == '-') ? 1 : 0;
int index = 0; int index = 0;
for ( char *token = strsep ( &input, sep[pythonic] ); token != NULL; token = strsep ( &input, sep[pythonic] ) ) { for (char *token = strsep(&input, sep[pythonic]); token != NULL;
token = strsep(&input, sep[pythonic])) {
if (index == 0) { if (index == 0) {
item->start = item->stop = (int)strtol(token, NULL, 10); item->start = item->stop = (int)strtol(token, NULL, 10);
index++; index++;
@@ -1149,63 +1143,56 @@ static gboolean parse_pair ( char *input, rofi_range_pair *item )
} }
return TRUE; return TRUE;
} }
void parse_ranges ( char *input, rofi_range_pair **list, unsigned int *length ) void parse_ranges(char *input, rofi_range_pair **list, unsigned int *length) {
{
char *endp; char *endp;
if (input == NULL) { if (input == NULL) {
return; return;
} }
const char *const sep = ","; const char *const sep = ",";
for ( char *token = strtok_r ( input, sep, &endp ); token != NULL; token = strtok_r ( NULL, sep, &endp ) ) { for (char *token = strtok_r(input, sep, &endp); token != NULL;
token = strtok_r(NULL, sep, &endp)) {
// Make space. // Make space.
*list = g_realloc ( ( *list ), ( ( *length ) + 1 ) * sizeof ( struct rofi_range_pair ) ); *list =
g_realloc((*list), ((*length) + 1) * sizeof(struct rofi_range_pair));
// Parse a single pair. // Parse a single pair.
if (parse_pair(token, &((*list)[*length]))) { if (parse_pair(token, &((*list)[*length]))) {
(*length)++; (*length)++;
} }
} }
} }
void rofi_output_formatted_line ( const char *format, const char *string, int selected_line, const char *filter ) void rofi_output_formatted_line(const char *format, const char *string,
{ int selected_line, const char *filter) {
for (int i = 0; format && format[i]; i++) { for (int i = 0; format && format[i]; i++) {
if (format[i] == 'i') { if (format[i] == 'i') {
fprintf(stdout, "%d", selected_line); fprintf(stdout, "%d", selected_line);
} } else if (format[i] == 'd') {
else if ( format[i] == 'd' ) {
fprintf(stdout, "%d", (selected_line + 1)); fprintf(stdout, "%d", (selected_line + 1));
} } else if (format[i] == 's') {
else if ( format[i] == 's' ) {
fputs(string, stdout); fputs(string, stdout);
} } else if (format[i] == 'p') {
else if ( format[i] == 'p' ) {
char *esc = NULL; char *esc = NULL;
pango_parse_markup(string, -1, 0, NULL, &esc, NULL, NULL); pango_parse_markup(string, -1, 0, NULL, &esc, NULL, NULL);
if (esc) { if (esc) {
fputs(esc, stdout); fputs(esc, stdout);
g_free(esc); g_free(esc);
} } else {
else {
fputs("invalid string", stdout); fputs("invalid string", stdout);
} }
} } else if (format[i] == 'q') {
else if ( format[i] == 'q' ) {
char *quote = g_shell_quote(string); char *quote = g_shell_quote(string);
fputs(quote, stdout); fputs(quote, stdout);
g_free(quote); g_free(quote);
} } else if (format[i] == 'f') {
else if ( format[i] == 'f' ) {
if (filter) { if (filter) {
fputs(filter, stdout); fputs(filter, stdout);
} }
} } else if (format[i] == 'F') {
else if ( format[i] == 'F' ) {
if (filter) { if (filter) {
char *quote = g_shell_quote(filter); char *quote = g_shell_quote(filter);
fputs(quote, stdout); fputs(quote, stdout);
g_free(quote); g_free(quote);
} }
} } else {
else {
fputc(format[i], stdout); fputc(format[i], stdout);
} }
} }
@@ -1213,8 +1200,8 @@ void rofi_output_formatted_line ( const char *format, const char *string, int se
fflush(stdout); fflush(stdout);
} }
static gboolean helper_eval_cb2 ( const GMatchInfo *info, GString *res, gpointer data ) static gboolean helper_eval_cb2(const GMatchInfo *info, GString *res,
{ gpointer data) {
gchar *match; gchar *match;
// Get the match // Get the match
int num_match = g_match_info_get_match_count(info); int num_match = g_match_info_get_match_count(info);
@@ -1259,8 +1246,7 @@ static gboolean helper_eval_cb2 ( const GMatchInfo *info, GString *res, gpointer
return FALSE; return FALSE;
} }
char *helper_string_replace_if_exists ( char * string, ... ) char *helper_string_replace_if_exists(char *string, ...) {
{
GHashTable *h; GHashTable *h;
h = g_hash_table_new(g_str_hash, g_str_equal); h = g_hash_table_new(g_str_hash, g_str_equal);
va_list ap; va_list ap;
@@ -1282,32 +1268,36 @@ char *helper_string_replace_if_exists ( char * string, ... )
} }
/** /**
* @param string The string with elements to be replaced * @param string The string with elements to be replaced
* @param h Hash table with set of {key}, value that will be replaced, terminated by a NULL * @param h Hash table with set of {key}, value that will be replaced,
* terminated by a NULL
* *
* Items {key} are replaced by the value if '{key}' is passed as key/value pair, otherwise removed from string. * Items {key} are replaced by the value if '{key}' is passed as key/value pair,
* If the {key} is in between [] all the text between [] are removed if {key} * otherwise removed from string. If the {key} is in between [] all the text
* is not found. Otherwise key is replaced and [ & ] removed. * between [] are removed if {key} is not found. Otherwise key is replaced and [
* & ] removed.
* *
* This allows for optional replacement, f.e. '{ssh-client} [-t {title}] -e * This allows for optional replacement, f.e. '{ssh-client} [-t {title}] -e
* "{cmd}"' the '-t {title}' is only there if {title} is set. * "{cmd}"' the '-t {title}' is only there if {title} is set.
* *
* @returns a new string with the keys replaced. * @returns a new string with the keys replaced.
*/ */
char *helper_string_replace_if_exists_v ( char * string, GHashTable *h ) char *helper_string_replace_if_exists_v(char *string, GHashTable *h) {
{
GError *error = NULL; GError *error = NULL;
char *res = NULL; char *res = NULL;
// Replace hits within {-\w+}. // Replace hits within {-\w+}.
GRegex *reg = g_regex_new ( "\\[(.*)({[-\\w]+})(.*)\\]|({[\\w-]+})", G_REGEX_UNGREEDY, 0, &error ); GRegex *reg = g_regex_new("\\[(.*)({[-\\w]+})(.*)\\]|({[\\w-]+})",
G_REGEX_UNGREEDY, 0, &error);
if (error == NULL) { if (error == NULL) {
res = g_regex_replace_eval ( reg, string, -1, 0, 0, helper_eval_cb2, h, &error ); res =
g_regex_replace_eval(reg, string, -1, 0, 0, helper_eval_cb2, h, &error);
} }
// Free regex. // Free regex.
g_regex_unref(reg); g_regex_unref(reg);
// Throw error if shell parsing fails. // Throw error if shell parsing fails.
if (error != NULL) { if (error != NULL) {
char *msg = g_strdup_printf ( "Failed to parse: '%s'\nError: '%s'", string, error->message ); char *msg = g_strdup_printf("Failed to parse: '%s'\nError: '%s'", string,
error->message);
rofi_view_error_dialog(msg, FALSE); rofi_view_error_dialog(msg, FALSE);
g_free(msg); g_free(msg);
// print error. // print error.

View File

@@ -25,50 +25,50 @@
* *
*/ */
#include <config.h> #include "history.h"
#include <stdlib.h> #include "rofi.h"
#include <stdio.h> #include "settings.h"
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <errno.h> #include <errno.h>
#include <glib.h> #include <glib.h>
#include <glib/gstdio.h> #include <glib/gstdio.h>
#include "rofi.h" #include <stdio.h>
#include "history.h" #include <stdlib.h>
#include "settings.h" #include <string.h>
#include <sys/types.h>
#include <unistd.h>
/** /**
* History element * History element
*/ */
typedef struct __element typedef struct __element {
{
/** Index in history */ /** Index in history */
long int index; long int index;
/** Entry */ /** Entry */
char *name; char *name;
} _element; } _element;
static int __element_sort_func ( const void *ea, const void *eb, void *data __attribute__( ( unused ) ) ) static int __element_sort_func(const void *ea, const void *eb,
{ void *data __attribute__((unused))) {
_element *a = *(_element **)ea; _element *a = *(_element **)ea;
_element *b = *(_element **)eb; _element *b = *(_element **)eb;
return b->index - a->index; return b->index - a->index;
} }
static void __history_write_element_list ( FILE *fd, _element **list, unsigned int length ) static void __history_write_element_list(FILE *fd, _element **list,
{ unsigned int length) {
if (list == NULL || length == 0) { if (list == NULL || length == 0) {
return; return;
} }
// Sort the list before writing out. // Sort the list before writing out.
g_qsort_with_data ( list, length, sizeof ( _element* ), __element_sort_func, NULL ); g_qsort_with_data(list, length, sizeof(_element *), __element_sort_func,
NULL);
// Get minimum index. // Get minimum index.
int min_value = list[length - 1]->index; int min_value = list[length - 1]->index;
// Set the max length of the list. // Set the max length of the list.
length = ( length > config.max_history_size ) ? config.max_history_size : length; length =
(length > config.max_history_size) ? config.max_history_size : length;
// Write out entries. // Write out entries.
for (unsigned int iter = 0; iter < length; iter++) { for (unsigned int iter = 0; iter < length; iter++) {
@@ -76,10 +76,11 @@ static void __history_write_element_list ( FILE *fd, _element **list, unsigned i
} }
} }
static char ** __history_get_element_list_fields ( FILE *fd, unsigned int *length ) static char **__history_get_element_list_fields(FILE *fd,
{ unsigned int *length) {
unsigned int real_length = 0; unsigned int real_length = 0;
char **retv = NULL;; char **retv = NULL;
;
if (length == NULL) { if (length == NULL) {
return NULL; return NULL;
} }
@@ -119,8 +120,7 @@ static char ** __history_get_element_list_fields ( FILE *fd, unsigned int *lengt
return retv; return retv;
} }
static _element ** __history_get_element_list ( FILE *fd, unsigned int *length ) static _element **__history_get_element_list(FILE *fd, unsigned int *length) {
{
unsigned int real_length = 0; unsigned int real_length = 0;
_element **retv = NULL; _element **retv = NULL;
@@ -175,18 +175,20 @@ static _element ** __history_get_element_list ( FILE *fd, unsigned int *length )
return retv; return retv;
} }
void history_set ( const char *filename, const char *entry ) void history_set(const char *filename, const char *entry) {
{
if (config.disable_history) { if (config.disable_history) {
return; return;
} }
// Check if program should be ignored // Check if program should be ignored
for ( char *checked_prefix = strtok ( config.ignored_prefixes, ";" ); checked_prefix != NULL; checked_prefix = strtok ( NULL, ";" ) ) { for (char *checked_prefix = strtok(config.ignored_prefixes, ";");
checked_prefix != NULL; checked_prefix = strtok(NULL, ";")) {
// For each ignored prefix // For each ignored prefix
while (g_unichar_isspace(g_utf8_get_char(checked_prefix))) { while (g_unichar_isspace(g_utf8_get_char(checked_prefix))) {
checked_prefix = g_utf8_next_char ( checked_prefix ); // Some users will probably want "; " as their separator for aesthetics. checked_prefix = g_utf8_next_char(
checked_prefix); // Some users will probably want "; " as their
// separator for aesthetics.
} }
if (g_str_has_prefix(entry, checked_prefix)) { if (g_str_has_prefix(entry, checked_prefix)) {
@@ -219,8 +221,7 @@ void history_set ( const char *filename, const char *entry )
if (found) { if (found) {
// If exists, increment list index number // If exists, increment list index number
list[curr]->index++; list[curr]->index++;
} } else {
else{
// If not exists, add it. // If not exists, add it.
// Increase list by one // Increase list by one
list = g_realloc(list, (length + 2) * sizeof(_element *)); list = g_realloc(list, (length + 2) * sizeof(_element *));
@@ -239,8 +240,7 @@ void history_set ( const char *filename, const char *entry )
fd = fopen(filename, "w"); fd = fopen(filename, "w");
if (fd == NULL) { if (fd == NULL) {
g_warning("Failed to open file: %s", g_strerror(errno)); g_warning("Failed to open file: %s", g_strerror(errno));
} } else {
else {
// Write list. // Write list.
__history_write_element_list(fd, list, length); __history_write_element_list(fd, list, length);
// Close file, if fails let user know on stderr. // Close file, if fails let user know on stderr.
@@ -256,8 +256,7 @@ void history_set ( const char *filename, const char *entry )
g_free(list); g_free(list);
} }
void history_remove ( const char *filename, const char *entry ) void history_remove(const char *filename, const char *entry) {
{
if (config.disable_history) { if (config.disable_history) {
return; return;
} }
@@ -306,8 +305,7 @@ void history_remove ( const char *filename, const char *entry )
if (fclose(fd) != 0) { if (fclose(fd) != 0) {
g_warning("Failed to close history file: %s", g_strerror(errno)); g_warning("Failed to close history file: %s", g_strerror(errno));
} }
} } else {
else{
g_warning("Failed to open file: %s", g_strerror(errno)); g_warning("Failed to open file: %s", g_strerror(errno));
} }
} }
@@ -322,8 +320,7 @@ void history_remove ( const char *filename, const char *entry )
} }
} }
char ** history_get_list ( const char *filename, unsigned int *length ) char **history_get_list(const char *filename, unsigned int *length) {
{
*length = 0; *length = 0;
if (config.disable_history) { if (config.disable_history) {

View File

@@ -25,7 +25,7 @@
* *
*/ */
#include <config.h> #include "config.h"
#include <string.h> #include <string.h>
#include "rofi.h" #include "rofi.h"
#include "nkutils-bindings.h" #include "nkutils-bindings.h"

View File

@@ -25,12 +25,12 @@
* *
*/ */
#include <stdio.h> #include "mode.h"
#include <glib.h>
#include <string.h>
#include "rofi.h" #include "rofi.h"
#include "xrmoptions.h" #include "xrmoptions.h"
#include "mode.h" #include <glib.h>
#include <stdio.h>
#include <string.h>
// This one should only be in mode implementations. // This one should only be in mode implementations.
#include "mode-private.h" #include "mode-private.h"
@@ -39,70 +39,64 @@
* @{ * @{
*/ */
int mode_init ( Mode *mode ) int mode_init(Mode *mode) {
{
g_return_val_if_fail(mode != NULL, FALSE); g_return_val_if_fail(mode != NULL, FALSE);
g_return_val_if_fail(mode->_init != NULL, FALSE); g_return_val_if_fail(mode->_init != NULL, FALSE);
return mode->_init(mode); return mode->_init(mode);
} }
void mode_destroy ( Mode *mode ) void mode_destroy(Mode *mode) {
{
g_assert(mode != NULL); g_assert(mode != NULL);
g_assert(mode->_destroy != NULL); g_assert(mode->_destroy != NULL);
mode->_destroy(mode); mode->_destroy(mode);
} }
unsigned int mode_get_num_entries ( const Mode *mode ) unsigned int mode_get_num_entries(const Mode *mode) {
{
g_assert(mode != NULL); g_assert(mode != NULL);
g_assert(mode->_get_num_entries != NULL); g_assert(mode->_get_num_entries != NULL);
return mode->_get_num_entries(mode); return mode->_get_num_entries(mode);
} }
char * mode_get_display_value ( const Mode *mode, unsigned int selected_line, int *state, GList **attribute_list, int get_entry ) char *mode_get_display_value(const Mode *mode, unsigned int selected_line,
{ int *state, GList **attribute_list,
int get_entry) {
g_assert(mode != NULL); g_assert(mode != NULL);
g_assert(state != NULL); g_assert(state != NULL);
g_assert(mode->_get_display_value != NULL); g_assert(mode->_get_display_value != NULL);
return mode->_get_display_value ( mode, selected_line, state, attribute_list, get_entry ); return mode->_get_display_value(mode, selected_line, state, attribute_list,
get_entry);
} }
cairo_surface_t * mode_get_icon ( const Mode *mode, unsigned int selected_line, int height ) cairo_surface_t *mode_get_icon(const Mode *mode, unsigned int selected_line,
{ int height) {
g_assert(mode != NULL); g_assert(mode != NULL);
if (mode->_get_icon != NULL) { if (mode->_get_icon != NULL) {
return mode->_get_icon(mode, selected_line, height); return mode->_get_icon(mode, selected_line, height);
} }
else {
return NULL; return NULL;
} }
}
char * mode_get_completion ( const Mode *mode, unsigned int selected_line ) char *mode_get_completion(const Mode *mode, unsigned int selected_line) {
{
g_assert(mode != NULL); g_assert(mode != NULL);
if (mode->_get_completion != NULL) { if (mode->_get_completion != NULL) {
return mode->_get_completion(mode, selected_line); return mode->_get_completion(mode, selected_line);
} }
else {
int state; int state;
g_assert(mode->_get_display_value != NULL); g_assert(mode->_get_display_value != NULL);
return mode->_get_display_value(mode, selected_line, &state, NULL, TRUE); return mode->_get_display_value(mode, selected_line, &state, NULL, TRUE);
} }
}
ModeMode mode_result ( Mode *mode, int menu_retv, char **input, unsigned int selected_line ) ModeMode mode_result(Mode *mode, int menu_retv, char **input,
{ unsigned int selected_line) {
if (menu_retv & MENU_NEXT) { if (menu_retv & MENU_NEXT) {
return NEXT_DIALOG; return NEXT_DIALOG;
} }
else if ( menu_retv & MENU_PREVIOUS ) { if (menu_retv & MENU_PREVIOUS) {
return PREVIOUS_DIALOG; return PREVIOUS_DIALOG;
} }
else if ( menu_retv & MENU_QUICK_SWITCH ) { if (menu_retv & MENU_QUICK_SWITCH) {
return menu_retv & MENU_LOWER_MASK; return menu_retv & MENU_LOWER_MASK;
} }
@@ -113,21 +107,19 @@ ModeMode mode_result ( Mode *mode, int menu_retv, char **input, unsigned int sel
return mode->_result(mode, menu_retv, input, selected_line); return mode->_result(mode, menu_retv, input, selected_line);
} }
int mode_token_match ( const Mode *mode, rofi_int_matcher **tokens, unsigned int selected_line ) int mode_token_match(const Mode *mode, rofi_int_matcher **tokens,
{ unsigned int selected_line) {
g_assert(mode != NULL); g_assert(mode != NULL);
g_assert(mode->_token_match != NULL); g_assert(mode->_token_match != NULL);
return mode->_token_match(mode, tokens, selected_line); return mode->_token_match(mode, tokens, selected_line);
} }
const char *mode_get_name ( const Mode *mode ) const char *mode_get_name(const Mode *mode) {
{
g_assert(mode != NULL); g_assert(mode != NULL);
return mode->name; return mode->name;
} }
void mode_free ( Mode **mode ) void mode_free(Mode **mode) {
{
g_assert(mode != NULL); g_assert(mode != NULL);
g_assert((*mode) != NULL); g_assert((*mode) != NULL);
if ((*mode)->free != NULL) { if ((*mode)->free != NULL) {
@@ -136,14 +128,12 @@ void mode_free ( Mode **mode )
(*mode) = NULL; (*mode) = NULL;
} }
void *mode_get_private_data ( const Mode *mode ) void *mode_get_private_data(const Mode *mode) {
{
g_assert(mode != NULL); g_assert(mode != NULL);
return mode->private_data; return mode->private_data;
} }
void mode_set_private_data ( Mode *mode, void *pd ) void mode_set_private_data(Mode *mode, void *pd) {
{
g_assert(mode != NULL); g_assert(mode != NULL);
if (pd != NULL) { if (pd != NULL) {
g_assert(mode->private_data == NULL); g_assert(mode->private_data == NULL);
@@ -151,8 +141,7 @@ void mode_set_private_data ( Mode *mode, void *pd )
mode->private_data = pd; mode->private_data = pd;
} }
const char *mode_get_display_name ( const Mode *mode ) const char *mode_get_display_name(const Mode *mode) {
{
/** Find the widget */ /** Find the widget */
ThemeWidget *wid = rofi_config_find_widget(mode->name, NULL, TRUE); ThemeWidget *wid = rofi_config_find_widget(mode->name, NULL, TRUE);
if (wid) { if (wid) {
@@ -168,21 +157,20 @@ const char *mode_get_display_name ( const Mode *mode )
return mode->name; return mode->name;
} }
void mode_set_config ( Mode *mode ) void mode_set_config(Mode *mode) {
{
snprintf(mode->cfg_name_key, 128, "display-%s", mode->name); snprintf(mode->cfg_name_key, 128, "display-%s", mode->name);
config_parser_add_option ( xrm_String, mode->cfg_name_key, (void * *) &( mode->display_name ), "The display name of this browser" ); config_parser_add_option(xrm_String, mode->cfg_name_key,
(void **)&(mode->display_name),
"The display name of this browser");
} }
char * mode_preprocess_input ( Mode *mode, const char *input ) char *mode_preprocess_input(Mode *mode, const char *input) {
{
if (mode->_preprocess_input) { if (mode->_preprocess_input) {
return mode->_preprocess_input(mode, input); return mode->_preprocess_input(mode, input);
} }
return g_strdup(input); return g_strdup(input);
} }
char *mode_get_message ( const Mode *mode ) char *mode_get_message(const Mode *mode) {
{
if (mode->_get_message) { if (mode->_get_message) {
return mode->_get_message(mode); return mode->_get_message(mode);
} }

View File

@@ -28,7 +28,7 @@
/** The log domain of this Helper. */ /** The log domain of this Helper. */
#define G_LOG_DOMAIN "Helpers.IconFetcher" #define G_LOG_DOMAIN "Helpers.IconFetcher"
#include <config.h> #include "config.h"
#include <stdlib.h> #include <stdlib.h>
#include <xcb/xproto.h> #include <xcb/xproto.h>

View File

@@ -29,7 +29,7 @@
/** Log domain */ /** Log domain */
#define G_LOG_DOMAIN "Rofi" #define G_LOG_DOMAIN "Rofi"
#include <config.h> #include "config.h"
#include <errno.h> #include <errno.h>
#include <gmodule.h> #include <gmodule.h>
#include <locale.h> #include <locale.h>

File diff suppressed because it is too large Load Diff

View File

@@ -28,10 +28,10 @@
/** Log domain used by timings.*/ /** Log domain used by timings.*/
#define G_LOG_DOMAIN "Timings" #define G_LOG_DOMAIN "Timings"
#include "config.h"
#include <stdio.h>
#include "rofi.h"
#include "timings.h" #include "timings.h"
#include "config.h"
#include "rofi.h"
#include <stdio.h>
/** /**
* Timer used to calculate time stamps. * Timer used to calculate time stamps.
*/ */
@@ -41,23 +41,22 @@ GTimer *global_timer = NULL;
*/ */
double global_timer_last = 0.0; double global_timer_last = 0.0;
void rofi_timings_init ( void ) void rofi_timings_init(void) {
{
global_timer = g_timer_new(); global_timer = g_timer_new();
double now = g_timer_elapsed(global_timer, NULL); double now = g_timer_elapsed(global_timer, NULL);
g_debug("%4.6f (%2.6f): Started", now, 0.0); g_debug("%4.6f (%2.6f): Started", now, 0.0);
} }
void rofi_timings_tick ( const char *file, char const *str, int line, char const *msg ) void rofi_timings_tick(const char *file, char const *str, int line,
{ char const *msg) {
double now = g_timer_elapsed(global_timer, NULL); double now = g_timer_elapsed(global_timer, NULL);
g_debug ( "%4.6f (%2.6f): %s:%s:%-3d %s", now, now - global_timer_last, file, str, line, msg ); g_debug("%4.6f (%2.6f): %s:%s:%-3d %s", now, now - global_timer_last, file,
str, line, msg);
global_timer_last = now; global_timer_last = now;
} }
void rofi_timings_quit ( void ) void rofi_timings_quit(void) {
{
double now = g_timer_elapsed(global_timer, NULL); double now = g_timer_elapsed(global_timer, NULL);
g_debug("%4.6f (%2.6f): Stopped", now, 0.0); g_debug("%4.6f (%2.6f): Stopped", now, 0.0);
g_timer_destroy(global_timer); g_timer_destroy(global_timer);

View File

@@ -28,7 +28,7 @@
/** The Rofi View log domain */ /** The Rofi View log domain */
#define G_LOG_DOMAIN "View" #define G_LOG_DOMAIN "View"
#include <config.h> #include "config.h"
#include <errno.h> #include <errno.h>
#include <locale.h> #include <locale.h>
#include <signal.h> #include <signal.h>

View File

@@ -28,18 +28,16 @@
/** The log domain of this widget. */ /** The log domain of this widget. */
#define G_LOG_DOMAIN "Widgets.Box" #define G_LOG_DOMAIN "Widgets.Box"
#include <config.h>
#include <stdio.h>
#include "widgets/widget.h"
#include "widgets/widget-internal.h"
#include "widgets/box.h" #include "widgets/box.h"
#include "theme.h" #include "theme.h"
#include "widgets/widget-internal.h"
#include "widgets/widget.h"
#include <stdio.h>
/** Default spacing used in the box*/ /** Default spacing used in the box*/
#define DEFAULT_SPACING 2 #define DEFAULT_SPACING 2
struct _box struct _box {
{
widget widget; widget widget;
RofiOrientation type; RofiOrientation type;
int max_size; int max_size;
@@ -51,8 +49,7 @@ struct _box
static void box_update(widget *wid); static void box_update(widget *wid);
static int box_get_desired_width ( widget *wid ) static int box_get_desired_width(widget *wid) {
{
box *b = (box *)wid; box *b = (box *)wid;
int spacing = distance_get_pixel(b->spacing, b->type); int spacing = distance_get_pixel(b->spacing, b->type);
int width = 0; int width = 0;
@@ -66,7 +63,8 @@ static int box_get_desired_width ( widget *wid )
if (b->type == ROFI_ORIENTATION_HORIZONTAL) { if (b->type == ROFI_ORIENTATION_HORIZONTAL) {
int active_widgets = 0; int active_widgets = 0;
for ( GList *iter = g_list_first ( b->children ); iter != NULL; iter = g_list_next ( iter ) ) { for (GList *iter = g_list_first(b->children); iter != NULL;
iter = g_list_next(iter)) {
widget *child = (widget *)iter->data; widget *child = (widget *)iter->data;
if (!child->enabled) { if (!child->enabled) {
continue; continue;
@@ -81,9 +79,9 @@ static int box_get_desired_width ( widget *wid )
if (active_widgets > 0) { if (active_widgets > 0) {
width += (active_widgets - 1) * spacing; width += (active_widgets - 1) * spacing;
} }
} } else {
else { for (GList *iter = g_list_first(b->children); iter != NULL;
for ( GList *iter = g_list_first ( b->children ); iter != NULL; iter = g_list_next ( iter ) ) { iter = g_list_next(iter)) {
widget *child = (widget *)iter->data; widget *child = (widget *)iter->data;
if (!child->enabled) { if (!child->enabled) {
continue; continue;
@@ -94,14 +92,14 @@ static int box_get_desired_width ( widget *wid )
width += widget_padding_get_padding_width(wid); width += widget_padding_get_padding_width(wid);
return width; return width;
} }
static int box_get_desired_height ( widget *wid ) static int box_get_desired_height(widget *wid) {
{
box *b = (box *)wid; box *b = (box *)wid;
int spacing = distance_get_pixel(b->spacing, b->type); int spacing = distance_get_pixel(b->spacing, b->type);
int height = 0; int height = 0;
if (b->type == ROFI_ORIENTATION_VERTICAL) { if (b->type == ROFI_ORIENTATION_VERTICAL) {
int active_widgets = 0; int active_widgets = 0;
for ( GList *iter = g_list_first ( b->children ); iter != NULL; iter = g_list_next ( iter ) ) { for (GList *iter = g_list_first(b->children); iter != NULL;
iter = g_list_next(iter)) {
widget *child = (widget *)iter->data; widget *child = (widget *)iter->data;
if (!child->enabled) { if (!child->enabled) {
continue; continue;
@@ -112,9 +110,9 @@ static int box_get_desired_height ( widget *wid )
if (active_widgets > 0) { if (active_widgets > 0) {
height += (active_widgets - 1) * spacing; height += (active_widgets - 1) * spacing;
} }
} } else {
else { for (GList *iter = g_list_first(b->children); iter != NULL;
for ( GList *iter = g_list_first ( b->children ); iter != NULL; iter = g_list_next ( iter ) ) { iter = g_list_next(iter)) {
widget *child = (widget *)iter->data; widget *child = (widget *)iter->data;
if (!child->enabled) { if (!child->enabled) {
continue; continue;
@@ -126,21 +124,22 @@ static int box_get_desired_height ( widget *wid )
return height; return height;
} }
static void vert_calculate_size ( box *b ) static void vert_calculate_size(box *b) {
{
int spacing = distance_get_pixel(b->spacing, ROFI_ORIENTATION_VERTICAL); int spacing = distance_get_pixel(b->spacing, ROFI_ORIENTATION_VERTICAL);
int expanding_widgets = 0; int expanding_widgets = 0;
int active_widgets = 0; int active_widgets = 0;
int rem_width = widget_padding_get_remaining_width(WIDGET(b)); int rem_width = widget_padding_get_remaining_width(WIDGET(b));
int rem_height = widget_padding_get_remaining_height(WIDGET(b)); int rem_height = widget_padding_get_remaining_height(WIDGET(b));
for ( GList *iter = g_list_first ( b->children ); iter != NULL; iter = g_list_next ( iter ) ) { for (GList *iter = g_list_first(b->children); iter != NULL;
iter = g_list_next(iter)) {
widget *child = (widget *)iter->data; widget *child = (widget *)iter->data;
if (child->enabled && child->expand == FALSE) { if (child->enabled && child->expand == FALSE) {
widget_resize(child, rem_width, widget_get_desired_height(child)); widget_resize(child, rem_width, widget_get_desired_height(child));
} }
} }
b->max_size = 0; b->max_size = 0;
for ( GList *iter = g_list_first ( b->children ); iter != NULL; iter = g_list_next ( iter ) ) { for (GList *iter = g_list_first(b->children); iter != NULL;
iter = g_list_next(iter)) {
widget *child = (widget *)iter->data; widget *child = (widget *)iter->data;
if (!child->enabled) { if (!child->enabled) {
continue; continue;
@@ -159,14 +158,16 @@ static void vert_calculate_size ( box *b )
} }
if (b->max_size > rem_height) { if (b->max_size > rem_height) {
b->max_size = rem_height; b->max_size = rem_height;
g_debug ( "Widgets to large (height) for box: %d %d", b->max_size, b->widget.h ); g_debug("Widgets to large (height) for box: %d %d", b->max_size,
b->widget.h);
return; return;
} }
if (active_widgets > 0) { if (active_widgets > 0) {
int top = widget_padding_get_top(WIDGET(b)); int top = widget_padding_get_top(WIDGET(b));
double rem = rem_height - b->max_size; double rem = rem_height - b->max_size;
int index = 0; int index = 0;
for ( GList *iter = g_list_first ( b->children ); iter != NULL; iter = g_list_next ( iter ) ) { for (GList *iter = g_list_first(b->children); iter != NULL;
iter = g_list_next(iter)) {
widget *child = (widget *)iter->data; widget *child = (widget *)iter->data;
if (child->enabled == FALSE) { if (child->enabled == FALSE) {
continue; continue;
@@ -180,8 +181,7 @@ static void vert_calculate_size ( box *b )
top += spacing; top += spacing;
rem -= expanding_widgets_size; rem -= expanding_widgets_size;
index++; index++;
} } else {
else {
widget_move(child, widget_padding_get_left(WIDGET(b)), top); widget_move(child, widget_padding_get_left(WIDGET(b)), top);
top += widget_get_height(child); top += widget_get_height(child);
top += spacing; top += spacing;
@@ -190,14 +190,14 @@ static void vert_calculate_size ( box *b )
} }
b->max_size += widget_padding_get_padding_height(WIDGET(b)); b->max_size += widget_padding_get_padding_height(WIDGET(b));
} }
static void hori_calculate_size ( box *b ) static void hori_calculate_size(box *b) {
{
int spacing = distance_get_pixel(b->spacing, ROFI_ORIENTATION_HORIZONTAL); int spacing = distance_get_pixel(b->spacing, ROFI_ORIENTATION_HORIZONTAL);
int expanding_widgets = 0; int expanding_widgets = 0;
int active_widgets = 0; int active_widgets = 0;
int rem_width = widget_padding_get_remaining_width(WIDGET(b)); int rem_width = widget_padding_get_remaining_width(WIDGET(b));
int rem_height = widget_padding_get_remaining_height(WIDGET(b)); int rem_height = widget_padding_get_remaining_height(WIDGET(b));
for ( GList *iter = g_list_first ( b->children ); iter != NULL; iter = g_list_next ( iter ) ) { for (GList *iter = g_list_first(b->children); iter != NULL;
iter = g_list_next(iter)) {
widget *child = (widget *)iter->data; widget *child = (widget *)iter->data;
if (child->enabled && child->expand == FALSE) { if (child->enabled && child->expand == FALSE) {
widget_resize(child, widget_resize(child,
@@ -206,7 +206,8 @@ static void hori_calculate_size ( box *b )
} }
} }
b->max_size = 0; b->max_size = 0;
for ( GList *iter = g_list_first ( b->children ); iter != NULL; iter = g_list_next ( iter ) ) { for (GList *iter = g_list_first(b->children); iter != NULL;
iter = g_list_next(iter)) {
widget *child = (widget *)iter->data; widget *child = (widget *)iter->data;
if (!child->enabled) { if (!child->enabled) {
continue; continue;
@@ -224,7 +225,8 @@ static void hori_calculate_size ( box *b )
b->max_size += MAX(0, ((active_widgets - 1) * spacing)); b->max_size += MAX(0, ((active_widgets - 1) * spacing));
if (b->max_size > (rem_width)) { if (b->max_size > (rem_width)) {
b->max_size = rem_width; b->max_size = rem_width;
g_debug ( "Widgets to large (width) for box: %d %d", b->max_size, b->widget.w ); g_debug("Widgets to large (width) for box: %d %d", b->max_size,
b->widget.w);
// return; // return;
} }
if (active_widgets > 0) { if (active_widgets > 0) {
@@ -234,7 +236,8 @@ static void hori_calculate_size ( box *b )
if (rem < 0) { if (rem < 0) {
rem = 0; rem = 0;
} }
for ( GList *iter = g_list_first ( b->children ); iter != NULL; iter = g_list_next ( iter ) ) { for (GList *iter = g_list_first(b->children); iter != NULL;
iter = g_list_next(iter)) {
widget *child = (widget *)iter->data; widget *child = (widget *)iter->data;
if (child->enabled == FALSE) { if (child->enabled == FALSE) {
continue; continue;
@@ -248,8 +251,7 @@ static void hori_calculate_size ( box *b )
left += spacing; left += spacing;
rem -= expanding_widgets_size; rem -= expanding_widgets_size;
index++; index++;
} } else {
else {
widget_move(child, left, widget_padding_get_top(WIDGET(b))); widget_move(child, left, widget_padding_get_top(WIDGET(b)));
left += widget_get_width(child); left += widget_get_width(child);
left += spacing; left += spacing;
@@ -259,20 +261,20 @@ static void hori_calculate_size ( box *b )
b->max_size += widget_padding_get_padding_width(WIDGET(b)); b->max_size += widget_padding_get_padding_width(WIDGET(b));
} }
static void box_draw ( widget *wid, cairo_t *draw ) static void box_draw(widget *wid, cairo_t *draw) {
{
box *b = (box *)wid; box *b = (box *)wid;
for ( GList *iter = g_list_first ( b->children ); iter != NULL; iter = g_list_next ( iter ) ) { for (GList *iter = g_list_first(b->children); iter != NULL;
iter = g_list_next(iter)) {
widget *child = (widget *)iter->data; widget *child = (widget *)iter->data;
widget_draw(child, draw); widget_draw(child, draw);
} }
} }
static void box_free ( widget *wid ) static void box_free(widget *wid) {
{
box *b = (box *)wid; box *b = (box *)wid;
for ( GList *iter = g_list_first ( b->children ); iter != NULL; iter = g_list_next ( iter ) ) { for (GList *iter = g_list_first(b->children); iter != NULL;
iter = g_list_next(iter)) {
widget *child = (widget *)iter->data; widget *child = (widget *)iter->data;
widget_free(child); widget_free(child);
} }
@@ -280,20 +282,20 @@ static void box_free ( widget *wid )
g_free(b); g_free(b);
} }
void box_add ( box *box, widget *child, gboolean expand ) void box_add(box *box, widget *child, gboolean expand) {
{
if (box == NULL) { if (box == NULL) {
return; return;
} }
// Make sure box is width/heigh enough. // Make sure box is width/heigh enough.
if (box->type == ROFI_ORIENTATION_VERTICAL) { if (box->type == ROFI_ORIENTATION_VERTICAL) {
int width = box->widget.w; int width = box->widget.w;
width = MAX ( width, child->w + widget_padding_get_padding_width ( WIDGET ( box ) ) ); width =
MAX(width, child->w + widget_padding_get_padding_width(WIDGET(box)));
box->widget.w = width; box->widget.w = width;
} } else {
else {
int height = box->widget.h; int height = box->widget.h;
height = MAX ( height, child->h + widget_padding_get_padding_height ( WIDGET ( box ) ) ); height =
MAX(height, child->h + widget_padding_get_padding_height(WIDGET(box)));
box->widget.h = height; box->widget.h = height;
} }
child->expand = rofi_theme_get_boolean(child, "expand", expand); child->expand = rofi_theme_get_boolean(child, "expand", expand);
@@ -302,8 +304,7 @@ void box_add ( box *box, widget *child, gboolean expand )
widget_update(WIDGET(box)); widget_update(WIDGET(box));
} }
static void box_resize ( widget *widget, short w, short h ) static void box_resize(widget *widget, short w, short h) {
{
box *b = (box *)widget; box *b = (box *)widget;
if (b->widget.w != w || b->widget.h != h) { if (b->widget.w != w || b->widget.h != h) {
b->widget.w = w; b->widget.w = w;
@@ -312,10 +313,11 @@ static void box_resize ( widget *widget, short w, short h )
} }
} }
static widget *box_find_mouse_target ( widget *wid, WidgetType type, gint x, gint y ) static widget *box_find_mouse_target(widget *wid, WidgetType type, gint x,
{ gint y) {
box *b = (box *)wid; box *b = (box *)wid;
for ( GList *iter = g_list_first ( b->children ); iter != NULL; iter = g_list_next ( iter ) ) { for (GList *iter = g_list_first(b->children); iter != NULL;
iter = g_list_next(iter)) {
widget *child = (widget *)iter->data; widget *child = (widget *)iter->data;
if (!child->enabled) { if (!child->enabled) {
continue; continue;
@@ -332,16 +334,15 @@ static widget *box_find_mouse_target ( widget *wid, WidgetType type, gint x, gin
return NULL; return NULL;
} }
static void box_set_state ( widget *wid, const char *state ) static void box_set_state(widget *wid, const char *state) {
{ for (GList *iter = g_list_first(((box *)wid)->children); iter != NULL;
for ( GList *iter = g_list_first ( ( (box *) wid )->children ); iter != NULL; iter = g_list_next ( iter ) ) { iter = g_list_next(iter)) {
widget *child = (widget *)iter->data; widget *child = (widget *)iter->data;
widget_set_state(child, state); widget_set_state(child, state);
} }
} }
box * box_create ( widget *parent, const char *name, RofiOrientation type ) box *box_create(widget *parent, const char *name, RofiOrientation type) {
{
box *b = g_malloc0(sizeof(box)); box *b = g_malloc0(sizeof(box));
// Initialize widget. // Initialize widget.
widget_init(WIDGET(b), parent, WIDGET_TYPE_UNKNOWN, name); widget_init(WIDGET(b), parent, WIDGET_TYPE_UNKNOWN, name);
@@ -361,11 +362,9 @@ box * box_create ( widget *parent, const char *name, RofiOrientation type )
return b; return b;
} }
static void box_update ( widget *wid ) static void box_update(widget *wid) {
{
box *b = (box *)wid; box *b = (box *)wid;
switch ( b->type ) switch (b->type) {
{
case ROFI_ORIENTATION_VERTICAL: case ROFI_ORIENTATION_VERTICAL:
vert_calculate_size(b); vert_calculate_size(b);
break; break;

View File

@@ -28,23 +28,20 @@
/** The log domain of this widget. */ /** The log domain of this widget. */
#define G_LOG_DOMAIN "Widgets.Container" #define G_LOG_DOMAIN "Widgets.Container"
#include <config.h>
#include <stdio.h>
#include "widgets/widget.h"
#include "widgets/widget-internal.h"
#include "widgets/container.h" #include "widgets/container.h"
#include "theme.h" #include "theme.h"
#include "widgets/widget-internal.h"
#include "widgets/widget.h"
#include <stdio.h>
struct _container struct _container {
{
widget widget; widget widget;
widget *child; widget *child;
}; };
static void container_update(widget *wid); static void container_update(widget *wid);
static int container_get_desired_height ( widget *widget ) static int container_get_desired_height(widget *widget) {
{
container *b = (container *)widget; container *b = (container *)widget;
int height = 0; int height = 0;
if (b->child) { if (b->child) {
@@ -54,23 +51,20 @@ static int container_get_desired_height ( widget *widget )
return height; return height;
} }
static void container_draw ( widget *wid, cairo_t *draw ) static void container_draw(widget *wid, cairo_t *draw) {
{
container *b = (container *)wid; container *b = (container *)wid;
widget_draw(b->child, draw); widget_draw(b->child, draw);
} }
static void container_free ( widget *wid ) static void container_free(widget *wid) {
{
container *b = (container *)wid; container *b = (container *)wid;
widget_free(b->child); widget_free(b->child);
g_free(b); g_free(b);
} }
void container_add ( container *container, widget *child ) void container_add(container *container, widget *child) {
{
if (container == NULL) { if (container == NULL) {
return; return;
} }
@@ -79,8 +73,7 @@ void container_add ( container *container, widget *child )
widget_update(WIDGET(container)); widget_update(WIDGET(container));
} }
static void container_resize ( widget *widget, short w, short h ) static void container_resize(widget *widget, short w, short h) {
{
container *b = (container *)widget; container *b = (container *)widget;
if (b->widget.w != w || b->widget.h != h) { if (b->widget.w != w || b->widget.h != h) {
b->widget.w = w; b->widget.w = w;
@@ -89,8 +82,8 @@ static void container_resize ( widget *widget, short w, short h )
} }
} }
static widget *container_find_mouse_target ( widget *wid, WidgetType type, gint x, gint y ) static widget *container_find_mouse_target(widget *wid, WidgetType type, gint x,
{ gint y) {
container *b = (container *)wid; container *b = (container *)wid;
if (!widget_intersect(b->child, x, y)) { if (!widget_intersect(b->child, x, y)) {
return NULL; return NULL;
@@ -101,14 +94,12 @@ static widget *container_find_mouse_target ( widget *wid, WidgetType type, gint
return widget_find_mouse_target(b->child, type, x, y); return widget_find_mouse_target(b->child, type, x, y);
} }
static void container_set_state ( widget *wid, const char *state ) static void container_set_state(widget *wid, const char *state) {
{
container *b = (container *)wid; container *b = (container *)wid;
widget_set_state(b->child, state); widget_set_state(b->child, state);
} }
container * container_create ( widget *parent, const char *name ) container *container_create(widget *parent, const char *name) {
{
container *b = g_malloc0(sizeof(container)); container *b = g_malloc0(sizeof(container));
// Initialize widget. // Initialize widget.
widget_init(WIDGET(b), parent, WIDGET_TYPE_UNKNOWN, name); widget_init(WIDGET(b), parent, WIDGET_TYPE_UNKNOWN, name);
@@ -122,17 +113,13 @@ container * container_create ( widget *parent, const char *name )
return b; return b;
} }
static void container_update ( widget *wid ) static void container_update(widget *wid) {
{
container *b = (container *)wid; container *b = (container *)wid;
if (b->child && b->child->enabled) { if (b->child && b->child->enabled) {
widget_resize(WIDGET(b->child), widget_resize(WIDGET(b->child),
widget_padding_get_remaining_width(WIDGET(b)), widget_padding_get_remaining_width(WIDGET(b)),
widget_padding_get_remaining_height ( WIDGET ( b ) ) widget_padding_get_remaining_height(WIDGET(b)));
); widget_move(WIDGET(b->child), widget_padding_get_left(WIDGET(b)),
widget_move ( WIDGET ( b->child ), widget_padding_get_top(WIDGET(b)));
widget_padding_get_left ( WIDGET ( b ) ),
widget_padding_get_top ( WIDGET ( b ) )
);
} }
} }

View File

@@ -28,17 +28,15 @@
/** The log domain of this widget. */ /** The log domain of this widget. */
#define G_LOG_DOMAIN "Widgets.Icon" #define G_LOG_DOMAIN "Widgets.Icon"
#include <config.h>
#include <stdio.h>
#include "widgets/widget.h"
#include "widgets/widget-internal.h"
#include "widgets/icon.h" #include "widgets/icon.h"
#include "theme.h" #include "theme.h"
#include "widgets/widget-internal.h"
#include "widgets/widget.h"
#include <stdio.h>
#include "rofi-icon-fetcher.h" #include "rofi-icon-fetcher.h"
struct _icon struct _icon {
{
widget widget; widget widget;
// Size of the icon. // Size of the icon.
@@ -54,8 +52,7 @@ struct _icon
cairo_surface_t *icon; cairo_surface_t *icon;
}; };
static int icon_get_desired_height ( widget *widget ) static int icon_get_desired_height(widget *widget) {
{
icon *b = (icon *)widget; icon *b = (icon *)widget;
int height = b->size; int height = b->size;
if (b->squared == FALSE) { if (b->squared == FALSE) {
@@ -70,8 +67,7 @@ static int icon_get_desired_height ( widget *widget )
height += widget_padding_get_padding_height(widget); height += widget_padding_get_padding_height(widget);
return height; return height;
} }
static int icon_get_desired_width ( widget *widget ) static int icon_get_desired_width(widget *widget) {
{
icon *b = (icon *)widget; icon *b = (icon *)widget;
int width = b->size; int width = b->size;
if (b->squared == FALSE) { if (b->squared == FALSE) {
@@ -87,8 +83,7 @@ static int icon_get_desired_width ( widget *widget )
return width; return width;
} }
static void icon_draw ( widget *wid, cairo_t *draw ) static void icon_draw(widget *wid, cairo_t *draw) {
{
icon *b = (icon *)wid; icon *b = (icon *)wid;
// If no icon is loaded. quit. // If no icon is loaded. quit.
if (b->icon == NULL && b->icon_fetch_id > 0) { if (b->icon == NULL && b->icon_fetch_id > 0) {
@@ -112,8 +107,8 @@ static void icon_draw ( widget *wid, cairo_t *draw )
cairo_save(draw); cairo_save(draw);
cairo_translate ( draw, cairo_translate(
lpad + ( b->widget.w - iconw * scale - lpad - rpad ) * b->xalign, draw, lpad + (b->widget.w - iconw * scale - lpad - rpad) * b->xalign,
tpad + (b->widget.h - iconh * scale - tpad - bpad) * b->yalign); tpad + (b->widget.h - iconh * scale - tpad - bpad) * b->yalign);
cairo_scale(draw, scale, scale); cairo_scale(draw, scale, scale);
cairo_set_source_surface(draw, b->icon, 0, 0); cairo_set_source_surface(draw, b->icon, 0, 0);
@@ -121,8 +116,7 @@ static void icon_draw ( widget *wid, cairo_t *draw )
cairo_restore(draw); cairo_restore(draw);
} }
static void icon_free ( widget *wid ) static void icon_free(widget *wid) {
{
icon *b = (icon *)wid; icon *b = (icon *)wid;
if (b->icon) { if (b->icon) {
@@ -132,8 +126,7 @@ static void icon_free ( widget *wid )
g_free(b); g_free(b);
} }
static void icon_resize ( widget *widget, short w, short h ) static void icon_resize(widget *widget, short w, short h) {
{
icon *b = (icon *)widget; icon *b = (icon *)widget;
if (b->widget.w != w || b->widget.h != h) { if (b->widget.w != w || b->widget.h != h) {
b->widget.w = w; b->widget.w = w;
@@ -142,8 +135,7 @@ static void icon_resize ( widget *widget, short w, short h )
} }
} }
void icon_set_surface ( icon *icon, cairo_surface_t *surf ) void icon_set_surface(icon *icon, cairo_surface_t *surf) {
{
icon->icon_fetch_id = 0; icon->icon_fetch_id = 0;
if (icon->icon) { if (icon->icon) {
cairo_surface_destroy(icon->icon); cairo_surface_destroy(icon->icon);
@@ -156,8 +148,7 @@ void icon_set_surface ( icon *icon, cairo_surface_t *surf )
widget_queue_redraw(WIDGET(icon)); widget_queue_redraw(WIDGET(icon));
} }
icon * icon_create ( widget *parent, const char *name ) icon *icon_create(widget *parent, const char *name) {
{
icon *b = g_malloc0(sizeof(icon)); icon *b = g_malloc0(sizeof(icon));
b->size = 16; b->size = 16;

View File

@@ -27,12 +27,12 @@
#include <config.h> #include <config.h>
#include <glib.h> #include <glib.h>
#include <widgets/widget.h>
#include <widgets/textbox.h>
#include <widgets/scrollbar.h>
#include <widgets/icon.h>
#include <widgets/box.h> #include <widgets/box.h>
#include <widgets/icon.h>
#include <widgets/listview.h> #include <widgets/listview.h>
#include <widgets/scrollbar.h>
#include <widgets/textbox.h>
#include <widgets/widget.h>
#include "settings.h" #include "settings.h"
#include "theme.h" #include "theme.h"
@@ -51,24 +51,19 @@
#define BARVIEW ROFI_ORIENTATION_HORIZONTAL #define BARVIEW ROFI_ORIENTATION_HORIZONTAL
/** /**
* The moving direction of the selection, this (in barview) affects the scrolling. * The moving direction of the selection, this (in barview) affects the
* scrolling.
*/ */
typedef enum typedef enum { LEFT_TO_RIGHT = 0, RIGHT_TO_LEFT = 1 } MoveDirection;
{
LEFT_TO_RIGHT = 0,
RIGHT_TO_LEFT = 1
} MoveDirection;
typedef struct typedef struct {
{
box *box; box *box;
textbox *textbox; textbox *textbox;
textbox *index; textbox *index;
icon *icon; icon *icon;
} _listview_row; } _listview_row;
struct _listview struct _listview {
{
widget widget; widget widget;
RofiOrientation type; RofiOrientation type;
@@ -121,8 +116,7 @@ struct _listview
PangoEllipsizeMode emode; PangoEllipsizeMode emode;
/** Barview */ /** Barview */
struct struct {
{
MoveDirection direction; MoveDirection direction;
unsigned int cur_visible; unsigned int cur_visible;
} barview; } barview;
@@ -141,8 +135,7 @@ const char *const listview_theme_prop_names[][3] = {
{"normal.active", "selected.active", "alternate.active"}, {"normal.active", "selected.active", "alternate.active"},
}; };
static void listview_set_state ( _listview_row r, TextBoxFontType tbft ) static void listview_set_state(_listview_row r, TextBoxFontType tbft) {
{
widget *w = WIDGET(r.box); widget *w = WIDGET(r.box);
TextBoxFontType t = tbft & STATE_MASK; TextBoxFontType t = tbft & STATE_MASK;
if (w == NULL) { if (w == NULL) {
@@ -152,8 +145,7 @@ static void listview_set_state ( _listview_row r, TextBoxFontType tbft )
if (t == (URGENT | ACTIVE)) { if (t == (URGENT | ACTIVE)) {
t = ACTIVE; t = ACTIVE;
} }
switch ( ( tbft & FMOD_MASK ) ) switch ((tbft & FMOD_MASK)) {
{
case HIGHLIGHT: case HIGHLIGHT:
widget_set_state(w, listview_theme_prop_names[t][1]); widget_set_state(w, listview_theme_prop_names[t][1]);
break; break;
@@ -165,38 +157,40 @@ static void listview_set_state ( _listview_row r, TextBoxFontType tbft )
break; break;
} }
} }
static void listview_add_widget ( listview *lv, _listview_row *row, widget *wid, const char *label ) static void listview_add_widget(listview *lv, _listview_row *row, widget *wid,
{ const char *label) {
TextboxFlags flags = (lv->multi_select) ? TB_INDICATOR : 0; TextboxFlags flags = (lv->multi_select) ? TB_INDICATOR : 0;
if (strcasecmp(label, "element-icon") == 0) { if (strcasecmp(label, "element-icon") == 0) {
row->icon = icon_create(WIDGET(wid), "element-icon"); row->icon = icon_create(WIDGET(wid), "element-icon");
box_add((box *)wid, WIDGET(row->icon), FALSE); box_add((box *)wid, WIDGET(row->icon), FALSE);
} } else if (strcasecmp(label, "element-text") == 0) {
else if ( strcasecmp ( label, "element-text" ) == 0 ) { row->textbox =
row->textbox = textbox_create ( WIDGET ( wid ), WIDGET_TYPE_TEXTBOX_TEXT, "element-text", TB_AUTOHEIGHT | flags, NORMAL, "DDD", 0, 0 ); textbox_create(WIDGET(wid), WIDGET_TYPE_TEXTBOX_TEXT, "element-text",
TB_AUTOHEIGHT | flags, NORMAL, "DDD", 0, 0);
box_add((box *)wid, WIDGET(row->textbox), TRUE); box_add((box *)wid, WIDGET(row->textbox), TRUE);
} } else if (strcasecmp(label, "element-index") == 0) {
else if ( strcasecmp ( label, "element-index" ) == 0 ) { row->index =
row->index = textbox_create ( WIDGET ( wid ), WIDGET_TYPE_TEXTBOX_TEXT, "element-index", TB_AUTOHEIGHT, NORMAL, " ", 0, 0 ); textbox_create(WIDGET(wid), WIDGET_TYPE_TEXTBOX_TEXT, "element-index",
TB_AUTOHEIGHT, NORMAL, " ", 0, 0);
box_add((box *)wid, WIDGET(row->index), FALSE); box_add((box *)wid, WIDGET(row->index), FALSE);
} } else {
else {
widget *wid2 = (widget *)box_create(wid, label, ROFI_ORIENTATION_VERTICAL); widget *wid2 = (widget *)box_create(wid, label, ROFI_ORIENTATION_VERTICAL);
box_add((box *)wid, WIDGET(wid2), TRUE); box_add((box *)wid, WIDGET(wid2), TRUE);
GList *list = rofi_theme_get_list(WIDGET(wid2), "children", ""); GList *list = rofi_theme_get_list(WIDGET(wid2), "children", "");
for ( GList *iter = g_list_first ( list ); iter != NULL; iter = g_list_next ( iter ) ) { for (GList *iter = g_list_first(list); iter != NULL;
iter = g_list_next(iter)) {
listview_add_widget(lv, row, wid2, (const char *)iter->data); listview_add_widget(lv, row, wid2, (const char *)iter->data);
} }
} }
} }
static void listview_create_row ( listview *lv, _listview_row *row ) static void listview_create_row(listview *lv, _listview_row *row) {
{
row->box = box_create(WIDGET(lv), "element", ROFI_ORIENTATION_HORIZONTAL); row->box = box_create(WIDGET(lv), "element", ROFI_ORIENTATION_HORIZONTAL);
widget_set_type(WIDGET(row->box), WIDGET_TYPE_LISTVIEW_ELEMENT); widget_set_type(WIDGET(row->box), WIDGET_TYPE_LISTVIEW_ELEMENT);
GList *list = NULL; GList *list = NULL;
if (config.show_icons) { if (config.show_icons) {
list = rofi_theme_get_list ( WIDGET ( row->box ), "children", "element-icon,element-text" ); list = rofi_theme_get_list(WIDGET(row->box), "children",
"element-icon,element-text");
} else { } else {
list = rofi_theme_get_list(WIDGET(row->box), "children", "element-text"); list = rofi_theme_get_list(WIDGET(row->box), "children", "element-text");
} }
@@ -205,7 +199,8 @@ static void listview_create_row ( listview *lv, _listview_row *row )
row->icon = NULL; row->icon = NULL;
row->index = NULL; row->index = NULL;
for ( GList *iter = g_list_first ( list ); iter != NULL; iter = g_list_next ( iter ) ) { for (GList *iter = g_list_first(list); iter != NULL;
iter = g_list_next(iter)) {
listview_add_widget(lv, row, WIDGET(row->box), (const char *)iter->data); listview_add_widget(lv, row, WIDGET(row->box), (const char *)iter->data);
} }
g_list_free_full(list, g_free); g_list_free_full(list, g_free);
@@ -213,8 +208,7 @@ static void listview_create_row ( listview *lv, _listview_row *row )
static int listview_get_desired_height(widget *wid); static int listview_get_desired_height(widget *wid);
static void listview_free ( widget *wid ) static void listview_free(widget *wid) {
{
listview *lv = (listview *)wid; listview *lv = (listview *)wid;
for (unsigned int i = 0; i < lv->cur_elements; i++) { for (unsigned int i = 0; i < lv->cur_elements; i++) {
widget_free(WIDGET(lv->boxes[i].box)); widget_free(WIDGET(lv->boxes[i].box));
@@ -225,8 +219,7 @@ static void listview_free ( widget *wid )
widget_free(WIDGET(lv->scrollbar)); widget_free(WIDGET(lv->scrollbar));
g_free(lv); g_free(lv);
} }
static unsigned int scroll_per_page_barview ( listview *lv ) static unsigned int scroll_per_page_barview(listview *lv) {
{
unsigned int offset = lv->last_offset; unsigned int offset = lv->last_offset;
// selected row is always visible. // selected row is always visible.
@@ -234,25 +227,24 @@ static unsigned int scroll_per_page_barview ( listview *lv )
if (lv->selected < lv->last_offset) { if (lv->selected < lv->last_offset) {
offset = lv->selected; offset = lv->selected;
lv->rchanged = TRUE; lv->rchanged = TRUE;
} } else if (lv->selected >= (lv->last_offset + lv->barview.cur_visible)) {
else if ( lv->selected >= ( lv->last_offset + lv->barview.cur_visible ) ) {
offset = lv->selected; offset = lv->selected;
lv->rchanged = TRUE; lv->rchanged = TRUE;
} }
return offset; return offset;
} }
static unsigned int scroll_per_page ( listview * lv ) static unsigned int scroll_per_page(listview *lv) {
{
int offset = 0; int offset = 0;
// selected row is always visible. // selected row is always visible.
// If selected is visible do not scroll. // If selected is visible do not scroll.
if ( ( ( lv->selected - ( lv->last_offset ) ) < ( lv->max_elements ) ) && ( lv->selected >= ( lv->last_offset ) ) ) { if (((lv->selected - (lv->last_offset)) < (lv->max_elements)) &&
(lv->selected >= (lv->last_offset))) {
offset = lv->last_offset; offset = lv->last_offset;
} } else {
else{
// Do paginating // Do paginating
unsigned int page = ( lv->max_elements > 0 ) ? ( lv->selected / lv->max_elements ) : 0; unsigned int page =
(lv->max_elements > 0) ? (lv->selected / lv->max_elements) : 0;
offset = page * lv->max_elements; offset = page * lv->max_elements;
if (page != lv->cur_page) { if (page != lv->cur_page) {
lv->cur_page = page; lv->cur_page = page;
@@ -264,8 +256,7 @@ static unsigned int scroll_per_page ( listview * lv )
return offset; return offset;
} }
static unsigned int scroll_continious ( listview *lv ) static unsigned int scroll_continious(listview *lv) {
{
unsigned int middle = (lv->max_rows - ((lv->max_rows & 1) == 0)) / 2; unsigned int middle = (lv->max_rows - ((lv->max_rows & 1) == 0)) / 2;
unsigned int offset = 0; unsigned int offset = 0;
if (lv->selected > middle) { if (lv->selected > middle) {
@@ -285,37 +276,34 @@ static unsigned int scroll_continious ( listview *lv )
return offset; return offset;
} }
static void update_element ( listview *lv, unsigned int tb, unsigned int index, gboolean full ) static void update_element(listview *lv, unsigned int tb, unsigned int index,
{ gboolean full) {
// Select drawing mode // Select drawing mode
TextBoxFontType type = (index & 1) == 0 ? NORMAL : ALT; TextBoxFontType type = (index & 1) == 0 ? NORMAL : ALT;
type = (index) == lv->selected ? HIGHLIGHT : type; type = (index) == lv->selected ? HIGHLIGHT : type;
if (lv->boxes[tb].index) { if (lv->boxes[tb].index) {
if (index < 10) { if (index < 10) {
char str[2] = { char str[2] = {((index + 1) % 10) + '0', '\0'};
( ( index + 1 ) % 10 ) + '0',
'\0'
};
textbox_text(lv->boxes[tb].index, str); textbox_text(lv->boxes[tb].index, str);
} } else {
else {
textbox_text(lv->boxes[tb].index, " "); textbox_text(lv->boxes[tb].index, " ");
} }
} }
if (lv->callback) { if (lv->callback) {
lv->callback ( lv->boxes[tb].textbox, lv->boxes[tb].icon, index, lv->udata, &type, full ); lv->callback(lv->boxes[tb].textbox, lv->boxes[tb].icon, index, lv->udata,
&type, full);
listview_set_state(lv->boxes[tb], type); listview_set_state(lv->boxes[tb], type);
} }
} }
static void barview_draw ( widget *wid, cairo_t *draw ) static void barview_draw(widget *wid, cairo_t *draw) {
{
unsigned int offset = 0; unsigned int offset = 0;
listview *lv = (listview *)wid; listview *lv = (listview *)wid;
offset = scroll_per_page_barview(lv); offset = scroll_per_page_barview(lv);
lv->last_offset = offset; lv->last_offset = offset;
int spacing_hori = distance_get_pixel ( lv->spacing, ROFI_ORIENTATION_HORIZONTAL ); int spacing_hori =
distance_get_pixel(lv->spacing, ROFI_ORIENTATION_HORIZONTAL);
int left_offset = widget_padding_get_left(wid); int left_offset = widget_padding_get_left(wid);
int right_offset = lv->widget.w - widget_padding_get_right(wid); int right_offset = lv->widget.w - widget_padding_get_right(wid);
@@ -347,9 +335,9 @@ static void barview_draw ( widget *wid, cairo_t *draw )
first = FALSE; first = FALSE;
lv->barview.cur_visible++; lv->barview.cur_visible++;
} }
} } else {
else { for (unsigned int i = 0;
for ( unsigned int i = 0; i < lv->cur_elements && width > 0 && i <= offset; i++ ) { i < lv->cur_elements && width > 0 && i <= offset; i++) {
update_element(lv, i, offset - i, TRUE); update_element(lv, i, offset - i, TRUE);
int twidth = widget_get_desired_width(WIDGET(lv->boxes[i].box)); int twidth = widget_get_desired_width(WIDGET(lv->boxes[i].box));
if (twidth >= width) { if (twidth >= width) {
@@ -378,8 +366,7 @@ static void barview_draw ( widget *wid, cairo_t *draw )
} }
} }
lv->rchanged = FALSE; lv->rchanged = FALSE;
} } else {
else {
for (unsigned int i = 0; i < lv->barview.cur_visible; i++) { for (unsigned int i = 0; i < lv->barview.cur_visible; i++) {
update_element(lv, i, i + offset, TRUE); update_element(lv, i, i + offset, TRUE);
widget_draw(WIDGET(lv->boxes[i].box), draw); widget_draw(WIDGET(lv->boxes[i].box), draw);
@@ -388,14 +375,12 @@ static void barview_draw ( widget *wid, cairo_t *draw )
} }
} }
static void listview_draw ( widget *wid, cairo_t *draw ) static void listview_draw(widget *wid, cairo_t *draw) {
{
unsigned int offset = 0; unsigned int offset = 0;
listview *lv = (listview *)wid; listview *lv = (listview *)wid;
if (lv->scroll_type == LISTVIEW_SCROLL_CONTINIOUS) { if (lv->scroll_type == LISTVIEW_SCROLL_CONTINIOUS) {
offset = scroll_continious(lv); offset = scroll_continious(lv);
} } else {
else {
offset = scroll_per_page(lv); offset = scroll_per_page(lv);
} }
// Set these all together to make sure they update consistently. // Set these all together to make sure they update consistently.
@@ -403,13 +388,13 @@ static void listview_draw ( widget *wid, cairo_t *draw )
scrollbar_set_handle_length(lv->scrollbar, lv->cur_columns * lv->max_rows); scrollbar_set_handle_length(lv->scrollbar, lv->cur_columns * lv->max_rows);
if (lv->reverse) { if (lv->reverse) {
scrollbar_set_handle(lv->scrollbar, lv->req_elements - lv->selected - 1); scrollbar_set_handle(lv->scrollbar, lv->req_elements - lv->selected - 1);
} } else {
else {
scrollbar_set_handle(lv->scrollbar, lv->selected); scrollbar_set_handle(lv->scrollbar, lv->selected);
} }
lv->last_offset = offset; lv->last_offset = offset;
int spacing_vert = distance_get_pixel(lv->spacing, ROFI_ORIENTATION_VERTICAL); int spacing_vert = distance_get_pixel(lv->spacing, ROFI_ORIENTATION_VERTICAL);
int spacing_hori = distance_get_pixel ( lv->spacing, ROFI_ORIENTATION_HORIZONTAL ); int spacing_hori =
distance_get_pixel(lv->spacing, ROFI_ORIENTATION_HORIZONTAL);
int left_offset = widget_padding_get_left(wid); int left_offset = widget_padding_get_left(wid);
int top_offset = widget_padding_get_top(wid); int top_offset = widget_padding_get_top(wid);
@@ -428,9 +413,11 @@ static void listview_draw ( widget *wid, cairo_t *draw )
width -= spacing_hori; width -= spacing_hori;
width -= widget_get_width(WIDGET(lv->scrollbar)); width -= widget_get_width(WIDGET(lv->scrollbar));
} }
unsigned int element_width = ( width - spacing_hori * ( lv->cur_columns - 1 ) ) / lv->cur_columns; unsigned int element_width =
(width - spacing_hori * (lv->cur_columns - 1)) / lv->cur_columns;
int d = width - ( element_width + spacing_hori ) * ( lv->cur_columns - 1 ) - element_width; int d = width - (element_width + spacing_hori) * (lv->cur_columns - 1) -
element_width;
if (lv->cur_columns > 1) { if (lv->cur_columns > 1) {
int diff = d / (lv->cur_columns - 1); int diff = d / (lv->cur_columns - 1);
if (diff >= 1) { if (diff >= 1) {
@@ -439,28 +426,35 @@ static void listview_draw ( widget *wid, cairo_t *draw )
} }
} }
for (unsigned int i = 0; i < max; i++) { for (unsigned int i = 0; i < max; i++) {
unsigned int ex = left_offset + ( ( i ) / lv->max_rows ) * ( element_width + spacing_hori ); unsigned int ex =
left_offset + ((i) / lv->max_rows) * (element_width + spacing_hori);
if ((i) / lv->max_rows == (lv->cur_columns - 1)) { if ((i) / lv->max_rows == (lv->cur_columns - 1)) {
ex += d; ex += d;
} }
if (lv->reverse) { if (lv->reverse) {
unsigned int ey = wid->h - ( widget_padding_get_bottom ( wid ) + ( ( i ) % lv->max_rows ) * ( lv->element_height + spacing_vert ) ) - lv->element_height; unsigned int ey =
wid->h -
(widget_padding_get_bottom(wid) +
((i) % lv->max_rows) * (lv->element_height + spacing_vert)) -
lv->element_height;
widget_move(WIDGET(lv->boxes[i].box), ex, ey); widget_move(WIDGET(lv->boxes[i].box), ex, ey);
widget_resize ( WIDGET ( lv->boxes[i].box ), element_width, lv->element_height ); widget_resize(WIDGET(lv->boxes[i].box), element_width,
} lv->element_height);
else { } else {
unsigned int ey = top_offset + ( ( i ) % lv->max_rows ) * ( lv->element_height + spacing_vert ); unsigned int ey =
top_offset +
((i) % lv->max_rows) * (lv->element_height + spacing_vert);
widget_move(WIDGET(lv->boxes[i].box), ex, ey); widget_move(WIDGET(lv->boxes[i].box), ex, ey);
widget_resize ( WIDGET ( lv->boxes[i].box ), element_width, lv->element_height ); widget_resize(WIDGET(lv->boxes[i].box), element_width,
lv->element_height);
} }
update_element(lv, i, i + offset, TRUE); update_element(lv, i, i + offset, TRUE);
widget_draw(WIDGET(lv->boxes[i].box), draw); widget_draw(WIDGET(lv->boxes[i].box), draw);
} }
lv->rchanged = FALSE; lv->rchanged = FALSE;
} } else {
else {
for (unsigned int i = 0; i < max; i++) { for (unsigned int i = 0; i < max; i++) {
update_element(lv, i, i + offset, TRUE); update_element(lv, i, i + offset, TRUE);
widget_draw(WIDGET(lv->boxes[i].box), draw); widget_draw(WIDGET(lv->boxes[i].box), draw);
@@ -469,24 +463,24 @@ static void listview_draw ( widget *wid, cairo_t *draw )
} }
widget_draw(WIDGET(lv->scrollbar), draw); widget_draw(WIDGET(lv->scrollbar), draw);
} }
static WidgetTriggerActionResult listview_element_trigger_action ( widget *wid, MouseBindingListviewElementAction action, gint x, gint y, void *user_data ); static WidgetTriggerActionResult
listview_element_trigger_action(widget *wid,
MouseBindingListviewElementAction action,
gint x, gint y, void *user_data);
static gboolean listview_element_motion_notify(widget *wid, gint x, gint y); static gboolean listview_element_motion_notify(widget *wid, gint x, gint y);
static void _listview_draw ( widget *wid, cairo_t *draw ) static void _listview_draw(widget *wid, cairo_t *draw) {
{
listview *lv = (listview *)wid; listview *lv = (listview *)wid;
if (lv->type == LISTVIEW) { if (lv->type == LISTVIEW) {
listview_draw(wid, draw); listview_draw(wid, draw);
} } else {
else {
barview_draw(wid, draw); barview_draw(wid, draw);
} }
} }
/** /**
* State names used for theming. * State names used for theming.
*/ */
static void listview_recompute_elements ( listview *lv ) static void listview_recompute_elements(listview *lv) {
{
unsigned int newne = 0; unsigned int newne = 0;
if (lv->max_rows == 0) { if (lv->max_rows == 0) {
return; return;
@@ -494,8 +488,7 @@ static void listview_recompute_elements ( listview *lv )
if (!(lv->fixed_columns) && lv->req_elements < lv->max_elements) { if (!(lv->fixed_columns) && lv->req_elements < lv->max_elements) {
newne = lv->req_elements; newne = lv->req_elements;
lv->cur_columns = (lv->req_elements + (lv->max_rows - 1)) / lv->max_rows; lv->cur_columns = (lv->req_elements + (lv->max_rows - 1)) / lv->max_rows;
} } else {
else {
newne = MIN(lv->req_elements, lv->max_elements); newne = MIN(lv->req_elements, lv->max_elements);
lv->cur_columns = lv->menu_columns; lv->cur_columns = lv->menu_columns;
} }
@@ -507,7 +500,8 @@ static void listview_recompute_elements ( listview *lv )
for (unsigned int i = lv->cur_elements; i < newne; i++) { for (unsigned int i = lv->cur_elements; i < newne; i++) {
listview_create_row(lv, &(lv->boxes[i])); listview_create_row(lv, &(lv->boxes[i]));
widget *wid = WIDGET(lv->boxes[i].box); widget *wid = WIDGET(lv->boxes[i].box);
widget_set_trigger_action_handler ( wid, listview_element_trigger_action, lv ); widget_set_trigger_action_handler(wid, listview_element_trigger_action,
lv);
if (wid != NULL) { if (wid != NULL) {
wid->motion_notify = listview_element_motion_notify; wid->motion_notify = listview_element_motion_notify;
} }
@@ -519,8 +513,7 @@ static void listview_recompute_elements ( listview *lv )
lv->cur_elements = newne; lv->cur_elements = newne;
} }
void listview_set_num_elements ( listview *lv, unsigned int rows ) void listview_set_num_elements(listview *lv, unsigned int rows) {
{
if (lv == NULL) { if (lv == NULL) {
return; return;
} }
@@ -534,16 +527,14 @@ void listview_set_num_elements ( listview *lv, unsigned int rows )
TICK_N("queue redraw"); TICK_N("queue redraw");
} }
unsigned int listview_get_selected ( listview *lv ) unsigned int listview_get_selected(listview *lv) {
{
if (lv != NULL) { if (lv != NULL) {
return lv->selected; return lv->selected;
} }
return 0; return 0;
} }
void listview_set_selected ( listview *lv, unsigned int selected ) void listview_set_selected(listview *lv, unsigned int selected) {
{
if (lv && lv->req_elements > 0) { if (lv && lv->req_elements > 0) {
lv->selected = MIN(selected, lv->req_elements - 1); lv->selected = MIN(selected, lv->req_elements - 1);
lv->barview.direction = LEFT_TO_RIGHT; lv->barview.direction = LEFT_TO_RIGHT;
@@ -551,8 +542,7 @@ void listview_set_selected ( listview *lv, unsigned int selected )
} }
} }
static void listview_resize ( widget *wid, short w, short h ) static void listview_resize(widget *wid, short w, short h) {
{
listview *lv = (listview *)wid; listview *lv = (listview *)wid;
lv->widget.w = MAX(0, w); lv->widget.w = MAX(0, w);
lv->widget.h = MAX(0, h); lv->widget.h = MAX(0, h);
@@ -562,10 +552,12 @@ static void listview_resize ( widget *wid, short w, short h )
lv->max_elements = lv->max_rows * lv->menu_columns; lv->max_elements = lv->max_rows * lv->menu_columns;
widget_move(WIDGET(lv->scrollbar), widget_move(WIDGET(lv->scrollbar),
lv->widget.w - widget_padding_get_right ( WIDGET ( lv ) ) - widget_get_width ( WIDGET ( lv->scrollbar ) ), lv->widget.w - widget_padding_get_right(WIDGET(lv)) -
widget_get_width(WIDGET(lv->scrollbar)),
widget_padding_get_top(WIDGET(lv))); widget_padding_get_top(WIDGET(lv)));
widget_resize ( WIDGET ( lv->scrollbar ), widget_get_width ( WIDGET ( lv->scrollbar ) ), height ); widget_resize(WIDGET(lv->scrollbar), widget_get_width(WIDGET(lv->scrollbar)),
height);
if (lv->type == BARVIEW) { if (lv->type == BARVIEW) {
lv->max_elements = lv->menu_lines; lv->max_elements = lv->menu_lines;
@@ -575,12 +567,13 @@ static void listview_resize ( widget *wid, short w, short h )
widget_queue_redraw(wid); widget_queue_redraw(wid);
} }
static widget *listview_find_mouse_target ( widget *wid, WidgetType type, gint x, gint y ) static widget *listview_find_mouse_target(widget *wid, WidgetType type, gint x,
{ gint y) {
widget *target = NULL; widget *target = NULL;
gint rx, ry; gint rx, ry;
listview *lv = (listview *)wid; listview *lv = (listview *)wid;
if ( widget_enabled ( WIDGET ( lv->scrollbar ) ) && widget_intersect ( WIDGET ( lv->scrollbar ), x, y ) ) { if (widget_enabled(WIDGET(lv->scrollbar)) &&
widget_intersect(WIDGET(lv->scrollbar), x, y)) {
rx = x - widget_get_x_pos(WIDGET(lv->scrollbar)); rx = x - widget_get_x_pos(WIDGET(lv->scrollbar));
ry = y - widget_get_y_pos(WIDGET(lv->scrollbar)); ry = y - widget_get_y_pos(WIDGET(lv->scrollbar));
target = widget_find_mouse_target(WIDGET(lv->scrollbar), type, rx, ry); target = widget_find_mouse_target(WIDGET(lv->scrollbar), type, rx, ry);
@@ -600,11 +593,12 @@ static widget *listview_find_mouse_target ( widget *wid, WidgetType type, gint x
return target; return target;
} }
static WidgetTriggerActionResult listview_trigger_action ( widget *wid, MouseBindingListviewAction action, G_GNUC_UNUSED gint x, G_GNUC_UNUSED gint y, G_GNUC_UNUSED void *user_data ) static WidgetTriggerActionResult
{ listview_trigger_action(widget *wid, MouseBindingListviewAction action,
G_GNUC_UNUSED gint x, G_GNUC_UNUSED gint y,
G_GNUC_UNUSED void *user_data) {
listview *lv = (listview *)wid; listview *lv = (listview *)wid;
switch ( action ) switch (action) {
{
case SCROLL_LEFT: case SCROLL_LEFT:
listview_nav_left(lv); listview_nav_left(lv);
break; break;
@@ -621,8 +615,9 @@ static WidgetTriggerActionResult listview_trigger_action ( widget *wid, MouseBin
return WIDGET_TRIGGER_ACTION_RESULT_HANDLED; return WIDGET_TRIGGER_ACTION_RESULT_HANDLED;
} }
static WidgetTriggerActionResult listview_element_trigger_action ( widget *wid, MouseBindingListviewElementAction action, G_GNUC_UNUSED gint x, G_GNUC_UNUSED gint y, void *user_data ) static WidgetTriggerActionResult listview_element_trigger_action(
{ widget *wid, MouseBindingListviewElementAction action, G_GNUC_UNUSED gint x,
G_GNUC_UNUSED gint y, void *user_data) {
listview *lv = (listview *)user_data; listview *lv = (listview *)user_data;
unsigned int max = MIN(lv->cur_elements, lv->req_elements - lv->last_offset); unsigned int max = MIN(lv->cur_elements, lv->req_elements - lv->last_offset);
unsigned int i; unsigned int i;
@@ -633,8 +628,7 @@ static WidgetTriggerActionResult listview_element_trigger_action ( widget *wid,
} }
gboolean custom = FALSE; gboolean custom = FALSE;
switch ( action ) switch (action) {
{
case SELECT_HOVERED_ENTRY: case SELECT_HOVERED_ENTRY:
listview_set_selected(lv, lv->last_offset + i); listview_set_selected(lv, lv->last_offset + i);
break; break;
@@ -649,8 +643,9 @@ static WidgetTriggerActionResult listview_element_trigger_action ( widget *wid,
return WIDGET_TRIGGER_ACTION_RESULT_HANDLED; return WIDGET_TRIGGER_ACTION_RESULT_HANDLED;
} }
static gboolean listview_element_motion_notify ( widget *wid, G_GNUC_UNUSED gint x, G_GNUC_UNUSED gint y ) static gboolean listview_element_motion_notify(widget *wid,
{ G_GNUC_UNUSED gint x,
G_GNUC_UNUSED gint y) {
listview *lv = (listview *)wid->parent; listview *lv = (listview *)wid->parent;
unsigned int max = MIN(lv->cur_elements, lv->req_elements - lv->last_offset); unsigned int max = MIN(lv->cur_elements, lv->req_elements - lv->last_offset);
unsigned int i; unsigned int i;
@@ -662,8 +657,9 @@ static gboolean listview_element_motion_notify ( widget *wid, G_GNUC_UNUSED gint
return TRUE; return TRUE;
} }
listview *listview_create ( widget *parent, const char *name, listview_update_callback cb, void *udata, unsigned int eh, gboolean reverse ) listview *listview_create(widget *parent, const char *name,
{ listview_update_callback cb, void *udata,
unsigned int eh, gboolean reverse) {
listview *lv = g_malloc0(sizeof(listview)); listview *lv = g_malloc0(sizeof(listview));
widget_init(WIDGET(lv), parent, WIDGET_TYPE_LISTVIEW, name); widget_init(WIDGET(lv), parent, WIDGET_TYPE_LISTVIEW, name);
lv->listview_name = g_strdup(name); lv->listview_name = g_strdup(name);
@@ -686,9 +682,9 @@ listview *listview_create ( widget *parent, const char *name, listview_update_ca
char buff[lv->eh * 2 + 1]; char buff[lv->eh * 2 + 1];
memset(buff, '\0', lv->eh * 2 + 1); memset(buff, '\0', lv->eh * 2 + 1);
for (unsigned int i = 0; i < (lv->eh - 1); i++) { for (unsigned int i = 0; i < (lv->eh - 1); i++) {
buff[i * 2] = 'a'; buff[i * 2 + 1] = '\n'; buff[i * 2] = 'a';
} buff[i * 2 + 1] = '\n';
; };
textbox_text(row.textbox, buff); textbox_text(row.textbox, buff);
} }
lv->element_height = widget_get_desired_height(WIDGET(row.box)); lv->element_height = widget_get_desired_height(WIDGET(row.box));
@@ -699,18 +695,22 @@ listview *listview_create ( widget *parent, const char *name, listview_update_ca
// Some settings. // Some settings.
lv->spacing = rofi_theme_get_distance(WIDGET(lv), "spacing", DEFAULT_SPACING); lv->spacing = rofi_theme_get_distance(WIDGET(lv), "spacing", DEFAULT_SPACING);
lv->menu_columns = rofi_theme_get_integer ( WIDGET ( lv ), "columns", DEFAULT_MENU_COLUMNS); lv->menu_columns =
lv->fixed_num_lines = rofi_theme_get_boolean ( WIDGET ( lv ), "fixed-height", config.fixed_num_lines ); rofi_theme_get_integer(WIDGET(lv), "columns", DEFAULT_MENU_COLUMNS);
lv->fixed_num_lines = rofi_theme_get_boolean(WIDGET(lv), "fixed-height",
config.fixed_num_lines);
lv->dynamic = rofi_theme_get_boolean(WIDGET(lv), "dynamic", TRUE); lv->dynamic = rofi_theme_get_boolean(WIDGET(lv), "dynamic", TRUE);
lv->reverse = rofi_theme_get_boolean(WIDGET(lv), "reverse", reverse); lv->reverse = rofi_theme_get_boolean(WIDGET(lv), "reverse", reverse);
lv->cycle = rofi_theme_get_boolean(WIDGET(lv), "cycle", config.cycle); lv->cycle = rofi_theme_get_boolean(WIDGET(lv), "cycle", config.cycle);
lv->fixed_columns = rofi_theme_get_boolean ( WIDGET ( lv ), "fixed-columns", FALSE ); lv->fixed_columns =
rofi_theme_get_boolean(WIDGET(lv), "fixed-columns", FALSE);
lv->type = rofi_theme_get_orientation ( WIDGET ( lv ), "layout", ROFI_ORIENTATION_VERTICAL ); lv->type = rofi_theme_get_orientation(WIDGET(lv), "layout",
ROFI_ORIENTATION_VERTICAL);
if (lv->type == LISTVIEW) { if (lv->type == LISTVIEW) {
listview_set_show_scrollbar ( lv, rofi_theme_get_boolean ( WIDGET ( lv ), "scrollbar", FALSE ) ); listview_set_show_scrollbar(
} lv, rofi_theme_get_boolean(WIDGET(lv), "scrollbar", FALSE));
else { } else {
listview_set_show_scrollbar(lv, FALSE); listview_set_show_scrollbar(lv, FALSE);
} }
return lv; return lv;
@@ -720,8 +720,7 @@ listview *listview_create ( widget *parent, const char *name, listview_update_ca
* Navigation commands. * Navigation commands.
*/ */
static void listview_nav_up_int ( listview *lv ) static void listview_nav_up_int(listview *lv) {
{
if (lv == NULL) { if (lv == NULL) {
return; return;
} }
@@ -735,46 +734,43 @@ static void listview_nav_up_int ( listview *lv )
lv->barview.direction = RIGHT_TO_LEFT; lv->barview.direction = RIGHT_TO_LEFT;
widget_queue_redraw(WIDGET(lv)); widget_queue_redraw(WIDGET(lv));
} }
static void listview_nav_down_int ( listview *lv ) static void listview_nav_down_int(listview *lv) {
{
if (lv == NULL) { if (lv == NULL) {
return; return;
} }
if ( lv->req_elements == 0 || ( lv->selected == ( lv->req_elements - 1 ) && !lv->cycle ) ) { if (lv->req_elements == 0 ||
(lv->selected == (lv->req_elements - 1) && !lv->cycle)) {
return; return;
} }
lv->selected = lv->selected < lv->req_elements - 1 ? MIN ( lv->req_elements - 1, lv->selected + 1 ) : 0; lv->selected = lv->selected < lv->req_elements - 1
? MIN(lv->req_elements - 1, lv->selected + 1)
: 0;
lv->barview.direction = LEFT_TO_RIGHT; lv->barview.direction = LEFT_TO_RIGHT;
widget_queue_redraw(WIDGET(lv)); widget_queue_redraw(WIDGET(lv));
} }
void listview_nav_up ( listview *lv ) void listview_nav_up(listview *lv) {
{
if (lv == NULL) { if (lv == NULL) {
return; return;
} }
if (lv->reverse) { if (lv->reverse) {
listview_nav_down_int(lv); listview_nav_down_int(lv);
} } else {
else {
listview_nav_up_int(lv); listview_nav_up_int(lv);
} }
} }
void listview_nav_down ( listview *lv ) void listview_nav_down(listview *lv) {
{
if (lv == NULL) { if (lv == NULL) {
return; return;
} }
if (lv->reverse) { if (lv->reverse) {
listview_nav_up_int(lv); listview_nav_up_int(lv);
} } else {
else {
listview_nav_down_int(lv); listview_nav_down_int(lv);
} }
} }
void listview_nav_left ( listview *lv ) void listview_nav_left(listview *lv) {
{
if (lv == NULL) { if (lv == NULL) {
return; return;
} }
@@ -787,8 +783,7 @@ void listview_nav_left ( listview *lv )
widget_queue_redraw(WIDGET(lv)); widget_queue_redraw(WIDGET(lv));
} }
} }
void listview_nav_right ( listview *lv ) void listview_nav_right(listview *lv) {
{
if (lv == NULL) { if (lv == NULL) {
return; return;
} }
@@ -802,11 +797,10 @@ void listview_nav_right ( listview *lv )
if ((lv->selected + lv->max_rows) < lv->req_elements) { if ((lv->selected + lv->max_rows) < lv->req_elements) {
lv->selected += lv->max_rows; lv->selected += lv->max_rows;
widget_queue_redraw(WIDGET(lv)); widget_queue_redraw(WIDGET(lv));
} } else if (lv->selected < (lv->req_elements - 1)) {
else if ( lv->selected < ( lv->req_elements - 1 ) ) {
// We do not want to move to last item, UNLESS the last column is only // We do not want to move to last item, UNLESS the last column is only
// partially filled, then we still want to move column and select last entry. // partially filled, then we still want to move column and select last
// First check the column we are currently in. // entry. First check the column we are currently in.
int col = lv->selected / lv->max_rows; int col = lv->selected / lv->max_rows;
// Check total number of columns. // Check total number of columns.
int ncol = lv->req_elements / lv->max_rows; int ncol = lv->req_elements / lv->max_rows;
@@ -818,16 +812,14 @@ void listview_nav_right ( listview *lv )
} }
} }
static void listview_nav_page_prev_int ( listview *lv ) static void listview_nav_page_prev_int(listview *lv) {
{
if (lv == NULL) { if (lv == NULL) {
return; return;
} }
if (lv->type == BARVIEW) { if (lv->type == BARVIEW) {
if (lv->last_offset == 0) { if (lv->last_offset == 0) {
lv->selected = 0; lv->selected = 0;
} } else {
else {
lv->selected = lv->last_offset - 1; lv->selected = lv->last_offset - 1;
} }
lv->barview.direction = RIGHT_TO_LEFT; lv->barview.direction = RIGHT_TO_LEFT;
@@ -837,14 +829,12 @@ static void listview_nav_page_prev_int ( listview *lv )
if (lv->selected < lv->max_elements) { if (lv->selected < lv->max_elements) {
lv->selected = 0; lv->selected = 0;
} } else {
else{
lv->selected -= (lv->max_elements); lv->selected -= (lv->max_elements);
} }
widget_queue_redraw(WIDGET(lv)); widget_queue_redraw(WIDGET(lv));
} }
static void listview_nav_page_next_int ( listview *lv ) static void listview_nav_page_next_int(listview *lv) {
{
if (lv == NULL) { if (lv == NULL) {
return; return;
} }
@@ -866,33 +856,28 @@ static void listview_nav_page_next_int ( listview *lv )
widget_queue_redraw(WIDGET(lv)); widget_queue_redraw(WIDGET(lv));
} }
void listview_nav_page_prev ( listview *lv ) void listview_nav_page_prev(listview *lv) {
{
if (lv == NULL) { if (lv == NULL) {
return; return;
} }
if (lv->reverse) { if (lv->reverse) {
listview_nav_page_next_int(lv); listview_nav_page_next_int(lv);
} } else {
else {
listview_nav_page_prev_int(lv); listview_nav_page_prev_int(lv);
} }
} }
void listview_nav_page_next ( listview *lv ) void listview_nav_page_next(listview *lv) {
{
if (lv == NULL) { if (lv == NULL) {
return; return;
} }
if (lv->reverse) { if (lv->reverse) {
listview_nav_page_prev_int(lv); listview_nav_page_prev_int(lv);
} } else {
else {
listview_nav_page_next_int(lv); listview_nav_page_next_int(lv);
} }
} }
static int listview_get_desired_height ( widget *wid ) static int listview_get_desired_height(widget *wid) {
{
listview *lv = (listview *)wid; listview *lv = (listview *)wid;
if (lv == NULL || lv->widget.enabled == FALSE) { if (lv == NULL || lv->widget.enabled == FALSE) {
return 0; return 0;
@@ -902,8 +887,7 @@ static int listview_get_desired_height ( widget *wid )
if (!(lv->fixed_num_lines)) { if (!(lv->fixed_num_lines)) {
if (lv->dynamic) { if (lv->dynamic) {
h = MIN(lv->menu_lines, lv->req_elements); h = MIN(lv->menu_lines, lv->req_elements);
} } else {
else {
h = MIN(lv->menu_lines, lv->max_displayed_lines); h = MIN(lv->menu_lines, lv->max_displayed_lines);
} }
} }
@@ -922,76 +906,67 @@ static int listview_get_desired_height ( widget *wid )
return height; return height;
} }
void listview_set_show_scrollbar ( listview *lv, gboolean enabled ) void listview_set_show_scrollbar(listview *lv, gboolean enabled) {
{
if (lv) { if (lv) {
if (enabled) { if (enabled) {
widget_enable(WIDGET(lv->scrollbar)); widget_enable(WIDGET(lv->scrollbar));
} } else {
else {
widget_disable(WIDGET(lv->scrollbar)); widget_disable(WIDGET(lv->scrollbar));
} }
listview_recompute_elements(lv); listview_recompute_elements(lv);
} }
} }
void listview_set_scroll_type ( listview *lv, ScrollType type ) void listview_set_scroll_type(listview *lv, ScrollType type) {
{
if (lv) { if (lv) {
lv->scroll_type = type; lv->scroll_type = type;
} }
} }
void listview_set_mouse_activated_cb ( listview *lv, listview_mouse_activated_cb cb, void *udata ) void listview_set_mouse_activated_cb(listview *lv,
{ listview_mouse_activated_cb cb,
void *udata) {
if (lv) { if (lv) {
lv->mouse_activated = cb; lv->mouse_activated = cb;
lv->mouse_activated_data = udata; lv->mouse_activated_data = udata;
} }
} }
void listview_set_multi_select ( listview *lv, gboolean enable ) void listview_set_multi_select(listview *lv, gboolean enable) {
{
if (lv) { if (lv) {
lv->multi_select = enable; lv->multi_select = enable;
} }
} }
void listview_set_num_lines ( listview *lv, unsigned int num_lines ) void listview_set_num_lines(listview *lv, unsigned int num_lines) {
{
if (lv) { if (lv) {
lv->menu_lines = num_lines; lv->menu_lines = num_lines;
} }
} }
unsigned int listview_get_num_lines ( listview *lv ) unsigned int listview_get_num_lines(listview *lv) {
{
if (lv) { if (lv) {
return lv->menu_lines; return lv->menu_lines;
} }
return 0; return 0;
} }
void listview_set_max_lines ( listview *lv, unsigned int max_lines ) void listview_set_max_lines(listview *lv, unsigned int max_lines) {
{
if (lv) { if (lv) {
lv->max_displayed_lines = max_lines; lv->max_displayed_lines = max_lines;
} }
} }
gboolean listview_get_fixed_num_lines ( listview *lv ) gboolean listview_get_fixed_num_lines(listview *lv) {
{
if (lv) { if (lv) {
return lv->fixed_num_lines; return lv->fixed_num_lines;
} }
return FALSE; return FALSE;
} }
void listview_set_fixed_num_lines ( listview *lv ) void listview_set_fixed_num_lines(listview *lv) {
{
if (lv) { if (lv) {
lv->fixed_num_lines = TRUE; lv->fixed_num_lines = TRUE;
} }
} }
void listview_set_ellipsize_start ( listview *lv ) void listview_set_ellipsize_start(listview *lv) {
{
if (lv) { if (lv) {
lv->emode = PANGO_ELLIPSIZE_START; lv->emode = PANGO_ELLIPSIZE_START;
for (unsigned int i = 0; i < lv->cur_elements; i++) { for (unsigned int i = 0; i < lv->cur_elements; i++) {
@@ -1000,17 +975,14 @@ void listview_set_ellipsize_start ( listview *lv )
} }
} }
void listview_toggle_ellipsizing ( listview *lv ) void listview_toggle_ellipsizing(listview *lv) {
{
if (lv) { if (lv) {
PangoEllipsizeMode mode = lv->emode; PangoEllipsizeMode mode = lv->emode;
if (mode == PANGO_ELLIPSIZE_START) { if (mode == PANGO_ELLIPSIZE_START) {
mode = PANGO_ELLIPSIZE_MIDDLE; mode = PANGO_ELLIPSIZE_MIDDLE;
} } else if (mode == PANGO_ELLIPSIZE_MIDDLE) {
else if ( mode == PANGO_ELLIPSIZE_MIDDLE ) {
mode = PANGO_ELLIPSIZE_END; mode = PANGO_ELLIPSIZE_END;
} } else if (mode == PANGO_ELLIPSIZE_END) {
else if ( mode == PANGO_ELLIPSIZE_END ) {
mode = PANGO_ELLIPSIZE_START; mode = PANGO_ELLIPSIZE_START;
} }
lv->emode = mode; lv->emode = mode;

View File

@@ -25,13 +25,12 @@
* *
*/ */
#include <config.h> #include "widgets/scrollbar.h"
#include <xkbcommon/xkbcommon.h>
#include <glib.h>
#include "widgets/textbox.h"
#include "widgets/icon.h" #include "widgets/icon.h"
#include "widgets/listview.h" #include "widgets/listview.h"
#include "widgets/scrollbar.h" #include "widgets/textbox.h"
#include <glib.h>
#include <xkbcommon/xkbcommon.h>
#include "theme.h" #include "theme.h"
@@ -41,16 +40,14 @@
static void scrollbar_draw(widget *, cairo_t *); static void scrollbar_draw(widget *, cairo_t *);
static void scrollbar_free(widget *); static void scrollbar_free(widget *);
static int scrollbar_get_desired_height ( widget *wid ) static int scrollbar_get_desired_height(widget *wid) {
{
// Want height we are. // Want height we are.
return wid->h; return wid->h;
} }
// TODO // TODO
// This should behave more like a real scrollbar. // This should behave more like a real scrollbar.
guint scrollbar_scroll_get_line ( const scrollbar *sb, int y ) guint scrollbar_scroll_get_line(const scrollbar *sb, int y) {
{
y -= sb->widget.border.top.base.distance; y -= sb->widget.border.top.base.distance;
if (y < 0) { if (y < 0) {
return 0; return 0;
@@ -60,7 +57,8 @@ guint scrollbar_scroll_get_line ( const scrollbar *sb, int y )
return sb->length - 1; return sb->length - 1;
} }
short r = ( sb->length * sb->widget.h ) / ( (double) ( sb->length + sb->pos_length ) ); short r =
(sb->length * sb->widget.h) / ((double)(sb->length + sb->pos_length));
short handle = sb->widget.h - r; short handle = sb->widget.h - r;
double sec = ((r) / (double)(sb->length - 1)); double sec = ((r) / (double)(sb->length - 1));
short half_handle = handle / 2; short half_handle = handle / 2;
@@ -71,16 +69,17 @@ guint scrollbar_scroll_get_line ( const scrollbar *sb, int y )
return MIN(sel, sb->length - 1); return MIN(sel, sb->length - 1);
} }
static void scrollbar_scroll ( scrollbar *sb, int y ) static void scrollbar_scroll(scrollbar *sb, int y) {
{ listview_set_selected((listview *)sb->widget.parent,
listview_set_selected ( (listview *) sb->widget.parent, scrollbar_scroll_get_line ( sb, y ) ); scrollbar_scroll_get_line(sb, y));
} }
static WidgetTriggerActionResult scrollbar_trigger_action ( widget *wid, MouseBindingMouseDefaultAction action, G_GNUC_UNUSED gint x, gint y, G_GNUC_UNUSED void *user_data ) static WidgetTriggerActionResult
{ scrollbar_trigger_action(widget *wid, MouseBindingMouseDefaultAction action,
G_GNUC_UNUSED gint x, gint y,
G_GNUC_UNUSED void *user_data) {
scrollbar *sb = (scrollbar *)wid; scrollbar *sb = (scrollbar *)wid;
switch ( action ) switch (action) {
{
case MOUSE_CLICK_DOWN: case MOUSE_CLICK_DOWN:
return WIDGET_TRIGGER_ACTION_RESULT_GRAB_MOTION_BEGIN; return WIDGET_TRIGGER_ACTION_RESULT_GRAB_MOTION_BEGIN;
case MOUSE_CLICK_UP: case MOUSE_CLICK_UP:
@@ -93,20 +92,20 @@ static WidgetTriggerActionResult scrollbar_trigger_action ( widget *wid, MouseBi
return FALSE; return FALSE;
} }
static gboolean scrollbar_motion_notify ( widget *wid, G_GNUC_UNUSED gint x, gint y ) static gboolean scrollbar_motion_notify(widget *wid, G_GNUC_UNUSED gint x,
{ gint y) {
scrollbar *sb = (scrollbar *)wid; scrollbar *sb = (scrollbar *)wid;
scrollbar_scroll(sb, y); scrollbar_scroll(sb, y);
return TRUE; return TRUE;
} }
scrollbar *scrollbar_create ( widget *parent, const char *name ) scrollbar *scrollbar_create(widget *parent, const char *name) {
{
scrollbar *sb = g_malloc0(sizeof(scrollbar)); scrollbar *sb = g_malloc0(sizeof(scrollbar));
widget_init(WIDGET(sb), parent, WIDGET_TYPE_SCROLLBAR, name); widget_init(WIDGET(sb), parent, WIDGET_TYPE_SCROLLBAR, name);
sb->widget.x = 0; sb->widget.x = 0;
sb->widget.y = 0; sb->widget.y = 0;
sb->width = rofi_theme_get_distance ( WIDGET ( sb ), "handle-width", DEFAULT_SCROLLBAR_WIDTH ); sb->width = rofi_theme_get_distance(WIDGET(sb), "handle-width",
DEFAULT_SCROLLBAR_WIDTH);
int width = distance_get_pixel(sb->width, ROFI_ORIENTATION_HORIZONTAL); int width = distance_get_pixel(sb->width, ROFI_ORIENTATION_HORIZONTAL);
sb->widget.w = widget_padding_get_padding_width(WIDGET(sb)) + width; sb->widget.w = widget_padding_get_padding_width(WIDGET(sb)) + width;
sb->widget.h = widget_padding_get_padding_height(WIDGET(sb)); sb->widget.h = widget_padding_get_padding_height(WIDGET(sb));
@@ -124,28 +123,24 @@ scrollbar *scrollbar_create ( widget *parent, const char *name )
return sb; return sb;
} }
static void scrollbar_free ( widget *wid ) static void scrollbar_free(widget *wid) {
{
scrollbar *sb = (scrollbar *)wid; scrollbar *sb = (scrollbar *)wid;
g_free(sb); g_free(sb);
} }
void scrollbar_set_max_value ( scrollbar *sb, unsigned int max ) void scrollbar_set_max_value(scrollbar *sb, unsigned int max) {
{
if (sb != NULL) { if (sb != NULL) {
sb->length = MAX(1u, max); sb->length = MAX(1u, max);
} }
} }
void scrollbar_set_handle ( scrollbar *sb, unsigned int pos ) void scrollbar_set_handle(scrollbar *sb, unsigned int pos) {
{
if (sb != NULL) { if (sb != NULL) {
sb->pos = MIN(sb->length, pos); sb->pos = MIN(sb->length, pos);
} }
} }
void scrollbar_set_handle_length ( scrollbar *sb, unsigned int pos_length ) void scrollbar_set_handle_length(scrollbar *sb, unsigned int pos_length) {
{
if (sb != NULL) { if (sb != NULL) {
sb->pos_length = MIN(sb->length, MAX(1u, pos_length)); sb->pos_length = MIN(sb->length, MAX(1u, pos_length));
} }
@@ -163,8 +158,7 @@ void scrollbar_set_handle_length ( scrollbar *sb, unsigned int pos_length )
* r ( num+hl ) = num*h * r ( num+hl ) = num*h
* r = (num*h)/(num+hl) * r = (num*h)/(num+hl)
*/ */
static void scrollbar_draw ( widget *wid, cairo_t *draw ) static void scrollbar_draw(widget *wid, cairo_t *draw) {
{
scrollbar *sb = (scrollbar *)wid; scrollbar *sb = (scrollbar *)wid;
unsigned int wh = widget_padding_get_remaining_height(wid); unsigned int wh = widget_padding_get_remaining_height(wid);
// Calculate position and size. // Calculate position and size.
@@ -180,10 +174,8 @@ static void scrollbar_draw ( widget *wid, cairo_t *draw )
// Cap length; // Cap length;
rofi_theme_get_color(WIDGET(sb), "handle-color", draw); rofi_theme_get_color(WIDGET(sb), "handle-color", draw);
cairo_rectangle ( draw, cairo_rectangle(draw, widget_padding_get_left(wid),
widget_padding_get_left ( wid ),
widget_padding_get_top(wid) + y, widget_padding_get_top(wid) + y,
widget_padding_get_remaining_width ( wid ), widget_padding_get_remaining_width(wid), height);
height );
cairo_fill(draw); cairo_fill(draw);
} }

View File

@@ -26,18 +26,17 @@
* *
*/ */
#include <config.h>
#include <xcb/xcb.h>
#include <ctype.h>
#include <string.h>
#include <glib.h>
#include <math.h>
#include "widgets/textbox.h" #include "widgets/textbox.h"
#include "keyb.h"
#include "helper.h"
#include "helper-theme.h" #include "helper-theme.h"
#include "helper.h"
#include "keyb.h"
#include "mode.h" #include "mode.h"
#include "view.h" #include "view.h"
#include <ctype.h>
#include <glib.h>
#include <math.h>
#include <string.h>
#include <xcb/xcb.h>
#include "theme.h" #include "theme.h"
@@ -61,27 +60,23 @@ static TBFontConfig *tbfc_default = NULL;
/** HashMap of previously parsed font descriptions. */ /** HashMap of previously parsed font descriptions. */
static GHashTable *tbfc_cache = NULL; static GHashTable *tbfc_cache = NULL;
static gboolean textbox_blink ( gpointer data ) static gboolean textbox_blink(gpointer data) {
{
textbox *tb = (textbox *)data; textbox *tb = (textbox *)data;
if (tb->blink < 2) { if (tb->blink < 2) {
tb->blink = !tb->blink; tb->blink = !tb->blink;
widget_queue_redraw(WIDGET(tb)); widget_queue_redraw(WIDGET(tb));
rofi_view_queue_redraw(); rofi_view_queue_redraw();
} } else {
else {
tb->blink--; tb->blink--;
} }
return TRUE; return TRUE;
} }
static void textbox_resize ( widget *wid, short w, short h ) static void textbox_resize(widget *wid, short w, short h) {
{
textbox *tb = (textbox *)wid; textbox *tb = (textbox *)wid;
textbox_moveresize(tb, tb->widget.x, tb->widget.y, w, h); textbox_moveresize(tb, tb->widget.x, tb->widget.y, w, h);
} }
static int textbox_get_desired_height ( widget *wid ) static int textbox_get_desired_height(widget *wid) {
{
textbox *tb = (textbox *)wid; textbox *tb = (textbox *)wid;
if ((tb->flags & TB_AUTOHEIGHT) == 0) { if ((tb->flags & TB_AUTOHEIGHT) == 0) {
return tb->widget.h; return tb->widget.h;
@@ -89,17 +84,18 @@ static int textbox_get_desired_height ( widget *wid )
if (tb->changed) { if (tb->changed) {
__textbox_update_pango_text(tb); __textbox_update_pango_text(tb);
} }
int height = textbox_get_estimated_height ( tb, pango_layout_get_line_count ( tb->layout ) ); int height =
textbox_get_estimated_height(tb, pango_layout_get_line_count(tb->layout));
return height; return height;
} }
static WidgetTriggerActionResult textbox_editable_trigger_action ( widget *wid, MouseBindingMouseDefaultAction action, gint x, gint y, G_GNUC_UNUSED void *user_data ) static WidgetTriggerActionResult
{ textbox_editable_trigger_action(widget *wid,
MouseBindingMouseDefaultAction action, gint x,
gint y, G_GNUC_UNUSED void *user_data) {
textbox *tb = (textbox *)wid; textbox *tb = (textbox *)wid;
switch ( action ) switch (action) {
{ case MOUSE_CLICK_DOWN: {
case MOUSE_CLICK_DOWN:
{
gint i; gint i;
// subtract padding on left. // subtract padding on left.
x -= widget_padding_get_left(wid); x -= widget_padding_get_left(wid);
@@ -107,10 +103,10 @@ static WidgetTriggerActionResult textbox_editable_trigger_action ( widget *wid,
// Right of text, move to end. // Right of text, move to end.
if (x >= max) { if (x >= max) {
textbox_cursor_end(tb); textbox_cursor_end(tb);
} } else if (x > 0) {
else if ( x > 0 ) {
// If in range, get index. // If in range, get index.
pango_layout_xy_to_index ( tb->layout, x * PANGO_SCALE, y * PANGO_SCALE, &i, NULL ); pango_layout_xy_to_index(tb->layout, x * PANGO_SCALE, y * PANGO_SCALE, &i,
NULL);
textbox_cursor(tb, i); textbox_cursor(tb, i);
} }
return WIDGET_TRIGGER_ACTION_RESULT_HANDLED; return WIDGET_TRIGGER_ACTION_RESULT_HANDLED;
@@ -123,8 +119,7 @@ static WidgetTriggerActionResult textbox_editable_trigger_action ( widget *wid,
return WIDGET_TRIGGER_ACTION_RESULT_IGNORED; return WIDGET_TRIGGER_ACTION_RESULT_IGNORED;
} }
static void textbox_initialize_font ( textbox *tb ) static void textbox_initialize_font(textbox *tb) {
{
tb->tbfc = tbfc_default; tb->tbfc = tbfc_default;
const char *font = rofi_theme_get_string(WIDGET(tb), "font", NULL); const char *font = rofi_theme_get_string(WIDGET(tb), "font", NULL);
if (font) { if (font) {
@@ -143,10 +138,10 @@ static void textbox_initialize_font ( textbox *tb )
tbfc->height = rect.y + rect.height; tbfc->height = rect.y + rect.height;
g_object_unref(layout); g_object_unref(layout);
// Cast away consts. (*yuck*) because table_insert does not know it is const. // Cast away consts. (*yuck*) because table_insert does not know it is
// const.
g_hash_table_insert(tbfc_cache, (char *)font, tbfc); g_hash_table_insert(tbfc_cache, (char *)font, tbfc);
} } else {
else {
pango_font_description_free(tbfc->pfd); pango_font_description_free(tbfc->pfd);
g_free(tbfc); g_free(tbfc);
tbfc = NULL; tbfc = NULL;
@@ -160,8 +155,9 @@ static void textbox_initialize_font ( textbox *tb )
} }
} }
textbox* textbox_create ( widget *parent, WidgetType type, const char *name, TextboxFlags flags, TextBoxFontType tbft, const char *text, double xalign, double yalign ) textbox *textbox_create(widget *parent, WidgetType type, const char *name,
{ TextboxFlags flags, TextBoxFontType tbft,
const char *text, double xalign, double yalign) {
textbox *tb = g_slice_new0(textbox); textbox *tb = g_slice_new0(textbox);
widget_init(WIDGET(tb), parent, type, name); widget_init(WIDGET(tb), parent, type, name);
@@ -188,10 +184,10 @@ textbox* textbox_create ( widget *parent, WidgetType type, const char *name, Tex
} }
// Allow overriding of markup. // Allow overriding of markup.
if ( rofi_theme_get_boolean ( WIDGET ( tb ), "markup", ( tb->flags & TB_MARKUP ) == TB_MARKUP ) ) { if (rofi_theme_get_boolean(WIDGET(tb), "markup",
(tb->flags & TB_MARKUP) == TB_MARKUP)) {
tb->flags |= TB_MARKUP; tb->flags |= TB_MARKUP;
} } else {
else {
tb->flags &= (~TB_MARKUP); tb->flags &= (~TB_MARKUP);
} }
@@ -199,7 +195,8 @@ textbox* textbox_create ( widget *parent, WidgetType type, const char *name, Tex
if (txt == NULL || (*txt) == '\0') { if (txt == NULL || (*txt) == '\0') {
txt = rofi_theme_get_string(WIDGET(tb), "content", text); txt = rofi_theme_get_string(WIDGET(tb), "content", text);
} }
const char *placeholder = rofi_theme_get_string ( WIDGET ( tb ), "placeholder", NULL ); const char *placeholder =
rofi_theme_get_string(WIDGET(tb), "placeholder", NULL);
if (placeholder) { if (placeholder) {
tb->placeholder = placeholder; tb->placeholder = placeholder;
} }
@@ -207,7 +204,8 @@ textbox* textbox_create ( widget *parent, WidgetType type, const char *name, Tex
textbox_cursor_end(tb); textbox_cursor_end(tb);
// auto height/width modes get handled here // auto height/width modes get handled here
textbox_moveresize ( tb, tb->widget.x, tb->widget.y, tb->widget.w, tb->widget.h ); textbox_moveresize(tb, tb->widget.x, tb->widget.y, tb->widget.w,
tb->widget.h);
tb->blink_timeout = 0; tb->blink_timeout = 0;
tb->blink = 1; tb->blink = 1;
@@ -238,8 +236,7 @@ const char *const theme_prop_names[][3] = {
{"normal.active", "selected.active", "alternate.active"}, {"normal.active", "selected.active", "alternate.active"},
}; };
void textbox_font ( textbox *tb, TextBoxFontType tbft ) void textbox_font(textbox *tb, TextBoxFontType tbft) {
{
TextBoxFontType t = tbft & STATE_MASK; TextBoxFontType t = tbft & STATE_MASK;
if (tb == NULL) { if (tb == NULL) {
return; return;
@@ -248,8 +245,7 @@ void textbox_font ( textbox *tb, TextBoxFontType tbft )
if (t == (URGENT | ACTIVE)) { if (t == (URGENT | ACTIVE)) {
t = ACTIVE; t = ACTIVE;
} }
switch ( ( tbft & FMOD_MASK ) ) switch ((tbft & FMOD_MASK)) {
{
case HIGHLIGHT: case HIGHLIGHT:
widget_set_state(WIDGET(tb), theme_prop_names[t][1]); widget_set_state(WIDGET(tb), theme_prop_names[t][1]);
break; break;
@@ -272,8 +268,7 @@ void textbox_font ( textbox *tb, TextBoxFontType tbft )
* Update the pango layout's text. It does this depending on the * Update the pango layout's text. It does this depending on the
* textbox flags. * textbox flags.
*/ */
static void __textbox_update_pango_text ( textbox *tb ) static void __textbox_update_pango_text(textbox *tb) {
{
pango_layout_set_attributes(tb->layout, NULL); pango_layout_set_attributes(tb->layout, NULL);
if (tb->placeholder && (tb->text == NULL || tb->text[0] == 0)) { if (tb->placeholder && (tb->text == NULL || tb->text[0] == 0)) {
tb->show_placeholder = TRUE; tb->show_placeholder = TRUE;
@@ -287,30 +282,25 @@ static void __textbox_update_pango_text ( textbox *tb )
memset(string, '*', l); memset(string, '*', l);
string[l] = '\0'; string[l] = '\0';
pango_layout_set_text(tb->layout, string, l); pango_layout_set_text(tb->layout, string, l);
} } else if (tb->flags & TB_MARKUP || tb->tbft & MARKUP) {
else if ( tb->flags & TB_MARKUP || tb->tbft & MARKUP ) {
pango_layout_set_markup(tb->layout, tb->text, -1); pango_layout_set_markup(tb->layout, tb->text, -1);
} } else {
else {
pango_layout_set_text(tb->layout, tb->text, -1); pango_layout_set_text(tb->layout, tb->text, -1);
} }
} }
const char *textbox_get_visible_text ( const textbox *tb ) const char *textbox_get_visible_text(const textbox *tb) {
{
if (tb == NULL) { if (tb == NULL) {
return NULL; return NULL;
} }
return pango_layout_get_text(tb->layout); return pango_layout_get_text(tb->layout);
} }
PangoAttrList *textbox_get_pango_attributes ( textbox *tb ) PangoAttrList *textbox_get_pango_attributes(textbox *tb) {
{
if (tb == NULL) { if (tb == NULL) {
return NULL; return NULL;
} }
return pango_layout_get_attributes(tb->layout); return pango_layout_get_attributes(tb->layout);
} }
void textbox_set_pango_attributes ( textbox *tb, PangoAttrList *list ) void textbox_set_pango_attributes(textbox *tb, PangoAttrList *list) {
{
if (tb == NULL) { if (tb == NULL) {
return; return;
} }
@@ -318,8 +308,7 @@ void textbox_set_pango_attributes ( textbox *tb, PangoAttrList *list )
} }
// set the default text to display // set the default text to display
void textbox_text ( textbox *tb, const char *text ) void textbox_text(textbox *tb, const char *text) {
{
if (tb == NULL) { if (tb == NULL) {
return; return;
} }
@@ -328,19 +317,18 @@ void textbox_text ( textbox *tb, const char *text )
if (g_utf8_validate(text, -1, &last_pointer)) { if (g_utf8_validate(text, -1, &last_pointer)) {
tb->text = g_strdup(text); tb->text = g_strdup(text);
} } else {
else {
if (last_pointer != NULL) { if (last_pointer != NULL) {
// Copy string up to invalid character. // Copy string up to invalid character.
tb->text = g_strndup(text, (last_pointer - text)); tb->text = g_strndup(text, (last_pointer - text));
} } else {
else {
tb->text = g_strdup("Invalid UTF-8 string."); tb->text = g_strdup("Invalid UTF-8 string.");
} }
} }
__textbox_update_pango_text(tb); __textbox_update_pango_text(tb);
if (tb->flags & TB_AUTOWIDTH) { if (tb->flags & TB_AUTOWIDTH) {
textbox_moveresize ( tb, tb->widget.x, tb->widget.y, tb->widget.w, tb->widget.h ); textbox_moveresize(tb, tb->widget.x, tb->widget.y, tb->widget.w,
tb->widget.h);
if (WIDGET(tb)->parent) { if (WIDGET(tb)->parent) {
widget_update(WIDGET(tb)->parent); widget_update(WIDGET(tb)->parent);
} }
@@ -351,22 +339,19 @@ void textbox_text ( textbox *tb, const char *text )
} }
// within the parent handled auto width/height modes // within the parent handled auto width/height modes
void textbox_moveresize ( textbox *tb, int x, int y, int w, int h ) void textbox_moveresize(textbox *tb, int x, int y, int w, int h) {
{
unsigned int offset = ((tb->flags & TB_INDICATOR) ? DOT_OFFSET : 0); unsigned int offset = ((tb->flags & TB_INDICATOR) ? DOT_OFFSET : 0);
if (tb->flags & TB_AUTOWIDTH) { if (tb->flags & TB_AUTOWIDTH) {
pango_layout_set_width(tb->layout, -1); pango_layout_set_width(tb->layout, -1);
w = textbox_get_font_width ( tb ) + widget_padding_get_padding_width ( WIDGET ( tb ) ) + offset; w = textbox_get_font_width(tb) +
} widget_padding_get_padding_width(WIDGET(tb)) + offset;
else { } else {
// set ellipsize // set ellipsize
if ((tb->flags & TB_EDITABLE) == TB_EDITABLE) { if ((tb->flags & TB_EDITABLE) == TB_EDITABLE) {
pango_layout_set_ellipsize(tb->layout, PANGO_ELLIPSIZE_MIDDLE); pango_layout_set_ellipsize(tb->layout, PANGO_ELLIPSIZE_MIDDLE);
} } else if ((tb->flags & TB_WRAP) != TB_WRAP) {
else if ( ( tb->flags & TB_WRAP ) != TB_WRAP ) {
pango_layout_set_ellipsize(tb->layout, tb->emode); pango_layout_set_ellipsize(tb->layout, tb->emode);
} } else {
else {
pango_layout_set_ellipsize(tb->layout, PANGO_ELLIPSIZE_NONE); pango_layout_set_ellipsize(tb->layout, PANGO_ELLIPSIZE_NONE);
} }
} }
@@ -374,12 +359,16 @@ void textbox_moveresize ( textbox *tb, int x, int y, int w, int h )
if (tb->flags & TB_AUTOHEIGHT) { if (tb->flags & TB_AUTOHEIGHT) {
// Width determines height! // Width determines height!
int tw = MAX(1, w); int tw = MAX(1, w);
pango_layout_set_width ( tb->layout, PANGO_SCALE * ( tw - widget_padding_get_padding_width ( WIDGET ( tb ) ) - offset ) ); pango_layout_set_width(
tb->layout,
PANGO_SCALE *
(tw - widget_padding_get_padding_width(WIDGET(tb)) - offset));
int hd = textbox_get_height(tb); int hd = textbox_get_height(tb);
h = MAX(hd, h); h = MAX(hd, h);
} }
if ( x != tb->widget.x || y != tb->widget.y || w != tb->widget.w || h != tb->widget.h ) { if (x != tb->widget.x || y != tb->widget.y || w != tb->widget.w ||
h != tb->widget.h) {
tb->widget.x = x; tb->widget.x = x;
tb->widget.y = y; tb->widget.y = y;
tb->widget.h = MAX(1, h); tb->widget.h = MAX(1, h);
@@ -387,13 +376,15 @@ void textbox_moveresize ( textbox *tb, int x, int y, int w, int h )
} }
// We always want to update this // We always want to update this
pango_layout_set_width ( tb->layout, PANGO_SCALE * ( tb->widget.w - widget_padding_get_padding_width ( WIDGET ( tb ) ) - offset ) ); pango_layout_set_width(
tb->layout,
PANGO_SCALE * (tb->widget.w -
widget_padding_get_padding_width(WIDGET(tb)) - offset));
widget_queue_redraw(WIDGET(tb)); widget_queue_redraw(WIDGET(tb));
} }
// will also unmap the window if still displayed // will also unmap the window if still displayed
static void textbox_free ( widget *wid ) static void textbox_free(widget *wid) {
{
if (wid == NULL) { if (wid == NULL) {
return; return;
} }
@@ -411,8 +402,7 @@ static void textbox_free ( widget *wid )
g_slice_free(textbox, tb); g_slice_free(textbox, tb);
} }
static void textbox_draw ( widget *wid, cairo_t *draw ) static void textbox_draw(widget *wid, cairo_t *draw) {
{
if (wid == NULL) { if (wid == NULL) {
return; return;
} }
@@ -426,7 +416,9 @@ static void textbox_draw ( widget *wid, cairo_t *draw )
// Skip the side MARGIN on the X axis. // Skip the side MARGIN on the X axis.
int x = widget_padding_get_left(WIDGET(tb)); int x = widget_padding_get_left(WIDGET(tb));
int top = widget_padding_get_top(WIDGET(tb)); int top = widget_padding_get_top(WIDGET(tb));
int y = ( pango_font_metrics_get_ascent ( tb->tbfc->metrics ) - pango_layout_get_baseline ( tb->layout ) ) / PANGO_SCALE; int y = (pango_font_metrics_get_ascent(tb->tbfc->metrics) -
pango_layout_get_baseline(tb->layout)) /
PANGO_SCALE;
int line_width = 0, line_height = 0; int line_width = 0, line_height = 0;
// Get actual width. // Get actual width.
pango_layout_get_pixel_size(tb->layout, &line_width, &line_height); pango_layout_get_pixel_size(tb->layout, &line_width, &line_height);
@@ -440,7 +432,9 @@ static void textbox_draw ( widget *wid, cairo_t *draw )
x += offset; x += offset;
if (tb->xalign > 0.001) { if (tb->xalign > 0.001) {
int rem = MAX ( 0, tb->widget.w - widget_padding_get_padding_width ( WIDGET ( tb ) ) - line_width ); int rem =
MAX(0, tb->widget.w - widget_padding_get_padding_width(WIDGET(tb)) -
line_width);
x = tb->xalign * rem + widget_padding_get_left(WIDGET(tb)); x = tb->xalign * rem + widget_padding_get_left(WIDGET(tb));
} }
// TODO check if this is still needed after flatning. // TODO check if this is still needed after flatning.
@@ -474,7 +468,8 @@ static void textbox_draw ( widget *wid, cairo_t *draw )
int cursor_y = pos.y / PANGO_SCALE; int cursor_y = pos.y / PANGO_SCALE;
int cursor_height = pos.height / PANGO_SCALE; int cursor_height = pos.height / PANGO_SCALE;
int cursor_width = 2; int cursor_width = 2;
cairo_rectangle ( draw, x + cursor_x, y + cursor_y, cursor_width, cursor_height ); cairo_rectangle(draw, x + cursor_x, y + cursor_y, cursor_width,
cursor_height);
cairo_fill(draw); cairo_fill(draw);
} }
@@ -485,8 +480,7 @@ static void textbox_draw ( widget *wid, cairo_t *draw )
} }
// cursor handling for edit mode // cursor handling for edit mode
void textbox_cursor ( textbox *tb, int pos ) void textbox_cursor(textbox *tb, int pos) {
{
if (tb == NULL) { if (tb == NULL) {
return; return;
} }
@@ -504,8 +498,7 @@ void textbox_cursor ( textbox *tb, int pos )
* *
* @returns if cursor was moved. * @returns if cursor was moved.
*/ */
static int textbox_cursor_inc ( textbox *tb ) static int textbox_cursor_inc(textbox *tb) {
{
int old = tb->cursor; int old = tb->cursor;
textbox_cursor(tb, tb->cursor + 1); textbox_cursor(tb, tb->cursor + 1);
return old != tb->cursor; return old != tb->cursor;
@@ -518,16 +511,14 @@ static int textbox_cursor_inc ( textbox *tb )
* *
* @returns if cursor was moved. * @returns if cursor was moved.
*/ */
static int textbox_cursor_dec ( textbox *tb ) static int textbox_cursor_dec(textbox *tb) {
{
int old = tb->cursor; int old = tb->cursor;
textbox_cursor(tb, tb->cursor - 1); textbox_cursor(tb, tb->cursor - 1);
return old != tb->cursor; return old != tb->cursor;
} }
// Move word right // Move word right
static void textbox_cursor_inc_word ( textbox *tb ) static void textbox_cursor_inc_word(textbox *tb) {
{
if (tb->text == NULL) { if (tb->text == NULL) {
return; return;
} }
@@ -536,8 +527,9 @@ static void textbox_cursor_inc_word ( textbox *tb )
while ((c = g_utf8_next_char(c))) { while ((c = g_utf8_next_char(c))) {
gunichar uc = g_utf8_get_char(c); gunichar uc = g_utf8_get_char(c);
GUnicodeBreakType bt = g_unichar_break_type(uc); GUnicodeBreakType bt = g_unichar_break_type(uc);
if ( ( bt == G_UNICODE_BREAK_ALPHABETIC || bt == G_UNICODE_BREAK_HEBREW_LETTER || if ((bt == G_UNICODE_BREAK_ALPHABETIC ||
bt == G_UNICODE_BREAK_NUMERIC || bt == G_UNICODE_BREAK_QUOTATION ) ) { bt == G_UNICODE_BREAK_HEBREW_LETTER || bt == G_UNICODE_BREAK_NUMERIC ||
bt == G_UNICODE_BREAK_QUOTATION)) {
break; break;
} }
} }
@@ -547,7 +539,8 @@ static void textbox_cursor_inc_word ( textbox *tb )
while ((c = g_utf8_next_char(c))) { while ((c = g_utf8_next_char(c))) {
gunichar uc = g_utf8_get_char(c); gunichar uc = g_utf8_get_char(c);
GUnicodeBreakType bt = g_unichar_break_type(uc); GUnicodeBreakType bt = g_unichar_break_type(uc);
if ( !( bt == G_UNICODE_BREAK_ALPHABETIC || bt == G_UNICODE_BREAK_HEBREW_LETTER || if (!(bt == G_UNICODE_BREAK_ALPHABETIC ||
bt == G_UNICODE_BREAK_HEBREW_LETTER ||
bt == G_UNICODE_BREAK_NUMERIC || bt == G_UNICODE_BREAK_QUOTATION)) { bt == G_UNICODE_BREAK_NUMERIC || bt == G_UNICODE_BREAK_QUOTATION)) {
break; break;
} }
@@ -556,16 +549,16 @@ static void textbox_cursor_inc_word ( textbox *tb )
textbox_cursor(tb, index); textbox_cursor(tb, index);
} }
// move word left // move word left
static void textbox_cursor_dec_word ( textbox *tb ) static void textbox_cursor_dec_word(textbox *tb) {
{
// Find word boundaries, with pango_Break? // Find word boundaries, with pango_Break?
gchar *n; gchar *n;
gchar *c = g_utf8_offset_to_pointer(tb->text, tb->cursor); gchar *c = g_utf8_offset_to_pointer(tb->text, tb->cursor);
while ((c = g_utf8_prev_char(c)) && c != tb->text) { while ((c = g_utf8_prev_char(c)) && c != tb->text) {
gunichar uc = g_utf8_get_char(c); gunichar uc = g_utf8_get_char(c);
GUnicodeBreakType bt = g_unichar_break_type(uc); GUnicodeBreakType bt = g_unichar_break_type(uc);
if ( ( bt == G_UNICODE_BREAK_ALPHABETIC || bt == G_UNICODE_BREAK_HEBREW_LETTER || if ((bt == G_UNICODE_BREAK_ALPHABETIC ||
bt == G_UNICODE_BREAK_NUMERIC || bt == G_UNICODE_BREAK_QUOTATION ) ) { bt == G_UNICODE_BREAK_HEBREW_LETTER || bt == G_UNICODE_BREAK_NUMERIC ||
bt == G_UNICODE_BREAK_QUOTATION)) {
break; break;
} }
} }
@@ -573,7 +566,8 @@ static void textbox_cursor_dec_word ( textbox *tb )
while ((n = g_utf8_prev_char(c))) { while ((n = g_utf8_prev_char(c))) {
gunichar uc = g_utf8_get_char(n); gunichar uc = g_utf8_get_char(n);
GUnicodeBreakType bt = g_unichar_break_type(uc); GUnicodeBreakType bt = g_unichar_break_type(uc);
if ( !( bt == G_UNICODE_BREAK_ALPHABETIC || bt == G_UNICODE_BREAK_HEBREW_LETTER || if (!(bt == G_UNICODE_BREAK_ALPHABETIC ||
bt == G_UNICODE_BREAK_HEBREW_LETTER ||
bt == G_UNICODE_BREAK_NUMERIC || bt == G_UNICODE_BREAK_QUOTATION)) { bt == G_UNICODE_BREAK_NUMERIC || bt == G_UNICODE_BREAK_QUOTATION)) {
break; break;
} }
@@ -588,8 +582,7 @@ static void textbox_cursor_dec_word ( textbox *tb )
} }
// end of line // end of line
void textbox_cursor_end ( textbox *tb ) void textbox_cursor_end(textbox *tb) {
{
if (tb->text == NULL) { if (tb->text == NULL) {
tb->cursor = 0; tb->cursor = 0;
widget_queue_redraw(WIDGET(tb)); widget_queue_redraw(WIDGET(tb));
@@ -602,8 +595,8 @@ void textbox_cursor_end ( textbox *tb )
} }
// insert text // insert text
void textbox_insert ( textbox *tb, const int char_pos, const char *str, const int slen ) void textbox_insert(textbox *tb, const int char_pos, const char *str,
{ const int slen) {
if (tb == NULL) { if (tb == NULL) {
return; return;
} }
@@ -626,8 +619,7 @@ void textbox_insert ( textbox *tb, const int char_pos, const char *str, const in
} }
// remove text // remove text
void textbox_delete ( textbox *tb, int pos, int dlen ) void textbox_delete(textbox *tb, int pos, int dlen) {
{
if (tb == NULL) { if (tb == NULL) {
return; return;
} }
@@ -646,8 +638,7 @@ void textbox_delete ( textbox *tb, int pos, int dlen )
memmove(start, end, (tb->text + strlen(tb->text)) - end + 1); memmove(start, end, (tb->text + strlen(tb->text)) - end + 1);
if (tb->cursor >= pos && tb->cursor < (pos + dlen)) { if (tb->cursor >= pos && tb->cursor < (pos + dlen)) {
tb->cursor = pos; tb->cursor = pos;
} } else if (tb->cursor >= (pos + dlen)) {
else if ( tb->cursor >= ( pos + dlen ) ) {
tb->cursor -= dlen; tb->cursor -= dlen;
} }
// Set modified, lay out need te be redrawn // Set modified, lay out need te be redrawn
@@ -661,8 +652,7 @@ void textbox_delete ( textbox *tb, int pos, int dlen )
* *
* Delete character after cursor. * Delete character after cursor.
*/ */
static void textbox_cursor_del ( textbox *tb ) static void textbox_cursor_del(textbox *tb) {
{
if (tb == NULL || tb->text == NULL) { if (tb == NULL || tb->text == NULL) {
return; return;
} }
@@ -674,15 +664,13 @@ static void textbox_cursor_del ( textbox *tb )
* *
* Delete character before cursor. * Delete character before cursor.
*/ */
static void textbox_cursor_bkspc ( textbox *tb ) static void textbox_cursor_bkspc(textbox *tb) {
{
if (tb && tb->cursor > 0) { if (tb && tb->cursor > 0) {
textbox_cursor_dec(tb); textbox_cursor_dec(tb);
textbox_cursor_del(tb); textbox_cursor_del(tb);
} }
} }
static void textbox_cursor_bkspc_word ( textbox *tb ) static void textbox_cursor_bkspc_word(textbox *tb) {
{
if (tb && tb->cursor > 0) { if (tb && tb->cursor > 0) {
int cursor = tb->cursor; int cursor = tb->cursor;
textbox_cursor_dec_word(tb); textbox_cursor_dec_word(tb);
@@ -691,8 +679,7 @@ static void textbox_cursor_bkspc_word ( textbox *tb )
} }
} }
} }
static void textbox_cursor_del_eol ( textbox *tb ) static void textbox_cursor_del_eol(textbox *tb) {
{
if (tb && tb->cursor >= 0) { if (tb && tb->cursor >= 0) {
int length = g_utf8_strlen(tb->text, -1) - tb->cursor; int length = g_utf8_strlen(tb->text, -1) - tb->cursor;
if (length >= 0) { if (length >= 0) {
@@ -700,8 +687,7 @@ static void textbox_cursor_del_eol ( textbox *tb )
} }
} }
} }
static void textbox_cursor_del_sol ( textbox *tb ) static void textbox_cursor_del_sol(textbox *tb) {
{
if (tb && tb->cursor >= 0) { if (tb && tb->cursor >= 0) {
int length = tb->cursor; int length = tb->cursor;
if (length >= 0) { if (length >= 0) {
@@ -709,8 +695,7 @@ static void textbox_cursor_del_sol ( textbox *tb )
} }
} }
} }
static void textbox_cursor_del_word ( textbox *tb ) static void textbox_cursor_del_word(textbox *tb) {
{
if (tb && tb->cursor >= 0) { if (tb && tb->cursor >= 0) {
int cursor = tb->cursor; int cursor = tb->cursor;
textbox_cursor_inc_word(tb); textbox_cursor_inc_word(tb);
@@ -725,8 +710,7 @@ static void textbox_cursor_del_word ( textbox *tb )
// 0 = unhandled // 0 = unhandled
// 1 = handled // 1 = handled
// -1 = handled and return pressed (finished) // -1 = handled and return pressed (finished)
int textbox_keybinding ( textbox *tb, KeyBindingAction action ) int textbox_keybinding(textbox *tb, KeyBindingAction action) {
{
if (tb == NULL) { if (tb == NULL) {
return 0; return 0;
} }
@@ -734,8 +718,7 @@ int textbox_keybinding ( textbox *tb, KeyBindingAction action )
return 0; return 0;
} }
switch ( action ) switch (action) {
{
// Left or Ctrl-b // Left or Ctrl-b
case MOVE_CHAR_BACK: case MOVE_CHAR_BACK:
return (textbox_cursor_dec(tb) == TRUE) ? 2 : 0; return (textbox_cursor_dec(tb) == TRUE) ? 2 : 0;
@@ -789,8 +772,7 @@ int textbox_keybinding ( textbox *tb, KeyBindingAction action )
} }
} }
gboolean textbox_append_text ( textbox *tb, const char *pad, const int pad_len ) gboolean textbox_append_text(textbox *tb, const char *pad, const int pad_len) {
{
if (tb == NULL) { if (tb == NULL) {
return FALSE; return FALSE;
} }
@@ -802,7 +784,8 @@ gboolean textbox_append_text ( textbox *tb, const char *pad, const int pad_len )
gboolean used_something = FALSE; gboolean used_something = FALSE;
const gchar *w, *n, *e; const gchar *w, *n, *e;
for ( w = pad, n = g_utf8_next_char ( w ), e = w + pad_len; w < e; w = n, n = g_utf8_next_char ( n ) ) { for (w = pad, n = g_utf8_next_char(w), e = w + pad_len; w < e;
w = n, n = g_utf8_next_char(n)) {
if (g_unichar_iscntrl(g_utf8_get_char(w))) { if (g_unichar_iscntrl(g_utf8_get_char(w))) {
continue; continue;
} }
@@ -813,23 +796,21 @@ gboolean textbox_append_text ( textbox *tb, const char *pad, const int pad_len )
return used_something; return used_something;
} }
static void tbfc_entry_free ( TBFontConfig *tbfc ) static void tbfc_entry_free(TBFontConfig *tbfc) {
{
pango_font_metrics_unref(tbfc->metrics); pango_font_metrics_unref(tbfc->metrics);
if (tbfc->pfd) { if (tbfc->pfd) {
pango_font_description_free(tbfc->pfd); pango_font_description_free(tbfc->pfd);
} }
g_free(tbfc); g_free(tbfc);
} }
void textbox_setup ( void ) void textbox_setup(void) {
{ tbfc_cache = g_hash_table_new_full(g_str_hash, g_str_equal, NULL,
tbfc_cache = g_hash_table_new_full ( g_str_hash, g_str_equal, NULL, (GDestroyNotify) tbfc_entry_free ); (GDestroyNotify)tbfc_entry_free);
} }
/** Name of the default font (if none is given) */ /** Name of the default font (if none is given) */
const char *default_font_name = "default"; const char *default_font_name = "default";
void textbox_set_pango_context ( const char *font, PangoContext *p ) void textbox_set_pango_context(const char *font, PangoContext *p) {
{
g_assert(p_metrics == NULL); g_assert(p_metrics == NULL);
p_context = g_object_ref(p); p_context = g_object_ref(p);
p_metrics = pango_context_get_metrics(p_context, NULL, NULL); p_metrics = pango_context_get_metrics(p_context, NULL, NULL);
@@ -844,11 +825,11 @@ void textbox_set_pango_context ( const char *font, PangoContext *p )
g_object_unref(layout); g_object_unref(layout);
tbfc_default = tbfc; tbfc_default = tbfc;
g_hash_table_insert ( tbfc_cache, (gpointer *) ( font ? font : default_font_name ), tbfc ); g_hash_table_insert(tbfc_cache, (gpointer *)(font ? font : default_font_name),
tbfc);
} }
void textbox_cleanup ( void ) void textbox_cleanup(void) {
{
g_hash_table_destroy(tbfc_cache); g_hash_table_destroy(tbfc_cache);
if (p_context) { if (p_context) {
g_object_unref(p_context); g_object_unref(p_context);
@@ -856,53 +837,47 @@ void textbox_cleanup ( void )
} }
} }
int textbox_get_width ( widget *wid ) int textbox_get_width(widget *wid) {
{
textbox *tb = (textbox *)wid; textbox *tb = (textbox *)wid;
if (tb->flags & TB_AUTOWIDTH) { if (tb->flags & TB_AUTOWIDTH) {
unsigned int offset = (tb->flags & TB_INDICATOR) ? DOT_OFFSET : 0; unsigned int offset = (tb->flags & TB_INDICATOR) ? DOT_OFFSET : 0;
return textbox_get_font_width ( tb ) + widget_padding_get_padding_width ( wid ) + offset; return textbox_get_font_width(tb) + widget_padding_get_padding_width(wid) +
offset;
} }
return tb->widget.w; return tb->widget.w;
} }
int _textbox_get_height ( widget *wid ) int _textbox_get_height(widget *wid) {
{
textbox *tb = (textbox *)wid; textbox *tb = (textbox *)wid;
if (tb->flags & TB_AUTOHEIGHT) { if (tb->flags & TB_AUTOHEIGHT) {
return textbox_get_estimated_height ( tb, pango_layout_get_line_count ( tb->layout ) ); return textbox_get_estimated_height(
tb, pango_layout_get_line_count(tb->layout));
} }
return tb->widget.h; return tb->widget.h;
} }
int textbox_get_height ( const textbox *tb ) int textbox_get_height(const textbox *tb) {
{ return textbox_get_font_height(tb) +
return textbox_get_font_height ( tb ) + widget_padding_get_padding_height ( WIDGET ( tb ) ); widget_padding_get_padding_height(WIDGET(tb));
} }
int textbox_get_font_height ( const textbox *tb ) int textbox_get_font_height(const textbox *tb) {
{
PangoRectangle rect; PangoRectangle rect;
pango_layout_get_pixel_extents(tb->layout, NULL, &rect); pango_layout_get_pixel_extents(tb->layout, NULL, &rect);
return rect.height + rect.y; return rect.height + rect.y;
} }
int textbox_get_font_width ( const textbox *tb ) int textbox_get_font_width(const textbox *tb) {
{
PangoRectangle rect; PangoRectangle rect;
pango_layout_get_pixel_extents(tb->layout, NULL, &rect); pango_layout_get_pixel_extents(tb->layout, NULL, &rect);
return rect.width + rect.x; return rect.width + rect.x;
} }
/** Caching for the estimated character height. (em) */ /** Caching for the estimated character height. (em) */
double textbox_get_estimated_char_height ( void ) double textbox_get_estimated_char_height(void) { return tbfc_default->height; }
{
return tbfc_default->height;
}
/** Caching for the expected character width. */ /** Caching for the expected character width. */
static double char_width = -1; static double char_width = -1;
double textbox_get_estimated_char_width ( void ) double textbox_get_estimated_char_width(void) {
{
if (char_width < 0) { if (char_width < 0) {
int width = pango_font_metrics_get_approximate_char_width(p_metrics); int width = pango_font_metrics_get_approximate_char_width(p_metrics);
char_width = (width) / (double)PANGO_SCALE; char_width = (width) / (double)PANGO_SCALE;
@@ -912,8 +887,7 @@ double textbox_get_estimated_char_width ( void )
/** Cache storing the estimated width of a digit (ch). */ /** Cache storing the estimated width of a digit (ch). */
static double ch_width = -1; static double ch_width = -1;
double textbox_get_estimated_ch ( void ) double textbox_get_estimated_ch(void) {
{
if (ch_width < 0) { if (ch_width < 0) {
int width = pango_font_metrics_get_approximate_digit_width(p_metrics); int width = pango_font_metrics_get_approximate_digit_width(p_metrics);
ch_width = (width) / (double)PANGO_SCALE; ch_width = (width) / (double)PANGO_SCALE;
@@ -921,20 +895,19 @@ double textbox_get_estimated_ch ( void )
return ch_width; return ch_width;
} }
int textbox_get_estimated_height ( const textbox *tb, int eh ) int textbox_get_estimated_height(const textbox *tb, int eh) {
{
int height = tb->tbfc->height; int height = tb->tbfc->height;
return (eh * height) + widget_padding_get_padding_height(WIDGET(tb)); return (eh * height) + widget_padding_get_padding_height(WIDGET(tb));
} }
int textbox_get_desired_width ( widget *wid ) int textbox_get_desired_width(widget *wid) {
{
if (wid == NULL) { if (wid == NULL) {
return 0; return 0;
} }
textbox *tb = (textbox *)wid; textbox *tb = (textbox *)wid;
unsigned int offset = ((tb->flags & TB_INDICATOR) ? DOT_OFFSET : 0); unsigned int offset = ((tb->flags & TB_INDICATOR) ? DOT_OFFSET : 0);
if (wid->expand && tb->flags & TB_AUTOWIDTH) { if (wid->expand && tb->flags & TB_AUTOWIDTH) {
return textbox_get_font_width ( tb ) + widget_padding_get_padding_width ( wid ) + offset; return textbox_get_font_width(tb) + widget_padding_get_padding_width(wid) +
offset;
} }
RofiDistance w = rofi_theme_get_distance(WIDGET(tb), "width", 0); RofiDistance w = rofi_theme_get_distance(WIDGET(tb), "width", 0);
int wi = distance_get_pixel(w, ROFI_ORIENTATION_HORIZONTAL); int wi = distance_get_pixel(w, ROFI_ORIENTATION_HORIZONTAL);
@@ -951,8 +924,7 @@ int textbox_get_desired_width ( widget *wid )
return width + padding + offset; return width + padding + offset;
} }
void textbox_set_ellipsize ( textbox *tb, PangoEllipsizeMode mode ) void textbox_set_ellipsize(textbox *tb, PangoEllipsizeMode mode) {
{
if (tb) { if (tb) {
tb->emode = mode; tb->emode = mode;
if ((tb->flags & TB_WRAP) != TB_WRAP) { if ((tb->flags & TB_WRAP) != TB_WRAP) {

View File

@@ -25,48 +25,61 @@
* *
*/ */
#include "widgets/widget.h"
#include "theme.h"
#include "widgets/widget-internal.h"
#include <glib.h> #include <glib.h>
#include <math.h> #include <math.h>
#include "widgets/widget.h"
#include "widgets/widget-internal.h"
#include "theme.h"
/** Default padding. */ /** Default padding. */
#define WIDGET_DEFAULT_PADDING 0 #define WIDGET_DEFAULT_PADDING 0
/** macro for initializing the padding struction. */ /** macro for initializing the padding struction. */
#define WIDGET_PADDING_INIT { { WIDGET_DEFAULT_PADDING, ROFI_PU_PX, ROFI_DISTANCE_MODIFIER_NONE, NULL, NULL }, ROFI_HL_SOLID } #define WIDGET_PADDING_INIT \
{ \
{WIDGET_DEFAULT_PADDING, ROFI_PU_PX, ROFI_DISTANCE_MODIFIER_NONE, NULL, \
NULL}, \
ROFI_HL_SOLID \
}
void widget_init ( widget *wid, widget *parent, WidgetType type, const char *name ) void widget_init(widget *wid, widget *parent, WidgetType type,
{ const char *name) {
wid->type = type; wid->type = type;
wid->parent = parent; wid->parent = parent;
wid->name = g_strdup(name); wid->name = g_strdup(name);
wid->def_padding = (RofiPadding) { WIDGET_PADDING_INIT, WIDGET_PADDING_INIT, WIDGET_PADDING_INIT, WIDGET_PADDING_INIT }; wid->def_padding = (RofiPadding){WIDGET_PADDING_INIT, WIDGET_PADDING_INIT,
wid->def_border = (RofiPadding) { WIDGET_PADDING_INIT, WIDGET_PADDING_INIT, WIDGET_PADDING_INIT, WIDGET_PADDING_INIT }; WIDGET_PADDING_INIT, WIDGET_PADDING_INIT};
wid->def_border_radius = (RofiPadding) { WIDGET_PADDING_INIT, WIDGET_PADDING_INIT, WIDGET_PADDING_INIT, WIDGET_PADDING_INIT }; wid->def_border = (RofiPadding){WIDGET_PADDING_INIT, WIDGET_PADDING_INIT,
wid->def_margin = (RofiPadding) { WIDGET_PADDING_INIT, WIDGET_PADDING_INIT, WIDGET_PADDING_INIT, WIDGET_PADDING_INIT }; WIDGET_PADDING_INIT, WIDGET_PADDING_INIT};
wid->def_border_radius =
(RofiPadding){WIDGET_PADDING_INIT, WIDGET_PADDING_INIT,
WIDGET_PADDING_INIT, WIDGET_PADDING_INIT};
wid->def_margin = (RofiPadding){WIDGET_PADDING_INIT, WIDGET_PADDING_INIT,
WIDGET_PADDING_INIT, WIDGET_PADDING_INIT};
wid->padding = rofi_theme_get_padding(wid, "padding", wid->def_padding); wid->padding = rofi_theme_get_padding(wid, "padding", wid->def_padding);
wid->border = rofi_theme_get_padding(wid, "border", wid->def_border); wid->border = rofi_theme_get_padding(wid, "border", wid->def_border);
wid->border_radius = rofi_theme_get_padding ( wid, "border-radius", wid->def_border_radius ); wid->border_radius =
rofi_theme_get_padding(wid, "border-radius", wid->def_border_radius);
wid->margin = rofi_theme_get_padding(wid, "margin", wid->def_margin); wid->margin = rofi_theme_get_padding(wid, "margin", wid->def_margin);
wid->cursor_type = rofi_theme_get_cursor_type ( wid, "cursor", ROFI_CURSOR_DEFAULT ); wid->cursor_type =
rofi_theme_get_cursor_type(wid, "cursor", ROFI_CURSOR_DEFAULT);
// enabled by default // enabled by default
wid->enabled = rofi_theme_get_boolean(wid, "enabled", TRUE); wid->enabled = rofi_theme_get_boolean(wid, "enabled", TRUE);
} }
void widget_set_state ( widget *widget, const char *state ) void widget_set_state(widget *widget, const char *state) {
{
if (widget == NULL) { if (widget == NULL) {
return; return;
} }
if (g_strcmp0(widget->state, state)) { if (g_strcmp0(widget->state, state)) {
widget->state = state; widget->state = state;
// Update border. // Update border.
widget->border = rofi_theme_get_padding ( widget, "border", widget->def_border ); widget->border =
widget->border_radius = rofi_theme_get_padding ( widget, "border-radius", widget->def_border_radius ); rofi_theme_get_padding(widget, "border", widget->def_border);
widget->border_radius = rofi_theme_get_padding(widget, "border-radius",
widget->def_border_radius);
if (widget->set_state != NULL) { if (widget->set_state != NULL) {
widget->set_state(widget, state); widget->set_state(widget, state);
} }
@@ -74,21 +87,19 @@ void widget_set_state ( widget *widget, const char *state )
} }
} }
int widget_intersect ( const widget *widget, int x, int y ) int widget_intersect(const widget *widget, int x, int y) {
{
if (widget == NULL) { if (widget == NULL) {
return FALSE; return FALSE;
} }
if ( x >= ( widget->x ) && x < ( widget->x + widget->w ) && if (x >= (widget->x) && x < (widget->x + widget->w) && y >= (widget->y) &&
y >= ( widget->y ) && y < ( widget->y + widget->h ) ) { y < (widget->y + widget->h)) {
return TRUE; return TRUE;
} }
return FALSE; return FALSE;
} }
void widget_resize ( widget *widget, short w, short h ) void widget_resize(widget *widget, short w, short h) {
{
if (widget == NULL) { if (widget == NULL) {
return; return;
} }
@@ -96,48 +107,42 @@ void widget_resize ( widget *widget, short w, short h )
if (widget->w != w || widget->h != h) { if (widget->w != w || widget->h != h) {
widget->resize(widget, w, h); widget->resize(widget, w, h);
} }
} } else {
else {
widget->w = w; widget->w = w;
widget->h = h; widget->h = h;
} }
// On a resize we always want to update. // On a resize we always want to update.
widget_queue_redraw(widget); widget_queue_redraw(widget);
} }
void widget_move ( widget *widget, short x, short y ) void widget_move(widget *widget, short x, short y) {
{
if (widget == NULL) { if (widget == NULL) {
return; return;
} }
widget->x = x; widget->x = x;
widget->y = y; widget->y = y;
} }
void widget_set_type ( widget *widget, WidgetType type ) void widget_set_type(widget *widget, WidgetType type) {
{
if (widget == NULL) { if (widget == NULL) {
return; return;
} }
widget->type = type; widget->type = type;
} }
WidgetType widget_type ( widget *widget ) WidgetType widget_type(widget *widget) {
{
if (widget == NULL) { if (widget == NULL) {
return WIDGET_TYPE_UNKNOWN; return WIDGET_TYPE_UNKNOWN;
} }
return widget->type; return widget->type;
} }
gboolean widget_enabled ( widget *widget ) gboolean widget_enabled(widget *widget) {
{
if (widget == NULL) { if (widget == NULL) {
return FALSE; return FALSE;
} }
return widget->enabled; return widget->enabled;
} }
void widget_set_enabled ( widget *widget, gboolean enabled ) void widget_set_enabled(widget *widget, gboolean enabled) {
{
if (widget == NULL) { if (widget == NULL) {
return; return;
} }
@@ -149,8 +154,7 @@ void widget_set_enabled ( widget *widget, gboolean enabled )
} }
} }
void widget_draw ( widget *widget, cairo_t *d ) void widget_draw(widget *widget, cairo_t *d) {
{
if (widget == NULL) { if (widget == NULL) {
return; return;
} }
@@ -163,21 +167,35 @@ void widget_draw ( widget *widget, cairo_t *d )
} }
// Store current state. // Store current state.
cairo_save(d); cairo_save(d);
const int margin_left = distance_get_pixel ( widget->margin.left, ROFI_ORIENTATION_HORIZONTAL ); const int margin_left =
const int margin_top = distance_get_pixel ( widget->margin.top, ROFI_ORIENTATION_VERTICAL ); distance_get_pixel(widget->margin.left, ROFI_ORIENTATION_HORIZONTAL);
const int margin_right = distance_get_pixel ( widget->margin.right, ROFI_ORIENTATION_HORIZONTAL ); const int margin_top =
const int margin_bottom = distance_get_pixel ( widget->margin.bottom, ROFI_ORIENTATION_VERTICAL ); distance_get_pixel(widget->margin.top, ROFI_ORIENTATION_VERTICAL);
const int left = distance_get_pixel ( widget->border.left, ROFI_ORIENTATION_HORIZONTAL ); const int margin_right =
const int right = distance_get_pixel ( widget->border.right, ROFI_ORIENTATION_HORIZONTAL ); distance_get_pixel(widget->margin.right, ROFI_ORIENTATION_HORIZONTAL);
const int top = distance_get_pixel ( widget->border.top, ROFI_ORIENTATION_VERTICAL ); const int margin_bottom =
const int bottom = distance_get_pixel ( widget->border.bottom, ROFI_ORIENTATION_VERTICAL ); distance_get_pixel(widget->margin.bottom, ROFI_ORIENTATION_VERTICAL);
int radius_bl = distance_get_pixel ( widget->border_radius.left, ROFI_ORIENTATION_HORIZONTAL ); const int left =
int radius_tr = distance_get_pixel ( widget->border_radius.right, ROFI_ORIENTATION_HORIZONTAL ); distance_get_pixel(widget->border.left, ROFI_ORIENTATION_HORIZONTAL);
int radius_tl = distance_get_pixel ( widget->border_radius.top, ROFI_ORIENTATION_VERTICAL ); const int right =
int radius_br = distance_get_pixel ( widget->border_radius.bottom, ROFI_ORIENTATION_VERTICAL ); distance_get_pixel(widget->border.right, ROFI_ORIENTATION_HORIZONTAL);
const int top =
distance_get_pixel(widget->border.top, ROFI_ORIENTATION_VERTICAL);
const int bottom =
distance_get_pixel(widget->border.bottom, ROFI_ORIENTATION_VERTICAL);
int radius_bl = distance_get_pixel(widget->border_radius.left,
ROFI_ORIENTATION_HORIZONTAL);
int radius_tr = distance_get_pixel(widget->border_radius.right,
ROFI_ORIENTATION_HORIZONTAL);
int radius_tl = distance_get_pixel(widget->border_radius.top,
ROFI_ORIENTATION_VERTICAL);
int radius_br = distance_get_pixel(widget->border_radius.bottom,
ROFI_ORIENTATION_VERTICAL);
double vspace = widget->h - margin_top - margin_bottom - top / 2.0 - bottom / 2.0; double vspace =
double hspace = widget->w - margin_left - margin_right - left / 2.0 - right / 2.0; widget->h - margin_top - margin_bottom - top / 2.0 - bottom / 2.0;
double hspace =
widget->w - margin_left - margin_right - left / 2.0 - right / 2.0;
if ((radius_bl + radius_tl) > (vspace)) { if ((radius_bl + radius_tl) > (vspace)) {
int j = ((vspace) / 2.0); int j = ((vspace) / 2.0);
radius_bl = MIN(radius_bl, j); radius_bl = MIN(radius_bl, j);
@@ -206,32 +224,35 @@ void widget_draw ( widget *widget, cairo_t *d )
// Outer outline outlines // Outer outline outlines
double x1, y1, x2, y2; double x1, y1, x2, y2;
x1 = margin_left + left / 2.0, x1 = margin_left + left / 2.0, y1 = margin_top + top / 2.0,
y1 = margin_top + top / 2.0,
x2 = widget->w - margin_right - right / 2.0, x2 = widget->w - margin_right - right / 2.0,
y2 = widget->h - margin_bottom - bottom / 2.0; y2 = widget->h - margin_bottom - bottom / 2.0;
if (radius_tl > 0) { if (radius_tl > 0) {
cairo_move_to(d, x1, y1 + radius_tl); cairo_move_to(d, x1, y1 + radius_tl);
cairo_arc ( d, x1 + radius_tl, y1 + radius_tl, radius_tl, -1.0 * G_PI, -G_PI_2 ); cairo_arc(d, x1 + radius_tl, y1 + radius_tl, radius_tl, -1.0 * G_PI,
-G_PI_2);
} else { } else {
cairo_move_to(d, x1, y1); cairo_move_to(d, x1, y1);
} }
if (radius_tr > 0) { if (radius_tr > 0) {
cairo_line_to(d, x2 - radius_tr, y1); cairo_line_to(d, x2 - radius_tr, y1);
cairo_arc ( d, x2 - radius_tr, y1 + radius_tr, radius_tr, -G_PI_2, 0 * G_PI ); cairo_arc(d, x2 - radius_tr, y1 + radius_tr, radius_tr, -G_PI_2,
0 * G_PI);
} else { } else {
cairo_line_to(d, x2, y1); cairo_line_to(d, x2, y1);
} }
if (radius_br > 0) { if (radius_br > 0) {
cairo_line_to(d, x2, y2 - radius_br); cairo_line_to(d, x2, y2 - radius_br);
cairo_arc ( d, x2 - radius_br, y2 - radius_br, radius_br, 0.0 * G_PI, G_PI_2 ); cairo_arc(d, x2 - radius_br, y2 - radius_br, radius_br, 0.0 * G_PI,
G_PI_2);
} else { } else {
cairo_line_to(d, x2, y2); cairo_line_to(d, x2, y2);
} }
if (radius_bl > 0) { if (radius_bl > 0) {
cairo_line_to(d, x1 + radius_bl, y2); cairo_line_to(d, x1 + radius_bl, y2);
cairo_arc ( d, x1 + radius_bl, y2 - radius_bl, radius_bl, G_PI_2, 1.0 * G_PI ); cairo_arc(d, x1 + radius_bl, y2 - radius_bl, radius_bl, G_PI_2,
1.0 * G_PI);
} else { } else {
cairo_line_to(d, x1, y2); cairo_line_to(d, x1, y2);
} }
@@ -280,16 +301,29 @@ void widget_draw ( widget *widget, cairo_t *d )
// bbl bbr // bbl bbr
// | | // | |
// //
// The left and right part ($) start at thinkness top bottom when no radius // The left and right part ($) start at thinkness top bottom when no
double offset_ltl = ( radius_inner_tl > 0 ) ? ( left ) + radius_inner_tl : left; // radius
double offset_rtr = ( radius_inner_tr > 0 ) ? ( right ) + radius_inner_tr : right; double offset_ltl =
double offset_lbl = ( radius_inner_bl > 0 ) ? ( left ) + radius_inner_bl : left; (radius_inner_tl > 0) ? (left) + radius_inner_tl : left;
double offset_rbr = ( radius_inner_br > 0 ) ? ( right ) + radius_inner_br : right; double offset_rtr =
(radius_inner_tr > 0) ? (right) + radius_inner_tr : right;
double offset_lbl =
(radius_inner_bl > 0) ? (left) + radius_inner_bl : left;
double offset_rbr =
(radius_inner_br > 0) ? (right) + radius_inner_br : right;
// The top and bottom part (#) go into the corner when no radius // The top and bottom part (#) go into the corner when no radius
double offset_ttl = ( radius_inner_tl > 0 ) ? ( top ) + radius_inner_tl : ( radius_tl > 0 ) ? top : 0; double offset_ttl = (radius_inner_tl > 0) ? (top) + radius_inner_tl
double offset_ttr = ( radius_inner_tr > 0 ) ? ( top ) + radius_inner_tr : ( radius_tr > 0 ) ? top : 0; : (radius_tl > 0) ? top
double offset_bbl = ( radius_inner_bl > 0 ) ? ( bottom ) + radius_inner_bl : ( radius_bl > 0 ) ? bottom : 0; : 0;
double offset_bbr = ( radius_inner_br > 0 ) ? ( bottom ) + radius_inner_br : ( radius_br > 0 ) ? bottom : 0; double offset_ttr = (radius_inner_tr > 0) ? (top) + radius_inner_tr
: (radius_tr > 0) ? top
: 0;
double offset_bbl = (radius_inner_bl > 0) ? (bottom) + radius_inner_bl
: (radius_bl > 0) ? bottom
: 0;
double offset_bbr = (radius_inner_br > 0) ? (bottom) + radius_inner_br
: (radius_br > 0) ? bottom
: 0;
if (left > 0) { if (left > 0) {
cairo_set_line_width(d, left); cairo_set_line_width(d, left);
@@ -323,12 +357,12 @@ void widget_draw ( widget *widget, cairo_t *d )
distance_get_linestyle(widget->border.left, d); distance_get_linestyle(widget->border.left, d);
cairo_set_line_width(d, 0); cairo_set_line_width(d, 0);
double radius_outer = radius_tl + minof_tl; double radius_outer = radius_tl + minof_tl;
cairo_arc ( d, margin_left + radius_outer, margin_top + radius_outer, radius_outer, -G_PI, -G_PI_2 ); cairo_arc(d, margin_left + radius_outer, margin_top + radius_outer,
radius_outer, -G_PI, -G_PI_2);
cairo_line_to(d, margin_left + offset_ltl, margin_top); cairo_line_to(d, margin_left + offset_ltl, margin_top);
cairo_line_to(d, margin_left + offset_ltl, margin_top + top); cairo_line_to(d, margin_left + offset_ltl, margin_top + top);
if (radius_inner_tl > 0) { if (radius_inner_tl > 0) {
cairo_arc_negative ( d, cairo_arc_negative(d, margin_left + left + radius_inner_tl,
margin_left + left + radius_inner_tl,
margin_top + top + radius_inner_tl, margin_top + top + radius_inner_tl,
radius_inner_tl, -G_PI_2, G_PI); radius_inner_tl, -G_PI_2, G_PI);
cairo_line_to(d, margin_left + left, margin_top + offset_ttl); cairo_line_to(d, margin_left + left, margin_top + offset_ttl);
@@ -341,14 +375,17 @@ void widget_draw ( widget *widget, cairo_t *d )
distance_get_linestyle(widget->border.right, d); distance_get_linestyle(widget->border.right, d);
cairo_set_line_width(d, 0); cairo_set_line_width(d, 0);
double radius_outer = radius_tr + minof_tr; double radius_outer = radius_tr + minof_tr;
cairo_arc ( d, widget->w - margin_right - radius_outer, margin_top + radius_outer, radius_outer, -G_PI_2, 0 ); cairo_arc(d, widget->w - margin_right - radius_outer,
margin_top + radius_outer, radius_outer, -G_PI_2, 0);
cairo_line_to(d, widget->w - margin_right, margin_top + offset_ttr); cairo_line_to(d, widget->w - margin_right, margin_top + offset_ttr);
cairo_line_to ( d, widget->w - margin_right - right, margin_top + offset_ttr ); cairo_line_to(d, widget->w - margin_right - right,
margin_top + offset_ttr);
if (radius_inner_tr > 0) { if (radius_inner_tr > 0) {
cairo_arc_negative ( d, widget->w - margin_right - right - radius_inner_tr, cairo_arc_negative(
margin_top + top + radius_inner_tr, d, widget->w - margin_right - right - radius_inner_tr,
radius_inner_tr, 0, -G_PI_2 ); margin_top + top + radius_inner_tr, radius_inner_tr, 0, -G_PI_2);
cairo_line_to ( d, widget->w - margin_right - offset_rtr, margin_top + top ); cairo_line_to(d, widget->w - margin_right - offset_rtr,
margin_top + top);
} }
cairo_line_to(d, widget->w - margin_right - offset_rtr, margin_top); cairo_line_to(d, widget->w - margin_right - offset_rtr, margin_top);
cairo_close_path(d); cairo_close_path(d);
@@ -358,16 +395,23 @@ void widget_draw ( widget *widget, cairo_t *d )
distance_get_linestyle(widget->border.right, d); distance_get_linestyle(widget->border.right, d);
cairo_set_line_width(d, 1); cairo_set_line_width(d, 1);
double radius_outer = radius_br + minof_br; double radius_outer = radius_br + minof_br;
cairo_arc ( d, widget->w - margin_right - radius_outer, widget->h - margin_bottom - radius_outer, radius_outer, 0.0, G_PI_2 ); cairo_arc(d, widget->w - margin_right - radius_outer,
cairo_line_to ( d, widget->w - margin_right - offset_rbr, widget->h - margin_bottom ); widget->h - margin_bottom - radius_outer, radius_outer, 0.0,
cairo_line_to ( d, widget->w - margin_right - offset_rbr, widget->h - margin_bottom - bottom ); G_PI_2);
cairo_line_to(d, widget->w - margin_right - offset_rbr,
widget->h - margin_bottom);
cairo_line_to(d, widget->w - margin_right - offset_rbr,
widget->h - margin_bottom - bottom);
if (radius_inner_br > 0) { if (radius_inner_br > 0) {
cairo_arc_negative ( d, widget->w - margin_right - right - radius_inner_br, cairo_arc_negative(
d, widget->w - margin_right - right - radius_inner_br,
widget->h - margin_bottom - bottom - radius_inner_br, widget->h - margin_bottom - bottom - radius_inner_br,
radius_inner_br, G_PI_2, 0.0); radius_inner_br, G_PI_2, 0.0);
cairo_line_to ( d, widget->w - margin_right - right, widget->h - margin_bottom - offset_bbr ); cairo_line_to(d, widget->w - margin_right - right,
widget->h - margin_bottom - offset_bbr);
} }
cairo_line_to ( d, widget->w - margin_right, widget->h - margin_bottom - offset_bbr ); cairo_line_to(d, widget->w - margin_right,
widget->h - margin_bottom - offset_bbr);
cairo_close_path(d); cairo_close_path(d);
cairo_fill(d); cairo_fill(d);
} }
@@ -375,14 +419,19 @@ void widget_draw ( widget *widget, cairo_t *d )
distance_get_linestyle(widget->border.left, d); distance_get_linestyle(widget->border.left, d);
cairo_set_line_width(d, 1.0); cairo_set_line_width(d, 1.0);
double radius_outer = radius_bl + minof_bl; double radius_outer = radius_bl + minof_bl;
cairo_arc ( d, margin_left + radius_outer, widget->h - margin_bottom - radius_outer, radius_outer, G_PI_2, G_PI ); cairo_arc(d, margin_left + radius_outer,
widget->h - margin_bottom - radius_outer, radius_outer,
G_PI_2, G_PI);
cairo_line_to(d, margin_left, widget->h - margin_bottom - offset_bbl); cairo_line_to(d, margin_left, widget->h - margin_bottom - offset_bbl);
cairo_line_to ( d, margin_left + left, widget->h - margin_bottom - offset_bbl ); cairo_line_to(d, margin_left + left,
widget->h - margin_bottom - offset_bbl);
if (radius_inner_bl > 0) { if (radius_inner_bl > 0) {
cairo_arc_negative(d, margin_left + left + radius_inner_bl, cairo_arc_negative(d, margin_left + left + radius_inner_bl,
widget->h - margin_bottom - bottom - radius_inner_bl, widget->h - margin_bottom - bottom -
radius_inner_bl,
radius_inner_bl, G_PI, G_PI_2); radius_inner_bl, G_PI, G_PI_2);
cairo_line_to ( d, margin_left + offset_lbl, widget->h - margin_bottom - bottom ); cairo_line_to(d, margin_left + offset_lbl,
widget->h - margin_bottom - bottom);
} }
cairo_line_to(d, margin_left + offset_lbl, widget->h - margin_bottom); cairo_line_to(d, margin_left + offset_lbl, widget->h - margin_bottom);
cairo_close_path(d); cairo_close_path(d);
@@ -395,8 +444,7 @@ void widget_draw ( widget *widget, cairo_t *d )
} }
} }
void widget_free ( widget *wid ) void widget_free(widget *wid) {
{
if (wid == NULL) { if (wid == NULL) {
return; return;
} }
@@ -408,8 +456,7 @@ void widget_free ( widget *wid )
} }
} }
int widget_get_height ( widget *widget ) int widget_get_height(widget *widget) {
{
if (widget == NULL) { if (widget == NULL) {
return 0; return 0;
} }
@@ -418,8 +465,7 @@ int widget_get_height ( widget *widget )
} }
return widget->get_height(widget); return widget->get_height(widget);
} }
int widget_get_width ( widget *widget ) int widget_get_width(widget *widget) {
{
if (widget == NULL) { if (widget == NULL) {
return 0; return 0;
} }
@@ -428,23 +474,20 @@ int widget_get_width ( widget *widget )
} }
return widget->get_width(widget); return widget->get_width(widget);
} }
int widget_get_x_pos ( widget *widget ) int widget_get_x_pos(widget *widget) {
{
if (widget == NULL) { if (widget == NULL) {
return 0; return 0;
} }
return widget->x; return widget->x;
} }
int widget_get_y_pos ( widget *widget ) int widget_get_y_pos(widget *widget) {
{
if (widget == NULL) { if (widget == NULL) {
return 0; return 0;
} }
return widget->y; return widget->y;
} }
void widget_xy_to_relative ( widget *widget, gint *x, gint *y ) void widget_xy_to_relative(widget *widget, gint *x, gint *y) {
{
*x -= widget->x; *x -= widget->x;
*y -= widget->y; *y -= widget->y;
if (widget->parent == NULL) { if (widget->parent == NULL) {
@@ -453,8 +496,7 @@ void widget_xy_to_relative ( widget *widget, gint *x, gint *y )
widget_xy_to_relative(widget->parent, x, y); widget_xy_to_relative(widget->parent, x, y);
} }
void widget_update ( widget *widget ) void widget_update(widget *widget) {
{
if (widget == NULL) { if (widget == NULL) {
return; return;
} }
@@ -464,8 +506,7 @@ void widget_update ( widget *widget )
} }
} }
void widget_queue_redraw ( widget *wid ) void widget_queue_redraw(widget *wid) {
{
if (wid == NULL) { if (wid == NULL) {
return; return;
} }
@@ -478,8 +519,7 @@ void widget_queue_redraw ( widget *wid )
iter->need_redraw = TRUE; iter->need_redraw = TRUE;
} }
gboolean widget_need_redraw ( widget *wid ) gboolean widget_need_redraw(widget *wid) {
{
if (wid == NULL) { if (wid == NULL) {
return FALSE; return FALSE;
} }
@@ -489,8 +529,7 @@ gboolean widget_need_redraw ( widget *wid )
return wid->need_redraw; return wid->need_redraw;
} }
widget *widget_find_mouse_target ( widget *wid, WidgetType type, gint x, gint y ) widget *widget_find_mouse_target(widget *wid, WidgetType type, gint x, gint y) {
{
if (wid == NULL) { if (wid == NULL) {
return NULL; return NULL;
} }
@@ -509,8 +548,8 @@ widget *widget_find_mouse_target ( widget *wid, WidgetType type, gint x, gint y
return NULL; return NULL;
} }
WidgetTriggerActionResult widget_trigger_action ( widget *wid, guint action, gint x, gint y ) WidgetTriggerActionResult widget_trigger_action(widget *wid, guint action,
{ gint x, gint y) {
if (wid == NULL) { if (wid == NULL) {
return FALSE; return FALSE;
} }
@@ -520,8 +559,8 @@ WidgetTriggerActionResult widget_trigger_action ( widget *wid, guint action, gin
return wid->trigger_action(wid, action, x, y, wid->trigger_action_cb_data); return wid->trigger_action(wid, action, x, y, wid->trigger_action_cb_data);
} }
void widget_set_trigger_action_handler ( widget *wid, widget_trigger_action_cb cb, void * cb_data ) void widget_set_trigger_action_handler(widget *wid, widget_trigger_action_cb cb,
{ void *cb_data) {
if (wid == NULL) { if (wid == NULL) {
return; return;
} }
@@ -529,8 +568,7 @@ void widget_set_trigger_action_handler ( widget *wid, widget_trigger_action_cb c
wid->trigger_action_cb_data = cb_data; wid->trigger_action_cb_data = cb_data;
} }
gboolean widget_motion_notify ( widget *wid, gint x, gint y ) gboolean widget_motion_notify(widget *wid, gint x, gint y) {
{
if (wid == NULL) { if (wid == NULL) {
return FALSE; return FALSE;
} }
@@ -540,78 +578,75 @@ gboolean widget_motion_notify ( widget *wid, gint x, gint y )
return wid->motion_notify(wid, x, y); return wid->motion_notify(wid, x, y);
} }
int widget_padding_get_left ( const widget *wid ) int widget_padding_get_left(const widget *wid) {
{
if (wid == NULL) { if (wid == NULL) {
return 0; return 0;
} }
int distance = distance_get_pixel ( wid->padding.left, ROFI_ORIENTATION_HORIZONTAL ); int distance =
distance_get_pixel(wid->padding.left, ROFI_ORIENTATION_HORIZONTAL);
distance += distance_get_pixel(wid->border.left, ROFI_ORIENTATION_HORIZONTAL); distance += distance_get_pixel(wid->border.left, ROFI_ORIENTATION_HORIZONTAL);
distance += distance_get_pixel(wid->margin.left, ROFI_ORIENTATION_HORIZONTAL); distance += distance_get_pixel(wid->margin.left, ROFI_ORIENTATION_HORIZONTAL);
return distance; return distance;
} }
int widget_padding_get_right ( const widget *wid ) int widget_padding_get_right(const widget *wid) {
{
if (wid == NULL) { if (wid == NULL) {
return 0; return 0;
} }
int distance = distance_get_pixel ( wid->padding.right, ROFI_ORIENTATION_HORIZONTAL ); int distance =
distance += distance_get_pixel ( wid->border.right, ROFI_ORIENTATION_HORIZONTAL ); distance_get_pixel(wid->padding.right, ROFI_ORIENTATION_HORIZONTAL);
distance += distance_get_pixel ( wid->margin.right, ROFI_ORIENTATION_HORIZONTAL ); distance +=
distance_get_pixel(wid->border.right, ROFI_ORIENTATION_HORIZONTAL);
distance +=
distance_get_pixel(wid->margin.right, ROFI_ORIENTATION_HORIZONTAL);
return distance; return distance;
} }
int widget_padding_get_top ( const widget *wid ) int widget_padding_get_top(const widget *wid) {
{
if (wid == NULL) { if (wid == NULL) {
return 0; return 0;
} }
int distance = distance_get_pixel ( wid->padding.top, ROFI_ORIENTATION_VERTICAL ); int distance =
distance_get_pixel(wid->padding.top, ROFI_ORIENTATION_VERTICAL);
distance += distance_get_pixel(wid->border.top, ROFI_ORIENTATION_VERTICAL); distance += distance_get_pixel(wid->border.top, ROFI_ORIENTATION_VERTICAL);
distance += distance_get_pixel(wid->margin.top, ROFI_ORIENTATION_VERTICAL); distance += distance_get_pixel(wid->margin.top, ROFI_ORIENTATION_VERTICAL);
return distance; return distance;
} }
int widget_padding_get_bottom ( const widget *wid ) int widget_padding_get_bottom(const widget *wid) {
{
if (wid == NULL) { if (wid == NULL) {
return 0; return 0;
} }
int distance = distance_get_pixel ( wid->padding.bottom, ROFI_ORIENTATION_VERTICAL ); int distance =
distance_get_pixel(wid->padding.bottom, ROFI_ORIENTATION_VERTICAL);
distance += distance_get_pixel(wid->border.bottom, ROFI_ORIENTATION_VERTICAL); distance += distance_get_pixel(wid->border.bottom, ROFI_ORIENTATION_VERTICAL);
distance += distance_get_pixel(wid->margin.bottom, ROFI_ORIENTATION_VERTICAL); distance += distance_get_pixel(wid->margin.bottom, ROFI_ORIENTATION_VERTICAL);
return distance; return distance;
} }
int widget_padding_get_remaining_width ( const widget *wid ) int widget_padding_get_remaining_width(const widget *wid) {
{
int width = wid->w; int width = wid->w;
width -= widget_padding_get_left(wid); width -= widget_padding_get_left(wid);
width -= widget_padding_get_right(wid); width -= widget_padding_get_right(wid);
return width; return width;
} }
int widget_padding_get_remaining_height ( const widget *wid ) int widget_padding_get_remaining_height(const widget *wid) {
{
int height = wid->h; int height = wid->h;
height -= widget_padding_get_top(wid); height -= widget_padding_get_top(wid);
height -= widget_padding_get_bottom(wid); height -= widget_padding_get_bottom(wid);
return height; return height;
} }
int widget_padding_get_padding_height ( const widget *wid ) int widget_padding_get_padding_height(const widget *wid) {
{
int height = 0; int height = 0;
height += widget_padding_get_top(wid); height += widget_padding_get_top(wid);
height += widget_padding_get_bottom(wid); height += widget_padding_get_bottom(wid);
return height; return height;
} }
int widget_padding_get_padding_width ( const widget *wid ) int widget_padding_get_padding_width(const widget *wid) {
{
int width = 0; int width = 0;
width += widget_padding_get_left(wid); width += widget_padding_get_left(wid);
width += widget_padding_get_right(wid); width += widget_padding_get_right(wid);
return width; return width;
} }
int widget_get_desired_height ( widget *wid ) int widget_get_desired_height(widget *wid) {
{
if (wid == NULL) { if (wid == NULL) {
return 0; return 0;
} }
@@ -620,8 +655,7 @@ int widget_get_desired_height ( widget *wid )
} }
return wid->get_desired_height(wid); return wid->get_desired_height(wid);
} }
int widget_get_desired_width ( widget *wid ) int widget_get_desired_width(widget *wid) {
{
if (wid == NULL) { if (wid == NULL) {
return 0; return 0;
} }
@@ -631,8 +665,7 @@ int widget_get_desired_width ( widget *wid )
return wid->get_desired_width(wid); return wid->get_desired_width(wid);
} }
int widget_get_absolute_xpos ( widget *wid ) int widget_get_absolute_xpos(widget *wid) {
{
if (wid == NULL) { if (wid == NULL) {
return 0; return 0;
} }
@@ -642,8 +675,7 @@ int widget_get_absolute_xpos ( widget *wid )
} }
return retv; return retv;
} }
int widget_get_absolute_ypos ( widget *wid ) int widget_get_absolute_ypos(widget *wid) {
{
if (wid == NULL) { if (wid == NULL) {
return 0; return 0;
} }

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff