Example #1
0
int
main (int argc, char *argv [])
{
    /*Running Shell*/
    GError *error  = NULL;

    python_shell_data = g_try_malloc (sizeof (ChildProcessData));
    python_shell_data->argv = NULL;
    python_shell_data->slave_termios = g_try_malloc (sizeof (struct termios));
    python_shell_data->current_dir = NULL;

    bash_loaded = ptyFork (python_shell_data, &error);
    gtk_init (&argc, &argv);

    python_shell_data->channel = g_io_channel_unix_new (python_shell_data->master_fd);
    g_io_add_watch (python_shell_data->channel, G_IO_IN,
                   (GIOFunc)read_masterFd, &(python_shell_data->master_fd));

    /**********/
    
     /*Loading Options*/
    if (g_file_test ("./options.inf", G_FILE_TEST_EXISTS))
        load_options_from_file ("./options.inf");
    else
    {
        options.indent_width = 4;
        options.tab_width = 4;
        options.is_code_completion = TRUE;
        options.is_code_folding = TRUE;
        options.show_line_numbers = TRUE;
        options.font_name = "Liberation Mono";
    }
    /*************/
    options.python_shell_path = "/usr/bin/python";
    options.comment_out_str = "##";
    options.indent_width_str = "    ";
    options.tab_width_str = "    ";

    env_python_path = "";
    gchar **p = options.env_vars;
    if (p)
    {
        while (*p)
        {
            gchar *s = g_strstr_len (*p, -1, "PYTHONPATH=");
            if (s)
            {
                env_python_path = s + strlen ("PYTHONPATH=");
                break;
            }
            p++;
        }
    }

    /*Get sys.path*/
    char *sys_path_argv[] = {"python", "./scripts/path.py", NULL}; 
    g_spawn_sync (NULL, sys_path_argv, NULL, G_SPAWN_SEARCH_PATH,
                               NULL, NULL, &sys_path_string, NULL, NULL, NULL);
    /***********/

    char *_str = g_strconcat (sys_path_string, "\n", env_python_path, NULL);
    g_free (sys_path_string);
    sys_path_string = _str; 
    
    file_monitor = file_monitor_new (file_monitor_changed);

    /*Setting Main Window*/    
    GtkWidget *navigate_bookmarks;
    builder = gtk_builder_new ();
    gtk_builder_add_from_file (builder, "./ui/main.ui", NULL);

    content_box = GTK_WIDGET (gtk_builder_get_object (builder, "content_box"));

    window = gtk_builder_get_object (builder, "main_window");
    g_signal_connect (window, "destroy", G_CALLBACK (gtk_main_quit), NULL);

    path_browser = path_browser_new ();
    g_object_ref (path_browser);

    proj_notebook = project_notebook_new ();
    
    /**Setting proj_syms_tree_view**/
    symbols_view = symbols_view_new ();

    g_object_ref (symbols_view);
    /*************************/
    content_paned = gtk_paned_new (GTK_ORIENTATION_HORIZONTAL);
    g_object_ref (content_paned);

    status_bar = gtk_statusbar_new ();
    g_object_ref (status_bar);
    
    gtk_notebook_append_page (GTK_NOTEBOOK (proj_notebook),
                                   symbols_view, gtk_label_new ("Symbols"));
    gtk_notebook_append_page (GTK_NOTEBOOK (proj_notebook), 
                                   path_browser,
                                   gtk_label_new ("Paths"));

    navigate_bookmarks = GTK_WIDGET (gtk_builder_get_object (builder,
                                    "navigate_bookmarks"));
    bookmarks_menu = gtk_menu_new ();

    gtk_menu_item_set_submenu (GTK_MENU_ITEM (navigate_bookmarks),
                              bookmarks_menu);

    GtkAccelGroup *accelgroup = GTK_ACCEL_GROUP (gtk_builder_get_object (builder,
                                                                       "accelgroup"));

    /*Connecting menu item's signals*/ 
    //For File Menu
    g_signal_connect (gtk_builder_get_object (builder, "file_new"), "activate",
                      G_CALLBACK (file_new_activate), NULL);
    g_signal_connect (gtk_builder_get_object (builder, "file_new_tab"), "activate",
                      G_CALLBACK (file_new_tab_activate), NULL);
    g_signal_connect (gtk_builder_get_object (builder, "file_open"), "activate",
                      G_CALLBACK (file_open_activate), NULL);
    g_signal_connect (gtk_builder_get_object (builder, "recentchoosermenu"), "selection-done",
                      G_CALLBACK (file_recent_menu_selection_done), NULL);
    g_signal_connect (gtk_builder_get_object (builder, "file_save"), "activate",
                                   G_CALLBACK (file_save_activate), NULL);
    g_signal_connect (gtk_builder_get_object (builder, "file_save_as"), "activate",
                                   G_CALLBACK (file_save_as_activate), NULL);
    g_signal_connect (gtk_builder_get_object (builder, "file_save_copy_as"), "activate",
                                   G_CALLBACK (file_save_copy_as_activate), NULL);
    g_signal_connect (gtk_builder_get_object (builder, "file_save_all"), "activate",
                                   G_CALLBACK (file_save_all_activate), NULL);
    g_signal_connect (gtk_builder_get_object (builder, "file_close_tab"), "activate",
                                   G_CALLBACK (file_close_tab_activate), NULL);
    g_signal_connect (gtk_builder_get_object (builder, "file_close_all_tabs"), "activate",
                      G_CALLBACK (file_close_all_tabs_activate), NULL);
    g_signal_connect (gtk_builder_get_object (builder, "file_quit"), "activate",
                      G_CALLBACK (file_quit_activate), NULL);
    
    //For Edit Menu           
    g_signal_connect (gtk_builder_get_object (builder, "edit_undo"), "activate",
                                   G_CALLBACK (edit_undo_activate), NULL);
    g_signal_connect (gtk_builder_get_object (builder, "edit_redo"), "activate",
                                   G_CALLBACK (edit_redo_activate), NULL);
    g_signal_connect (gtk_builder_get_object (builder, "edit_cut"), "activate",
                                   G_CALLBACK (edit_cut_activate), NULL);
    g_signal_connect (gtk_builder_get_object (builder, "edit_copy"), "activate",
                                   G_CALLBACK (edit_copy_activate), NULL);
    g_signal_connect (gtk_builder_get_object (builder, "edit_paste"), "activate",
                                   G_CALLBACK (edit_paste_activate), NULL);
    g_signal_connect (gtk_builder_get_object (builder, "edit_delete"), "activate",
                                   G_CALLBACK (edit_delete_activate), NULL);
    g_signal_connect (gtk_builder_get_object (builder, "edit_select_all"), "activate",
                                   G_CALLBACK (edit_select_all_activate), NULL);
    g_signal_connect (gtk_builder_get_object (builder, "edit_select_function"), "activate",
                                   G_CALLBACK (edit_select_function_activate), NULL);
    g_signal_connect (gtk_builder_get_object (builder, "edit_select_block"), "activate",
                                   G_CALLBACK (edit_select_block_activate), NULL);
    g_signal_connect (gtk_builder_get_object (builder, "edit_fold_all_func"), "activate",
                                   G_CALLBACK (edit_fold_all_func_activate), NULL);
    g_signal_connect (gtk_builder_get_object (builder, "edit_unfold_all_func"), "activate",
                                   G_CALLBACK (edit_unfold_all_func_activate), NULL);
    g_signal_connect (gtk_builder_get_object (builder, "edit_fold_current_func"), "activate",
                                   G_CALLBACK (edit_fold_current_func_activate), NULL);
    g_signal_connect (gtk_builder_get_object (builder, "edit_autocomplete"), "activate",
                                   G_CALLBACK (edit_autocomplete_activate), NULL);
    g_signal_connect (gtk_builder_get_object (builder, "edit_matching_paranthesis"), "activate",
                                   G_CALLBACK (edit_matching_paranthesis_activate), NULL);
        
    //For Format Menu
    g_signal_connect (gtk_builder_get_object (builder, "format_inc_indent"), "activate",
                                   G_CALLBACK (format_inc_indent_activate), NULL);
    gtk_widget_add_accelerator (GTK_WIDGET (gtk_builder_get_object (builder, "format_inc_indent")),
                               "activate", accelgroup, GDK_KEY_bracketright, 
                                GDK_CONTROL_MASK, GTK_ACCEL_VISIBLE);

    g_signal_connect (gtk_builder_get_object (builder, "format_dec_indent"), "activate",
                                   G_CALLBACK (format_dec_indent_activate), NULL);
    gtk_widget_add_accelerator (GTK_WIDGET (gtk_builder_get_object (builder, "format_dec_indent")),
                               "activate", accelgroup, GDK_KEY_bracketleft, 
                                GDK_CONTROL_MASK, GTK_ACCEL_VISIBLE);

    g_signal_connect (gtk_builder_get_object (builder, "format_comment_out"), "activate",
                                   G_CALLBACK (format_comment_out_activate), NULL);
    gtk_widget_add_accelerator (GTK_WIDGET (gtk_builder_get_object (builder, "format_comment_out")),
                               "activate", accelgroup, GDK_KEY_3, 
                                GDK_MOD1_MASK, GTK_ACCEL_VISIBLE);

    g_signal_connect (gtk_builder_get_object (builder, "format_uncomment_out"), "activate",
                                   G_CALLBACK (format_uncomment_out_activate), NULL);
    gtk_widget_add_accelerator (GTK_WIDGET (gtk_builder_get_object (builder, "format_uncomment_out")),
                               "activate", accelgroup, GDK_KEY_4, 
                                GDK_MOD1_MASK, GTK_ACCEL_VISIBLE);

    g_signal_connect (gtk_builder_get_object (builder, "format_tabify_region"), "activate",
                                   G_CALLBACK (format_tabify_region_activate), NULL);
    g_signal_connect (gtk_builder_get_object (builder, "format_untabify_region"), "activate",
                                   G_CALLBACK (format_untabify_region_activate), NULL);
    g_signal_connect (gtk_builder_get_object (builder, "format_uppercase"), "activate",
                                   G_CALLBACK (format_uppercase_activate), NULL);
    g_signal_connect (gtk_builder_get_object (builder, "format_lowercase"), "activate",
                                   G_CALLBACK (format_lowercase_activate), NULL);
    g_signal_connect (gtk_builder_get_object (builder, "format_strip_spaces"), "activate",
                                   G_CALLBACK (format_strip_spaces_activate), NULL);
    
    //For Search Menu
    g_signal_connect (gtk_builder_get_object (builder, "search_find"), "activate",
                                   G_CALLBACK (search_find_activate), NULL);
     g_signal_connect (gtk_builder_get_object (builder, "search_find_next"), "activate",
                                   G_CALLBACK (search_find_next_activate), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "search_find_prev"), "activate",
                                   G_CALLBACK (search_find_prev_activate), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "search_find_replace"), "activate",
                                   G_CALLBACK (search_find_replace_activate), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "search_find_selected"), "activate",
                                   G_CALLBACK (search_find_selected_activate), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "search_find_in_text"), "activate",
                                   G_CALLBACK (search_find_in_text_activate), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "search_find_file"), "activate",
                                   G_CALLBACK (search_find_file_activate), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "search_replace_file"), "activate",
                                   G_CALLBACK (search_replace_file_activate), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "search_reg_exp"), "activate",
                                   G_CALLBACK (search_reg_exp_activate), NULL);   
    
    //For Navigation Menu
    g_signal_connect (gtk_builder_get_object (builder, "navigate_back"), "activate",
                                   G_CALLBACK (navigate_back_activate), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "navigate_forward"), "activate",
                                   G_CALLBACK (navigate_forward_activate), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "navigate_first_line"), "activate",
                                   G_CALLBACK (navigate_first_line_activate), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "navigate_last_line"), "activate",
                                   G_CALLBACK (navigate_last_line_activate), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "navigate_line_history"), "select",
                                   G_CALLBACK (navigate_line_history_select), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "naviagate_add_bookmark"), "activate",
                                   G_CALLBACK (naviagate_add_bookmark_activate), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "naviagate_clear_bookmarks"), "activate",
                                   G_CALLBACK (naviagate_clear_bookmarks_activate), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "navigate_prev_bookmarks"), "activate",
                                   G_CALLBACK (navigate_prev_bookmarks_activate), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "navigate_next_bookmark"), "activate",
                                   G_CALLBACK (navigate_next_bookmark_activate), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "navigate_bookmarks"), "activate",
                                   G_CALLBACK (navigate_bookmarks_activate), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "navigate_go_to_line"), "activate",
                                   G_CALLBACK (navigate_go_to_line_activate), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "navigate_go_to_block_start"), "activate",
                                   G_CALLBACK (navigate_go_to_block_start_activate), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "navigate_go_to_func_def"), "activate",
                                   G_CALLBACK (navigate_go_to_func_def_activate), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "navigate_go_to_next_func"), "activate",
                                   G_CALLBACK (navigate_go_to_next_func_activate), NULL);
    g_signal_connect (gtk_builder_get_object (builder, "navigate_go_to_prev_func"), "activate",
                                   G_CALLBACK (navigate_go_to_prev_func_activate), NULL);
    
    //For Project Menu
    g_signal_connect (gtk_builder_get_object (builder, "project_new"), "activate",
                                   G_CALLBACK (project_new_activate), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "project_open"), "activate",
                                   G_CALLBACK (project_open_activate), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "project_save"), "activate",
                                   G_CALLBACK (project_save_activate), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "project_save_as"), "activate",
                                   G_CALLBACK (project_save_as_activate), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "project_save_copy_as"), "activate",
                                   G_CALLBACK (project_save_copy_as_activate), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "project_empty"), "activate",
                                   G_CALLBACK (project_empty_activate), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "project_close"), "activate",
                                   G_CALLBACK (project_close_activate), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "project_preferences"), "activate",
                                   G_CALLBACK (project_preferences_activate), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "project_recent"), "activate",
                                   G_CALLBACK (project_recent_activate), NULL);
    
    //For Python Shell Menu
    g_signal_connect (gtk_builder_get_object (builder, "python_shell_open"), "activate",
                                   G_CALLBACK (python_shell_open_activate), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "python_shell_restart"), "activate",
                                   G_CALLBACK (python_shell_restart_activate), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "python_shell_close"), "activate",
                                   G_CALLBACK (python_shell_close_activate), NULL);   
    
    //For Run Menu
    g_signal_connect (gtk_builder_get_object (builder, "run_run_script"), "activate",
                                   G_CALLBACK (run_run_script_activate), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "run_debug_script"), "activate",
                                   G_CALLBACK (run_debug_script_activate), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "run_run_project"), "activate",
                                   G_CALLBACK (run_run_project_activate), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "run_debug_project"), "activate",
                                   G_CALLBACK (run_debug_project_activate), NULL);   
    
    //For Debug Menu
    g_signal_connect (gtk_builder_get_object (builder, "debug_open_pdb_shell"), "activate",
                                   G_CALLBACK (debug_open_pdb_shell_activate), NULL);
    
    //For Tools Menu
    g_signal_connect (gtk_builder_get_object (builder, "tools_options"), "activate",
                                   G_CALLBACK (tools_options_activate), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "tools_auto_indent"), "activate",
                                   G_CALLBACK (tools_auto_indent_activate), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "tools_class_browser"), "activate",
                                   G_CALLBACK (tools_class_browser_activate), NULL);   

    /*************************/
    
    /**Connecting Toolbar's signals**/

    g_signal_connect (gtk_builder_get_object (builder, "toolbar_new_menu"), "clicked",
                                   G_CALLBACK (toolbar_new_clicked), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "toolbar_new_file"), "activate",
                                   G_CALLBACK (toolbar_new_file_clicked), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "toolbar_new_project"), "activate",
                                   G_CALLBACK (toolbar_new_proj_clicked), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "toolbar_open_menu"), "clicked",
                                   G_CALLBACK (toolbar_open_clicked), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "toolbar_open_file"), "activate",
                                   G_CALLBACK (toolbar_open_file_clicked), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "toolbar_open_project"), "activate",
                                   G_CALLBACK (toolbar_open_proj_clicked), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "toolbar_save_menu"), "clicked",
                                   G_CALLBACK (toolbar_save_clicked), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "toolbar_save_file"), "activate",
                                   G_CALLBACK (toolbar_save_file_clicked), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "toolbar_save_project"), "activate",
                                   G_CALLBACK (toolbar_save_project_clicked), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "toolbar_save_as"), "clicked",
                                   G_CALLBACK (toolbar_save_as_clicked), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "toolbar_save_as_file"), "activate",
                                   G_CALLBACK (toolbar_save_as_file_clicked), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "toolbar_save_as_project"), "activate",
                                   G_CALLBACK (toolbar_save_as_project_clicked), NULL);  
    
    g_signal_connect (gtk_builder_get_object (builder, "toolbar_undo"), "clicked",
                                   G_CALLBACK (toolbar_undo_clicked), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "toolbar_redo"), "clicked",
                                   G_CALLBACK (toolbar_redo_clicked), NULL);   
                                
    g_signal_connect (gtk_builder_get_object (builder, "toolbar_cut"), "clicked",
                                   G_CALLBACK (toolbar_cut_clicked), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "toolbar_copy"), "clicked",
                                   G_CALLBACK (toolbar_copy_clicked), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "toolbar_paste"), "clicked",
                                   G_CALLBACK (toolbar_cut_clicked), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "toolbar_delete"), "clicked",
                                   G_CALLBACK (toolbar_delete_clicked), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "toolbar_select_all"), "clicked",
                                   G_CALLBACK (toolbar_select_all_clicked), NULL);   
                                
    g_signal_connect (gtk_builder_get_object (builder, "toolbar_find"), "clicked",
                                   G_CALLBACK (toolbar_find_clicked), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "toolbar_find_replace"), "clicked",
                                   G_CALLBACK (toolbar_find_replace_clicked), NULL);   
      
    g_signal_connect (gtk_builder_get_object (builder, "toolbar_inc_indent"), "clicked",
                                   G_CALLBACK (toolbar_inc_indent_clicked), NULL);   
    g_signal_connect (gtk_builder_get_object (builder, "toolbar_dec_indent"), "clicked",
                                   G_CALLBACK (toolbar_dec_indent_clicked), NULL);   
    
    g_signal_connect (gtk_builder_get_object (builder, "toolbar_next_line"), "clicked",
                                   G_CALLBACK (navigate_forward_activate), NULL); 
    g_signal_connect (gtk_builder_get_object (builder, "toolbar_prev_line"), "clicked",
                                   G_CALLBACK (navigate_back_activate), NULL); 
    g_signal_connect (gtk_builder_get_object (builder, "toolbar_add_bookmark"), "clicked",
                                   G_CALLBACK (naviagate_add_bookmark_activate), NULL); 
    g_signal_connect (gtk_builder_get_object (builder, "toolbar_next_bookmark"), "clicked",
                                   G_CALLBACK (navigate_next_bookmark_activate), NULL); 
    g_signal_connect (gtk_builder_get_object (builder, "toolbar_prev_bookmark"), "clicked",
                                   G_CALLBACK (navigate_prev_bookmarks_activate), NULL); 
    g_signal_connect (gtk_builder_get_object (builder, "toolbar_clear_bookmark"), "clicked",
                                   G_CALLBACK (naviagate_clear_bookmarks_activate), NULL); 
    g_signal_connect (gtk_builder_get_object (builder, "toolbar_run"), "clicked",
                                   G_CALLBACK (toolbar_run), NULL); 
    /*g_signal_connect (gtk_builder_get_object (builder, "toolbar_debug"), "clicked",
                                   G_CALLBACK (toolbar_dec_indent_clicked), NULL); */
    g_signal_connect (gtk_builder_get_object (builder, "toolbar_open_shell"), "clicked",
                                   G_CALLBACK (python_shell_open_activate), NULL); 
    g_signal_connect (gtk_builder_get_object (builder, "toolbar_options"), "clicked",
                                   G_CALLBACK (tools_options_activate), NULL); 
    
    gtk_tool_button_set_icon_widget (GTK_TOOL_BUTTON (gtk_builder_get_object (builder, "toolbar_add_bookmark")),
                                      gtk_image_new_from_pixbuf(gdk_pixbuf_new_from_file("./icons/bookmarksadd.png",NULL)));
    gtk_tool_button_set_icon_widget (GTK_TOOL_BUTTON (gtk_builder_get_object (builder, "toolbar_next_bookmark")),
                                      gtk_image_new_from_pixbuf(gdk_pixbuf_new_from_file("./icons/bookmarksnext.png",NULL)));
    gtk_tool_button_set_icon_widget (GTK_TOOL_BUTTON (gtk_builder_get_object (builder, "toolbar_prev_bookmark")),
                                      gtk_image_new_from_pixbuf(gdk_pixbuf_new_from_file("./icons/bookmarksprev.png",NULL)));
    gtk_tool_button_set_icon_widget (GTK_TOOL_BUTTON (gtk_builder_get_object (builder, "toolbar_clear_bookmark")),
                                      gtk_image_new_from_pixbuf(gdk_pixbuf_new_from_file("./icons/bookmarksclear.png",NULL)));

    gtk_tool_button_set_icon_widget (GTK_TOOL_BUTTON (gtk_builder_get_object (builder, "toolbar_debug")),
                                      gtk_image_new_from_pixbuf(gdk_pixbuf_new_from_file("./icons/debug.png",NULL)));

    gtk_tool_button_set_icon_widget (GTK_TOOL_BUTTON (gtk_builder_get_object (builder, "toolbar_open_shell")),
                                      gtk_image_new_from_pixbuf(gdk_pixbuf_new_from_file("./icons/python_shell.png",NULL)));
    /*************************/
    
    line_history_menu = gtk_menu_new ();
    gtk_menu_item_set_submenu (GTK_MENU_ITEM (gtk_builder_get_object (builder, "navigate_line_history")),
                              line_history_menu);
    
    GtkRecentFilter *py_recent_filter = gtk_recent_filter_new ();
    gtk_recent_filter_set_name (py_recent_filter, "Python Files");
    gtk_recent_filter_add_pattern (py_recent_filter, "*.py");

    gtk_recent_chooser_add_filter (GTK_RECENT_CHOOSER (gtk_builder_get_object (builder, "recentchoosermenu")),
                                  py_recent_filter);
    
    /* Connecting window's signals and events */
    g_signal_connect (window, "delete-event",
                      G_CALLBACK (delete_event), NULL);
    g_signal_connect (window, "destroy",
                      G_CALLBACK (main_window_destroy), NULL);
    /********************************/
    
    /*Other global variables*/
    search_text = NULL;
    bookmark_array= NULL;
    bookmark_array_size = 0;
    current_bookmark_index = -1;
    /******************/

    /*Initialize Regular Expressions*/
    regex_class = g_regex_new ("[ \\ \\t]*\\bclass\\b\\s*\\w+\\s*\\(*.*\\)*:", 0, 0, NULL);
    regex_func = g_regex_new ("[ \\ \\t]*def\\s+[\\w\\d_]+\\s*\\(.+\\)\\:", 0, 0, NULL);
    
    /*Regex if you don't want to search imports with in indentation*/
    /*regex_import = g_regex_new ("^import\\s+[\\w\\d_\\.]+", 0, 0, NULL);
    regex_import_as = g_regex_new ("^import\\s+[\\w\\d_\\.]+\\s+as\\s+[\\w\\d_]+", 0, 0, NULL);*/
    regex_from_import = g_regex_new ("^from\\s+[\\w\\d_\\.]+\\s+import\\s+[\\w\\d_]+", 0, 0, NULL);
    regex_from_import_as = g_regex_new ("^from\\s+[\\w\\d_\\.]+\\s+import\\s+[\\w\\d_]+as\\s+[\\w\\d_]", 0, 0, NULL);
    regex_global_var = g_regex_new ("^[\\w\\d_]+\\s*=\\s*[\\w\\d_]+\\s*\\(.+\\)", 0, 0, NULL);
    regex_static_var = g_regex_new ("^\\s*[\\w\\d_]+\\s*=.+", 0, 0, NULL);
    regex_word = g_regex_new ("[self]*[\\w\\d_\\.]+$", 0, 0, NULL);
    regex_local_var = g_regex_new ("^\\s*[\\w\\d_\\.]+\\s*=.+", 0, 0, NULL);
    regex_self_var = g_regex_new ("^\\s+self\\.[\\w\\d_]+\\s*=.+", 0, 0, NULL);

    /*Regex if you want to search imports with in indentation*/
    regex_import = g_regex_new ("^\\s*import\\s+[\\w\\d_\\.]+", 0, 0, NULL);
    regex_import_as = g_regex_new ("^\\s*import\\s+[\\w\\d_]+\\s+as\\s+[\\w\\d_]+", 0, 0, NULL);

    /***********************/
    
    async_queue = g_async_queue_new ();

    //Creating code_widget_array
    //code_widget_array = g_malloc0 (1*sizeof (CodeWidget *));
    //code_widget_array [0] = codewidget_new ();
    code_widget_array_size = 0;
    
    notebook = gtk_notebook_new ();
    g_object_ref (notebook);
    //gtk_notebook_append_page (GTK_NOTEBOOK (notebook), code_widget_array [0]->vbox,
    //                                                 gtk_label_new ("New File"));
    /*If bash is not loaded*/
    if (!bash_loaded)
    {
        gchar *msg = g_strdup_printf ("Cannot run Python Shell (%s)", error->message);
        gtk_statusbar_push (GTK_STATUSBAR (status_bar), 0, msg);
        g_free (msg);
        g_error_free (error);
    }
    /****************/

    GtkSettings *settings = gtk_settings_get_default ();
    g_object_set (settings, "gtk-application-prefer-dark-theme", TRUE, NULL);
    gtk_window_maximize (GTK_WINDOW (window));
    gtk_widget_show_all (GTK_WIDGET (window));
    gtk_main ();
    return 0;
}
Example #2
0
static Xml2EventInfoT *snmp_bc_findevent4dupstr(gchar *search_str,
						Xml2EventInfoT *strhash_data,
						LogSource2ResourceT *resinfo)
{
	gchar dupstr[SNMP_BC_MAX_SEL_ENTRY_LENGTH];
	Xml2EventInfoT *dupstr_hash_data;
	short strnum;

	strncpy(dupstr, search_str, SNMP_BC_MAX_SEL_ENTRY_LENGTH);
	dupstr_hash_data = strhash_data;
	strnum = strhash_data->event_dup + 1; /* Original string plus dups */
       
	while (strnum && (dupstr_hash_data != NULL)) {
		int i,j;
		gchar *normalized_event; 

		/* Search sensor array for the duplicate string's event */
		for (i=0; (resinfo->sensor_array_ptr + i)->sensor.Num != 0; i++) {
			for (j=0; (resinfo->sensor_array_ptr + i)->bc_sensor_info.event_array[j].event != NULL; j++) {
				normalized_event = snmp_derive_objid(resinfo->ep,
						   (resinfo->sensor_array_ptr + i)->bc_sensor_info.event_array[j].event);
				if (!strcmp(dupstr_hash_data->event, normalized_event)) {
					g_free(normalized_event);
					return dupstr_hash_data;
				}
				g_free(normalized_event);
			}
		}
		
		/* Search resource array for the duplicate string's event */
		for (i=0; snmp_rpt_array[resinfo->rpt].bc_res_info.event_array[i].event != NULL; i++) {
			normalized_event = snmp_derive_objid(resinfo->ep,
					   snmp_rpt_array[resinfo->rpt].bc_res_info.event_array[i].event);
			if (!strcmp(dupstr_hash_data->event, normalized_event)) {
				g_free(normalized_event);
				return dupstr_hash_data;
			}
			g_free(normalized_event);
		}

		/* Find next duplicate string */
		strnum--;
		if (strnum) {
			gchar strnum_str[OH_MAX_LOCATION_DIGITS];
			gchar *tmpstr;

			snprintf(strnum_str, OH_MAX_LOCATION_DIGITS, "%d", strnum);
			tmpstr = g_strconcat(search_str, HPIDUP_STRING, strnum_str, NULL);
			strncpy(dupstr, tmpstr, SNMP_BC_MAX_SEL_ENTRY_LENGTH);
			g_free(tmpstr);

                        /* FIXME Fix for RSA */
			dupstr_hash_data = (Xml2EventInfoT *)g_hash_table_lookup(bc_xml2event_hash, dupstr);
			if (dupstr_hash_data == NULL) {
				dbg("Cannot find duplicate string=%s.", dupstr);
			}
		}
	}

	return NULL;
}
Example #3
0
int
main (int argc, char **argv)
{
  GError *error;
  GHashTable *table;
  GHashTable *files;
  gchar *srcfile;
  gboolean show_version_and_exit = FALSE;
  gchar *target = NULL;
  gchar *binary_target = NULL;
  gboolean generate_automatic = FALSE;
  gboolean generate_source = FALSE;
  gboolean generate_header = FALSE;
  gboolean manual_register = FALSE;
  gboolean internal = FALSE;
  gboolean generate_dependencies = FALSE;
  gboolean generate_phony_targets = FALSE;
  char *dependency_file = NULL;
  char *c_name = NULL;
  char *c_name_no_underscores;
  const char *linkage = "extern";
  GOptionContext *context;
  GOptionEntry entries[] = {
    { "version", 0, 0, G_OPTION_ARG_NONE, &show_version_and_exit, N_("Show program version and exit"), NULL },
    { "target", 0, 0, G_OPTION_ARG_FILENAME, &target, N_("name of the output file"), N_("FILE") },
    { "sourcedir", 0, 0, G_OPTION_ARG_FILENAME_ARRAY, &sourcedirs, N_("The directories where files are to be read from (default to current directory)"), N_("DIRECTORY") },
    { "generate", 0, 0, G_OPTION_ARG_NONE, &generate_automatic, N_("Generate output in the format selected for by the target filename extension"), NULL },
    { "generate-header", 0, 0, G_OPTION_ARG_NONE, &generate_header, N_("Generate source header"), NULL },
    { "generate-source", 0, 0, G_OPTION_ARG_NONE, &generate_source, N_("Generate sourcecode used to link in the resource file into your code"), NULL },
    { "generate-dependencies", 0, 0, G_OPTION_ARG_NONE, &generate_dependencies, N_("Generate dependency list"), NULL },
    { "dependency-file", 0, 0, G_OPTION_ARG_FILENAME, &dependency_file, N_("name of the dependency file to generate"), N_("FILE") },
    { "generate-phony-targets", 0, 0, G_OPTION_ARG_NONE, &generate_phony_targets, N_("Include phony targets in the generated dependency file"), NULL },
    { "manual-register", 0, 0, G_OPTION_ARG_NONE, &manual_register, N_("Don’t automatically create and register resource"), NULL },
    { "internal", 0, 0, G_OPTION_ARG_NONE, &internal, N_("Don’t export functions; declare them G_GNUC_INTERNAL"), NULL },
    { "c-name", 0, 0, G_OPTION_ARG_STRING, &c_name, N_("C identifier name used for the generated source code"), NULL },
    { NULL }
  };

#ifdef G_OS_WIN32
  gchar *tmp;
#endif

  setlocale (LC_ALL, "");
  textdomain (GETTEXT_PACKAGE);

#ifdef G_OS_WIN32
  tmp = _glib_get_locale_dir ();
  bindtextdomain (GETTEXT_PACKAGE, tmp);
  g_free (tmp);
#else
  bindtextdomain (GETTEXT_PACKAGE, GLIB_LOCALE_DIR);
#endif

#ifdef HAVE_BIND_TEXTDOMAIN_CODESET
  bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");
#endif

  context = g_option_context_new (N_("FILE"));
  g_option_context_set_translation_domain (context, GETTEXT_PACKAGE);
  g_option_context_set_summary (context,
    N_("Compile a resource specification into a resource file.\n"
       "Resource specification files have the extension .gresource.xml,\n"
       "and the resource file have the extension called .gresource."));
  g_option_context_add_main_entries (context, entries, GETTEXT_PACKAGE);

  error = NULL;
  if (!g_option_context_parse (context, &argc, &argv, &error))
    {
      g_printerr ("%s\n", error->message);
      return 1;
    }

  g_option_context_free (context);

  if (show_version_and_exit)
    {
      g_print (PACKAGE_VERSION "\n");
      return 0;
    }

  if (argc != 2)
    {
      g_printerr (_("You should give exactly one file name\n"));
      g_free (c_name);
      return 1;
    }

  if (internal)
    linkage = "G_GNUC_INTERNAL";

  srcfile = argv[1];

  xmllint = g_strdup (g_getenv ("XMLLINT"));
  if (xmllint == NULL)
    xmllint = g_find_program_in_path ("xmllint");
  if (xmllint == NULL)
    g_printerr ("XMLLINT not set and xmllint not found in path; skipping xml preprocessing.\n");

  gdk_pixbuf_pixdata = g_strdup (g_getenv ("GDK_PIXBUF_PIXDATA"));
  if (gdk_pixbuf_pixdata == NULL)
    gdk_pixbuf_pixdata = g_find_program_in_path ("gdk-pixbuf-pixdata");

  if (target == NULL)
    {
      char *dirname = g_path_get_dirname (srcfile);
      char *base = g_path_get_basename (srcfile);
      char *target_basename;
      if (g_str_has_suffix (base, ".xml"))
	base[strlen(base) - strlen (".xml")] = 0;

      if (generate_source)
	{
	  if (g_str_has_suffix (base, ".gresource"))
	    base[strlen(base) - strlen (".gresource")] = 0;
	  target_basename = g_strconcat (base, ".c", NULL);
	}
      else if (generate_header)
        {
          if (g_str_has_suffix (base, ".gresource"))
            base[strlen(base) - strlen (".gresource")] = 0;
          target_basename = g_strconcat (base, ".h", NULL);
        }
      else
	{
	  if (g_str_has_suffix (base, ".gresource"))
	    target_basename = g_strdup (base);
	  else
	    target_basename = g_strconcat (base, ".gresource", NULL);
	}

      target = g_build_filename (dirname, target_basename, NULL);
      g_free (target_basename);
      g_free (dirname);
      g_free (base);
    }
  else if (generate_automatic)
    {
      if (extension_in_set (target, "c", "cc", "cpp", "cxx", "c++", NULL))
        generate_source = TRUE;
      else if (extension_in_set (target, "h", "hh", "hpp", "hxx", "h++", NULL))
        generate_header = TRUE;
      else if (extension_in_set (target, "gresource", NULL))
        { }
    }

  files = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, (GDestroyNotify)file_data_free);

  if ((table = parse_resource_file (srcfile, !generate_dependencies, files)) == NULL)
    {
      g_free (target);
      g_free (c_name);
      return 1;
    }

  /* This can be used in the same invocation
     as other generate commands */
  if (dependency_file != NULL)
    {
      /* Generate a .d file that describes the dependencies for
       * build tools, gcc -M -MF style */
      GString *dep_string;
      GHashTableIter iter;
      gpointer key, data;
      FileData *file_data;
      char *escaped;

      g_hash_table_iter_init (&iter, files);

      dep_string = g_string_new (NULL);
      escaped = escape_makefile_string (srcfile);
      g_string_printf (dep_string, "%s:", escaped);
      g_free (escaped);

      /* First rule: foo.xml: resource1 resource2.. */
      while (g_hash_table_iter_next (&iter, &key, &data))
        {
          file_data = data;
          if (!g_str_equal (file_data->filename, srcfile))
            {
              escaped = escape_makefile_string (file_data->filename);
              g_string_append_printf (dep_string, " %s", escaped);
              g_free (escaped);
            }
        }

      g_string_append (dep_string, "\n");

      /* Optionally include phony targets as it silences `make` but
       * isn't supported on `ninja` at the moment. See also: `gcc -MP`
       */
      if (generate_phony_targets)
        {
					g_string_append (dep_string, "\n");

          /* One rule for every resource: resourceN: */
          g_hash_table_iter_init (&iter, files);
          while (g_hash_table_iter_next (&iter, &key, &data))
            {
              file_data = data;
              if (!g_str_equal (file_data->filename, srcfile))
                {
                  escaped = escape_makefile_string (file_data->filename);
                  g_string_append_printf (dep_string, "%s:\n\n", escaped);
                  g_free (escaped);
                }
            }
        }

      if (g_str_equal (dependency_file, "-"))
        {
          g_print ("%s\n", dep_string->str);
        }
      else
        {
          if (!g_file_set_contents (dependency_file, dep_string->str, dep_string->len, &error))
            {
              g_printerr ("Error writing dependency file: %s\n", error->message);
              g_string_free (dep_string, TRUE);
              g_free (dependency_file);
              g_error_free (error);
              return 1;
            }
        }

      g_string_free (dep_string, TRUE);
      g_free (dependency_file);
    }

  if (generate_dependencies)
    {
      GHashTableIter iter;
      gpointer key, data;
      FileData *file_data;

      g_hash_table_iter_init (&iter, files);

      /* Generate list of files for direct use as dependencies in a Makefile */
      while (g_hash_table_iter_next (&iter, &key, &data))
        {
          file_data = data;
          g_print ("%s\n", file_data->filename);
        }
    }
  else if (generate_source || generate_header)
    {
      if (generate_source)
	{
	  int fd = g_file_open_tmp (NULL, &binary_target, NULL);
	  if (fd == -1)
	    {
	      g_printerr ("Can't open temp file\n");
	      g_free (c_name);
	      return 1;
	    }
	  close (fd);
	}

      if (c_name == NULL)
	{
	  char *base = g_path_get_basename (srcfile);
	  GString *s;
	  char *dot;
	  int i;

	  /* Remove extensions */
	  dot = strchr (base, '.');
	  if (dot)
	    *dot = 0;

	  s = g_string_new ("");

	  for (i = 0; base[i] != 0; i++)
	    {
	      const char *first = G_CSET_A_2_Z G_CSET_a_2_z "_";
	      const char *rest = G_CSET_A_2_Z G_CSET_a_2_z G_CSET_DIGITS "_";
	      if (strchr ((i == 0) ? first : rest, base[i]) != NULL)
		g_string_append_c (s, base[i]);
	      else if (base[i] == '-')
		g_string_append_c (s, '_');

	    }

	  c_name = g_string_free (s, FALSE);
	}
    }
  else
    binary_target = g_strdup (target);

  c_name_no_underscores = c_name;
  while (c_name_no_underscores && *c_name_no_underscores == '_')
    c_name_no_underscores++;

  if (binary_target != NULL &&
      !write_to_file (table, binary_target, &error))
    {
      g_printerr ("%s\n", error->message);
      g_free (target);
      g_free (c_name);
      return 1;
    }

  if (generate_header)
    {
      FILE *file;

      file = fopen (target, "w");
      if (file == NULL)
	{
	  g_printerr ("can't write to file %s", target);
	  g_free (c_name);
	  return 1;
	}

      fprintf (file,
	       "#ifndef __RESOURCE_%s_H__\n"
	       "#define __RESOURCE_%s_H__\n"
	       "\n"
	       "#include <gio/gio.h>\n"
	       "\n"
	       "%s GResource *%s_get_resource (void);\n",
	       c_name, c_name, linkage, c_name);

      if (manual_register)
	fprintf (file,
		 "\n"
		 "%s void %s_register_resource (void);\n"
		 "%s void %s_unregister_resource (void);\n"
		 "\n",
		 linkage, c_name, linkage, c_name);

      fprintf (file,
	       "#endif\n");

      fclose (file);
    }
  else if (generate_source)
    {
      FILE *file;
      guint8 *data;
      gsize data_size;
      gsize i;

      if (!g_file_get_contents (binary_target, (char **)&data,
				&data_size, NULL))
	{
	  g_printerr ("can't read back temporary file");
	  g_free (c_name);
	  return 1;
	}
      g_unlink (binary_target);

      file = fopen (target, "w");
      if (file == NULL)
	{
	  g_printerr ("can't write to file %s", target);
	  g_free (c_name);
	  return 1;
	}

      fprintf (file,
	       "#include <gio/gio.h>\n"
	       "\n"
	       "#if defined (__ELF__) && ( __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 6))\n"
	       "# define SECTION __attribute__ ((section (\".gresource.%s\"), aligned (8)))\n"
	       "#else\n"
	       "# define SECTION\n"
	       "#endif\n"
	       "\n"
	       "static const SECTION union { const guint8 data[%"G_GSIZE_FORMAT"]; const double alignment; void * const ptr;}  %s_resource_data = { {\n",
	       c_name_no_underscores, data_size, c_name);

      for (i = 0; i < data_size; i++) {
	if (i % 8 == 0)
	  fprintf (file, "  ");
	fprintf (file, "0x%2.2x", (int)data[i]);
	if (i != data_size - 1)
	  fprintf (file, ", ");
	if ((i % 8 == 7) || (i == data_size - 1))
	  fprintf (file, "\n");
      }

      fprintf (file, "} };\n");

      fprintf (file,
	       "\n"
	       "static GStaticResource static_resource = { %s_resource_data.data, sizeof (%s_resource_data.data), NULL, NULL, NULL };\n"
	       "%s GResource *%s_get_resource (void);\n"
	       "GResource *%s_get_resource (void)\n"
	       "{\n"
	       "  return g_static_resource_get_resource (&static_resource);\n"
	       "}\n",
	       c_name, c_name, linkage, c_name, c_name);


      if (manual_register)
	{
	  fprintf (file,
		   "\n"
		   "%s void %s_unregister_resource (void);\n"
		   "void %s_unregister_resource (void)\n"
		   "{\n"
		   "  g_static_resource_fini (&static_resource);\n"
		   "}\n"
		   "\n"
		   "%s void %s_register_resource (void);\n"
		   "void %s_register_resource (void)\n"
		   "{\n"
		   "  g_static_resource_init (&static_resource);\n"
		   "}\n",
		   linkage, c_name, c_name, linkage, c_name, c_name);
	}
      else
	{
	  fprintf (file, "%s", gconstructor_code);
	  fprintf (file,
		   "\n"
		   "#ifdef G_HAS_CONSTRUCTORS\n"
		   "\n"
		   "#ifdef G_DEFINE_CONSTRUCTOR_NEEDS_PRAGMA\n"
		   "#pragma G_DEFINE_CONSTRUCTOR_PRAGMA_ARGS(resource_constructor)\n"
		   "#endif\n"
		   "G_DEFINE_CONSTRUCTOR(resource_constructor)\n"
		   "#ifdef G_DEFINE_DESTRUCTOR_NEEDS_PRAGMA\n"
		   "#pragma G_DEFINE_DESTRUCTOR_PRAGMA_ARGS(resource_destructor)\n"
		   "#endif\n"
		   "G_DEFINE_DESTRUCTOR(resource_destructor)\n"
		   "\n"
		   "#else\n"
		   "#warning \"Constructor not supported on this compiler, linking in resources will not work\"\n"
		   "#endif\n"
		   "\n"
		   "static void resource_constructor (void)\n"
		   "{\n"
		   "  g_static_resource_init (&static_resource);\n"
		   "}\n"
		   "\n"
		   "static void resource_destructor (void)\n"
		   "{\n"
		   "  g_static_resource_fini (&static_resource);\n"
		   "}\n");
	}

      fclose (file);

      g_free (data);
    }

  g_free (binary_target);
  g_free (target);
  g_hash_table_destroy (table);
  g_free (xmllint);
  g_free (c_name);

  return 0;
}
Example #4
0
G_MODULE_EXPORT gboolean
display_show(NOTIFICATION_INFO* ni) {

  DISPLAY_INFO* di = g_new0(DISPLAY_INFO, 1);
  if (!di) {
    perror("g_new0");
    return FALSE;
  }
  di->ni = ni;

  notifications = g_list_append(notifications, di);

  di->popup = gtk_window_new(GTK_WINDOW_POPUP);
  gtk_window_set_title(GTK_WINDOW(di->popup), "growl-for-linux");
  gtk_window_set_resizable(GTK_WINDOW(di->popup), TRUE);
  gtk_window_set_decorated(GTK_WINDOW(di->popup), FALSE);
  gtk_window_set_keep_above(GTK_WINDOW(di->popup), TRUE);

  gtk_widget_modify_bg(di->popup, GTK_STATE_NORMAL, colors + (rand() % lengthof(available_colors)));

  gtk_window_stick(GTK_WINDOW(di->popup));

  GtkWidget* ebox = gtk_event_box_new();
  gtk_event_box_set_visible_window(GTK_EVENT_BOX(ebox), FALSE);
  gtk_container_add(GTK_CONTAINER(di->popup), ebox);

  GtkWidget* fixed = gtk_fixed_new();
  gtk_container_set_border_width(GTK_CONTAINER(fixed), 0);
  gtk_container_add(GTK_CONTAINER(ebox), fixed);

  GtkWidget* image = NULL;
  if (di->ni->icon && *di->ni->icon) {
    GdkPixbuf* pixbuf;
    if (di->ni->local) {
      gchar* newurl = g_filename_from_uri(di->ni->icon, NULL, NULL);
      GError* error = NULL;
      pixbuf = gdk_pixbuf_new_from_file(newurl ? newurl : di->ni->icon, &error);
      g_free(newurl);
    } else {
      pixbuf = pixbuf_from_url(di->ni->icon, NULL);
    }

    if (pixbuf) {
      GdkPixbuf* tmp = gdk_pixbuf_scale_simple(pixbuf, 32, 32, GDK_INTERP_TILES);
      if (tmp) {
        g_object_unref(pixbuf);
        pixbuf = tmp;
      }
      image = gtk_image_new_from_pixbuf(pixbuf);
      gtk_container_add(GTK_CONTAINER(fixed), image);
      g_object_unref(pixbuf);
    }
  }

  PangoContext* context = gtk_widget_get_pango_context(di->popup) ;
  PangoLayout* layout = pango_layout_new(context);

  gchar* text = g_strconcat(di->ni->title, "\n", di->ni->text, NULL);
  pango_layout_set_text(layout, text, -1);
  g_free(text);
  pango_layout_set_font_description(layout, font_sans20_desc);
  pango_layout_get_pixel_size(layout, &di->width, &di->height);

  di->x = screen_rect.width;
  di->y = screen_rect.y + rand() % (screen_rect.height - di->height);
  di->width += 32 + 5;

  if (image)
    gtk_fixed_move(GTK_FIXED(fixed), image, 0, di->height / 2 - 16);
  GdkBitmap* bitmap = gdk_pixmap_new(di->popup->window, di->width, di->height, 1);
  GdkGC *gc = gdk_gc_new(GDK_DRAWABLE(bitmap));
  GdkColormap* colormap = gdk_colormap_get_system();
  gdk_gc_set_colormap(gc, colormap);

  gdk_colormap_alloc_color(colormap, color_black, TRUE, TRUE);
  gdk_gc_set_foreground (gc, color_black);
  gdk_draw_rectangle(bitmap, gc, TRUE, 0, 0, di->width, di->height);

  gdk_colormap_alloc_color(colormap, color_white, TRUE, TRUE);
  gdk_gc_set_foreground (gc, color_white);
  if (image)
    gdk_draw_rectangle(bitmap, gc, TRUE, 0, di->height / 2 - 16, 32, 32);
  gdk_draw_layout(bitmap, gc, 32 + 5, 0, layout);

  g_signal_connect(G_OBJECT(ebox), "button-press-event", G_CALLBACK(display_clicked), di);
  g_signal_connect(G_OBJECT(ebox), "enter-notify-event", G_CALLBACK(display_enter), di);
  g_signal_connect(G_OBJECT(ebox), "leave-notify-event", G_CALLBACK(display_leave), di);

  gtk_window_move(GTK_WINDOW(di->popup), di->x, di->y);
  gtk_widget_show_all(di->popup);

  gtk_widget_set_size_request(fixed, di->width, di->height);
  gdk_window_set_back_pixmap(di->popup->window, NULL, FALSE);
  gdk_window_shape_combine_mask(di->popup->window, bitmap, 0, 0);

  g_object_unref(gc);
  g_object_unref(layout);
  g_object_unref(context);
  g_object_unref(bitmap);

  g_object_ref(di->popup);
  g_timeout_add(100, display_animation_func, di);

  return FALSE;
}
GtkWidget* ctk_display_device_new(NvCtrlAttributeHandle *handle,
                                  CtkConfig *ctk_config,
                                  CtkEvent *ctk_event,
                                  CtkEvent *ctk_event_gpu,
                                  char *name,
                                  char *typeBaseName,
                                  ParsedAttribute *p)
{
    GObject *object;
    CtkDisplayDevice *ctk_object;
    GtkWidget *banner;
    GtkWidget *hbox, *tmpbox;

    GtkWidget *alignment;
    GtkWidget *notebook;
    GtkWidget *nbox;
    GtkWidget *align;
    GtkWidget *label;
    GtkWidget *hseparator;
    GtkWidget *button;
    gchar *str;
    int i;

    object = g_object_new(CTK_TYPE_DISPLAY_DEVICE, NULL);
    if (!object) return NULL;

    ctk_object = CTK_DISPLAY_DEVICE(object);
    ctk_object->handle = handle;
    ctk_object->ctk_event = ctk_event;
    ctk_object->ctk_event_gpu = ctk_event_gpu;
    ctk_object->ctk_config = ctk_config;
    ctk_object->name = g_strdup(name);
    ctk_object->color_correction_available = FALSE;

    gtk_box_set_spacing(GTK_BOX(object), 10);

    /* Banner */

    if (strcmp(typeBaseName, "CRT") == 0) {
        banner = ctk_banner_image_new(BANNER_ARTWORK_CRT);
    } else {
        banner = ctk_banner_image_new(BANNER_ARTWORK_DFP);
    }
    gtk_box_pack_start(GTK_BOX(object), banner, FALSE, FALSE, 0);

    /* Create tabbed notebook for widget */

    notebook = gtk_notebook_new();
    gtk_notebook_set_tab_pos(GTK_NOTEBOOK(notebook), GTK_POS_TOP);
    gtk_box_pack_start(GTK_BOX(object), notebook, TRUE, TRUE, 0);

    /* Create first tab for device info */

    nbox = gtk_vbox_new(FALSE, FRAME_PADDING);
    gtk_container_set_border_width(GTK_CONTAINER(nbox), FRAME_PADDING);
    gtk_notebook_append_page(GTK_NOTEBOOK(notebook), nbox,
                             gtk_label_new("Information"));


    /* Device info */

    hbox = gtk_hbox_new(FALSE, 0);
    gtk_box_pack_start(GTK_BOX(nbox), hbox, FALSE, FALSE, 0);

    label = gtk_label_new("Display Device Information");
    gtk_box_pack_start(GTK_BOX(hbox), label, FALSE, FALSE, 0);

    hseparator = gtk_hseparator_new();
    gtk_box_pack_start(GTK_BOX(hbox), hseparator, TRUE, TRUE, 5);


    /* create the hbox to store device info */

    hbox = gtk_hbox_new(FALSE, FRAME_PADDING);
    gtk_box_pack_start(GTK_BOX(nbox), hbox, FALSE, FALSE, FRAME_PADDING);

    /*
     * insert a vbox between the frame and the widgets, so that the
     * widgets don't expand to fill all of the space within the
     * frame
     */

    tmpbox = gtk_vbox_new(FALSE, FRAME_PADDING);
    gtk_container_set_border_width(GTK_CONTAINER(tmpbox), FRAME_PADDING);
    gtk_container_add(GTK_CONTAINER(hbox), tmpbox);

    /* Create and add the information widgets */

    ctk_object->num_info_entries = ARRAY_LEN(__info_entry_data);
    ctk_object->info_entries = calloc(ctk_object->num_info_entries,
                                      sizeof(InfoEntry));
    if (!ctk_object->info_entries) {
        ctk_object->num_info_entries = 0;
    }

    for (i = 0; i < ctk_object->num_info_entries; i++) {
        InfoEntryData *entryData = __info_entry_data+i;
        InfoEntry *entry = ctk_object->info_entries+i;
        gchar *str;

        entry->ctk_object = ctk_object;
        str = g_strconcat(entryData->str, ":", NULL);
        entry->label = gtk_label_new(str);
        g_free(str);

        entry->txt = gtk_label_new("");

        gtk_misc_set_alignment(GTK_MISC(entry->label), 0.0f, 0.5f);
        gtk_misc_set_alignment(GTK_MISC(entry->txt), 0.0f, 0.5f);

        ctk_config_set_tooltip(ctk_config,
                               entry->label,
                               *(entryData->tooltip));
        ctk_config_set_tooltip(ctk_config,
                               entry->txt,
                               *(entryData->tooltip));

        entry->hbox = gtk_hbox_new(FALSE, FRAME_PADDING);
        gtk_box_pack_start(GTK_BOX(entry->hbox), entry->label,
                           FALSE, TRUE, FRAME_PADDING);
        gtk_box_pack_start(GTK_BOX(entry->hbox), entry->txt,
                           FALSE, TRUE, FRAME_PADDING);

        gtk_box_pack_start(GTK_BOX(tmpbox), entry->hbox, FALSE, FALSE, 0);
    }

    /* pack the EDID button */

    ctk_object->edid = ctk_edid_new(ctk_object->handle,
                                    ctk_object->ctk_config,
                                    ctk_object->ctk_event,
                                    ctk_object->name);

    hbox = gtk_hbox_new(FALSE, 0);
    align = gtk_alignment_new(0, 1, 1, 1);
    gtk_container_add(GTK_CONTAINER(align), hbox);
    gtk_box_pack_end(GTK_BOX(nbox), align, FALSE, FALSE, 0);
    gtk_box_pack_start(GTK_BOX(hbox), ctk_object->edid, TRUE, TRUE, 0);

    /*
     * Create layout for second tab for controls but don't add the tab until we
     * make sure it's required
     */

    nbox = gtk_vbox_new(FALSE, FRAME_PADDING);
    gtk_container_set_border_width(GTK_CONTAINER(nbox), FRAME_PADDING);

    /* pack the reset button */

    button = gtk_button_new_with_label("Reset Hardware Defaults");
    str = ctk_help_create_reset_hardware_defaults_text(typeBaseName,
                                                       name);
    ctk_config_set_tooltip(ctk_config, button, str);
    ctk_object->reset_button = button;

    alignment = gtk_alignment_new(1, 1, 0, 0);
    gtk_container_add(GTK_CONTAINER(alignment), button);
    gtk_box_pack_end(GTK_BOX(nbox), alignment, FALSE, FALSE, 0);

    /* pack the color controls */

    ctk_object->color_controls =
        ctk_color_controls_new(handle, ctk_config, ctk_event,
                               ctk_object->reset_button, name);

    if (ctk_object->color_controls) {
        gtk_box_pack_start(GTK_BOX(nbox), ctk_object->color_controls,
                           FALSE, FALSE, 0);
    }

    /* pack the dithering controls */

    ctk_object->dithering_controls =
        ctk_dithering_controls_new(handle, ctk_config, ctk_event,
                                   ctk_object->reset_button, name);

    if (ctk_object->dithering_controls) {
        gtk_box_pack_start(GTK_BOX(nbox), ctk_object->dithering_controls,
                           FALSE, FALSE, 0);
    }

    /* pack the image sliders */

    ctk_object->image_sliders =
        ctk_image_sliders_new(handle, ctk_config, ctk_event,
                              ctk_object->reset_button, name);
    if (ctk_object->image_sliders) {
        gtk_box_pack_start(GTK_BOX(nbox), ctk_object->image_sliders,
                           FALSE, FALSE, 0);
    }

    /* If no controls are created, don't add a controls tab */

    if (ctk_object->color_controls ||
        ctk_object->dithering_controls ||
        ctk_object->image_sliders) {
        gtk_notebook_append_page(GTK_NOTEBOOK(notebook), nbox,
                                 gtk_label_new("Controls"));
    }

    /*
     * Show all widgets on this page so far. After this, the color correction
     * tab and other widgets can control their own visibility.
     */

    gtk_widget_show_all(GTK_WIDGET(object));

    /* add the color correction tab if RandR is available */

    add_color_correction_tab(ctk_object, ctk_config, ctk_event, notebook, p);

    /* Update the GUI */

    display_device_setup(ctk_object);

    /* Listen to events */

    g_signal_connect(G_OBJECT(ctk_object->reset_button),
                     "clicked", G_CALLBACK(reset_button_clicked),
                     (gpointer) ctk_object);

    g_signal_connect(G_OBJECT(ctk_event_gpu),
                     CTK_EVENT_NAME(NV_CTRL_ENABLED_DISPLAYS),
                     G_CALLBACK(enabled_displays_received),
                     (gpointer) ctk_object);

    for (i = 0; i < ctk_object->num_info_entries; i++) {
        InfoEntryData *entryData = __info_entry_data+i;
        InfoEntry *entry = ctk_object->info_entries+i;

        if (entryData->register_events_func) {
            entryData->register_events_func(entry);
        }
    }

    return GTK_WIDGET(object);

} /* ctk_display_device_new() */
Example #6
0
static void
menubar_open_mod_cb  (GtkWidget *widget, gpointer data)
{
    gchar *modnam = NULL;
    gchar *modfile;
    gchar *confdir;
    GtkWidget *module = NULL;


    sat_log_log (SAT_LOG_LEVEL_DEBUG,
                 _("%s: Open existing module..."),
                 __FUNCTION__);
    
    modnam = select_module ();

    if (modnam) {
        sat_log_log (SAT_LOG_LEVEL_DEBUG,
                     _("%s: Open module %s."),
                     __FUNCTION__, modnam);

        confdir = get_modules_dir ();
        modfile = g_strconcat (confdir, G_DIR_SEPARATOR_S,
                               modnam, ".mod", NULL);
        g_free (confdir);

        /* create new module */
        module = gtk_sat_module_new (modfile);

        if (module == NULL) {
            /* mod manager could not create the module */
            GtkWidget *dialog;

            dialog = gtk_message_dialog_new (GTK_WINDOW (app),
                                             GTK_DIALOG_MODAL |
                                             GTK_DIALOG_DESTROY_WITH_PARENT,
                                             GTK_MESSAGE_ERROR,
                                             GTK_BUTTONS_OK,
                                             _("Could not open %s. Please examine "\
                                               "the log messages for details."),
                                             modnam);

            gtk_dialog_run (GTK_DIALOG (dialog));
            gtk_widget_destroy (dialog);
        }
        else {

            /* if module state was window or user does not want to restore the
               state of the modules, pack the module into the notebook */
            if ((GTK_SAT_MODULE (module)->state == GTK_SAT_MOD_STATE_DOCKED) ||
                !sat_cfg_get_bool (SAT_CFG_BOOL_MOD_STATE)) {
                
                mod_mgr_add_module (module, TRUE);
                
            }
            else {
                mod_mgr_add_module (module, FALSE);
                create_module_window (module);
            }
        }

        g_free (modnam);
        g_free (modfile);
    }
    else {
        sat_log_log (SAT_LOG_LEVEL_DEBUG,
                     _("%s: Open module cancelled."),
                     __FUNCTION__);
    }
}
Example #7
0
gboolean
download_cb(WebKitWebView *web_view, WebKitDownload *download, gpointer user_data) {
    (void) web_view; (void) user_data;

    /* get the URI being downloaded */
    const gchar *uri = webkit_download_get_uri(download);

    /* get the destination path, if specified.
     * this is only intended to be set when this function is trigger by an
     * explicit download using uzbl's 'download' action. */
    const gchar *destination = user_data;

    if (uzbl.state.verbose)
        printf("Download requested -> %s\n", uri);

    if (!uzbl.behave.download_handler) {
        webkit_download_cancel(download);
        return FALSE; /* reject downloads when there's no download handler */
    }

    /* get a reasonable suggestion for a filename */
    const gchar *suggested_filename;
    g_object_get(download, "suggested-filename", &suggested_filename, NULL);

    /* get the mimetype of the download */
    const gchar *content_type = NULL;
    WebKitNetworkResponse *r  = webkit_download_get_network_response(download);
    /* downloads can be initiated from the context menu, in that case there is
       no network response yet and trying to get one would crash. */
    if(WEBKIT_IS_NETWORK_RESPONSE(r)) {
        SoupMessage        *m = webkit_network_response_get_message(r);
        SoupMessageHeaders *h = NULL;
        g_object_get(m, "response-headers", &h, NULL);
        if(h) /* some versions of libsoup don't have "response-headers" here */
            content_type = soup_message_headers_get_one(h, "Content-Type");
    }

    if(!content_type)
        content_type = "application/octet-stream";

    /* get the filesize of the download, as given by the server.
       (this may be inaccurate, there's nothing we can do about that.)  */
    unsigned int total_size = webkit_download_get_total_size(download);

    GArray *a = g_array_new (TRUE, FALSE, sizeof(gchar*));
    const CommandInfo *c = parse_command_parts(uzbl.behave.download_handler, a);
    if(!c) {
        webkit_download_cancel(download);
        g_array_free(a, TRUE);
        return FALSE;
    }

    g_array_append_val(a, uri);
    g_array_append_val(a, suggested_filename);
    g_array_append_val(a, content_type);
    gchar *total_size_s = g_strdup_printf("%d", total_size);
    g_array_append_val(a, total_size_s);

    if(destination)
        g_array_append_val(a, destination);

    GString *result = g_string_new ("");
    run_parsed_command(c, a, result);

    g_free(total_size_s);
    g_array_free(a, TRUE);

    /* no response, cancel the download */
    if(result->len == 0) {
        webkit_download_cancel(download);
        return FALSE;
    }

    /* we got a response, it's the path we should download the file to */
    gchar *destination_path = result->str;
    g_string_free(result, FALSE);

    /* presumably people don't need newlines in their filenames. */
    char *p = strchr(destination_path, '\n');
    if ( p != NULL ) *p = '\0';

    /* set up progress callbacks */
    g_signal_connect(download, "notify::status",   G_CALLBACK(download_status_cb),   NULL);
    g_signal_connect(download, "notify::progress", G_CALLBACK(download_progress_cb), NULL);

    /* convert relative path to absolute path */
    if(destination_path[0] != '/') {
        gchar *rel_path = destination_path;
        gchar *cwd = g_get_current_dir();
        destination_path = g_strconcat(cwd, "/", destination_path, NULL);
        g_free(cwd);
        g_free(rel_path);
    }

    send_event(DOWNLOAD_STARTED, NULL, TYPE_STR, destination_path, NULL);

    /* convert absolute path to file:// URI */
    gchar *destination_uri = g_strconcat("file://", destination_path, NULL);
    g_free(destination_path);

    webkit_download_set_destination_uri(download, destination_uri);
    g_free(destination_uri);

    return TRUE;
}
static gboolean
open_library (GstRealAudioDec * dec, gint version, GstRADecLibrary * lib)
{
  const gchar *path, *names;
  gchar **split_names, **split_path;
  gint i, j;
  gpointer ra_close_codec, ra_decode, ra_free_decoder;
  gpointer ra_open_codec2, ra_init_decoder, ra_set_flavor;
  gpointer set_dll_access_path = NULL, ra_set_pwd = NULL;
  gchar *tmppath = NULL;
  guint16 res = 0;

  path = dec->real_codecs_path ? dec->real_codecs_path :
      DEFAULT_REAL_CODECS_PATH;

  switch (version) {
    case GST_REAL_AUDIO_DEC_VERSION_COOK:
      names = dec->racook_names ? dec->racook_names : DEFAULT_RACOOK_NAMES;
      break;
    case GST_REAL_AUDIO_DEC_VERSION_ATRK:
      names = dec->raatrk_names ? dec->raatrk_names : DEFAULT_RAATRK_NAMES;
      break;
    case GST_REAL_AUDIO_DEC_VERSION_14_4:
      names = dec->ra14_4_names ? dec->ra14_4_names : DEFAULT_RA14_4_NAMES;
      break;
    case GST_REAL_AUDIO_DEC_VERSION_28_8:
      names = dec->ra28_8_names ? dec->ra28_8_names : DEFAULT_RA28_8_NAMES;
      break;
    case GST_REAL_AUDIO_DEC_VERSION_SIPR:
      names = dec->rasipr_names ? dec->rasipr_names : DEFAULT_RASIPR_NAMES;
      break;
    default:
      goto unknown_version;
  }

  GST_LOG_OBJECT (dec, "splitting paths %s, names %s", path, names);

  split_path = g_strsplit (path, ":", 0);
  split_names = g_strsplit (names, ":", 0);

  for (i = 0; split_path[i]; i++) {
    for (j = 0; split_names[j]; j++) {
      gchar *codec = g_strconcat (split_path[i], "/", split_names[j], NULL);

      GST_LOG_OBJECT (dec, "opening module %s", codec);

      /* This is racy, but it doesn't matter here; would be nice if GModule
       * gave us a GError instead of an error string, but it doesn't, so.. */
      if (g_file_test (codec, G_FILE_TEST_EXISTS)) {
        lib->module = g_module_open (codec, G_MODULE_BIND_LAZY);
        if (lib->module == NULL) {
          GST_ERROR_OBJECT (dec, "Could not open codec library '%s': %s",
              codec, g_module_error ());
        }
      } else {
        GST_DEBUG_OBJECT (dec, "%s does not exist", codec);
      }
      g_free (codec);
      if (lib->module)
        goto codec_search_done;
    }
  }

codec_search_done:
  /* we keep the path for a while to set the dll access path */
  g_strfreev (split_names);

  if (lib->module == NULL)
    goto could_not_open;

  GST_LOG_OBJECT (dec, "finding symbols");

  if (!g_module_symbol (lib->module, "RACloseCodec", &ra_close_codec) ||
      !g_module_symbol (lib->module, "RADecode", &ra_decode) ||
      !g_module_symbol (lib->module, "RAFreeDecoder", &ra_free_decoder) ||
      !g_module_symbol (lib->module, "RAOpenCodec2", &ra_open_codec2) ||
      !g_module_symbol (lib->module, "RAInitDecoder", &ra_init_decoder) ||
      !g_module_symbol (lib->module, "RASetFlavor", &ra_set_flavor)) {
    goto could_not_load;
  }

  g_module_symbol (lib->module, "RASetPwd", &ra_set_pwd);
  g_module_symbol (lib->module, "SetDLLAccessPath", &set_dll_access_path);

  lib->RACloseCodec = (guint16 (*)(gpointer)) ra_close_codec;
  lib->RADecode =
      (guint16 (*)(gpointer, guint8 *, guint32, guint8 *, guint32 *, guint32))
      ra_decode;
  lib->RAFreeDecoder = (guint16 (*)(gpointer)) ra_free_decoder;
  lib->RAOpenCodec2 = (guint16 (*)(gpointer, const gchar *)) ra_open_codec2;
  lib->RAInitDecoder = (guint16 (*)(gpointer, gpointer)) ra_init_decoder;
  lib->RASetFlavor = (guint16 (*)(gpointer, guint16)) ra_set_flavor;
  lib->RASetPwd = (void (*)(gpointer, const gchar *)) ra_set_pwd;
  lib->SetDLLAccessPath = (void (*)(gchar *)) set_dll_access_path;

  if (lib->SetDLLAccessPath)
    lib->SetDLLAccessPath (split_path[i]);

  tmppath = g_strdup_printf ("%s/", split_path[i]);
  if ((res = lib->RAOpenCodec2 (&lib->context, tmppath))) {
    g_free (tmppath);
    goto could_not_initialize;
  }
  g_free (tmppath);

  /* now we are done with the split paths, so free them */
  g_strfreev (split_path);

  return TRUE;

  /* ERRORS */
unknown_version:
  {
    GST_DEBUG_OBJECT (dec, "Cannot handle version %i.", version);
    return FALSE;
  }
could_not_open:
  {
    g_strfreev (split_path);
    GST_DEBUG_OBJECT (dec, "Could not find library '%s' in '%s'", names, path);
    return FALSE;
  }
could_not_load:
  {
    g_strfreev (split_path);
    close_library (dec, lib);
    GST_DEBUG_OBJECT (dec, "Could not load all symbols: %s", g_module_error ());
    return FALSE;
  }
could_not_initialize:
  {
    close_library (dec, lib);
    GST_WARNING_OBJECT (dec, "Initialization of REAL driver failed (%i).", res);
    return FALSE;
  }
}
Example #9
0
        /*
         * Initialize the given notification and add it to
         * the queue. Replace notification with id if id > 0.
         */
int notification_init(notification * n, int id)
{

        if (n == NULL)
                return -1;

        if (strcmp("DUNST_COMMAND_PAUSE", n->summary) == 0) {
                pause_display = true;
                return 0;
        }

        if (strcmp("DUNST_COMMAND_RESUME", n->summary) == 0) {
                pause_display = false;
                return 0;
        }

        n->script = NULL;
        n->text_to_render = NULL;

        n->format = settings.format;

        rule_apply_all(n);

        n->urls = notification_extract_markup_urls(&(n->body));

        n->msg = string_replace("%a", n->appname, g_strdup(n->format));
        n->msg = string_replace("%s", n->summary, n->msg);
        if (n->icon) {
                n->msg = string_replace("%I", basename(n->icon), n->msg);
                n->msg = string_replace("%i", n->icon, n->msg);
        }
        n->msg = string_replace("%b", n->body, n->msg);
        if (n->progress) {
                char pg[10];
                sprintf(pg, "[%3d%%]", n->progress - 1);
                n->msg = string_replace("%p", pg, n->msg);
        } else {
                n->msg = string_replace("%p", "", n->msg);
        }

        if (!settings.allow_markup)
                n->msg = notification_fix_markup(n->msg);
        else if (!settings.ignore_newline) {
                n->msg = string_replace("<br>", "\n", n->msg);
                n->msg = string_replace("<br />", "\n", n->msg);
        }

        while (strstr(n->msg, "\\n") != NULL)
                n->msg = string_replace("\\n", "\n", n->msg);

        if (settings.ignore_newline)
                while (strstr(n->msg, "\n") != NULL)
                        n->msg = string_replace("\n", " ", n->msg);

        n->msg = g_strstrip(n->msg);

        n->dup_count = 0;

        /* check if n is a duplicate */
        for (GList * iter = g_queue_peek_head_link(queue); iter;
             iter = iter->next) {
                notification *orig = iter->data;
                if (strcmp(orig->appname, n->appname) == 0
                    && strcmp(orig->summary, n->summary) == 0
                    && strcmp(orig->body, n->body) == 0) {
                        /* If the progress differs this was probably intended to replace the notification
                         * but notify-send was used. So don't increment dup_count in this case
                         */
                        if (orig->progress == n->progress) {
                                orig->dup_count++;
                        } else {
                                orig->progress = n->progress;
                        }
                        /* notifications that differ only in progress hints should be expected equal,
                         * but we want the latest message, with the latest hint value
                         */
                        free(orig->msg);
                        orig->msg = strdup(n->msg);
                        notification_free(n);
                        wake_up();
                        return orig->id;
                }
        }

        for (GList * iter = g_queue_peek_head_link(displayed); iter;
             iter = iter->next) {
                notification *orig = iter->data;
                if (strcmp(orig->appname, n->appname) == 0
                    && strcmp(orig->summary, n->summary) == 0
                    && strcmp(orig->body, n->body) == 0) {
                        /* notifications that differ only in progress hints should be expected equal,
                         * but we want the latest message, with the latest hint value
                         */
                        free(orig->msg);
                        orig->msg = strdup(n->msg);
                        /* If the progress differs this was probably intended to replace the notification
                         * but notify-send was used. So don't increment dup_count in this case
                         */
                        if (orig->progress == n->progress) {
                                orig->dup_count++;
                        } else {
                                orig->progress = n->progress;
                        }
                        orig->start = time(NULL);
                        notification_free(n);
                        wake_up();
                        return orig->id;
                }
        }

        /* urgency > CRIT -> array out of range */
        n->urgency = n->urgency > CRIT ? CRIT : n->urgency;

        if (!n->color_strings[ColFG]) {
                n->color_strings[ColFG] = xctx.color_strings[ColFG][n->urgency];
        }

        if (!n->color_strings[ColBG]) {
                n->color_strings[ColBG] = xctx.color_strings[ColBG][n->urgency];
        }

        n->timeout =
            n->timeout == -1 ? settings.timeouts[n->urgency] : n->timeout;
        n->start = 0;

        n->timestamp = time(NULL);

        n->redisplayed = false;

        n->first_render = true;

        if (id == 0) {
                n->id = ++next_notification_id;
        } else {
                notification_close_by_id(id, -1);
                n->id = id;
        }

        if (strlen(n->msg) == 0) {
                notification_close(n, 2);
                printf("skipping notification: %s %s\n", n->body, n->summary);
        } else {
                g_queue_insert_sorted(queue, n, notification_cmp_data, NULL);
        }

        char *tmp = g_strconcat(n->summary, " ", n->body, NULL);

        char *tmp_urls = extract_urls(tmp);
        if (tmp_urls != NULL) {
            if (n->urls != NULL) {
                n->urls = string_append(n->urls, tmp_urls, "\n");
                free(tmp_urls);
            } else {
                n->urls = tmp_urls;
            }
        }

        if (n->actions) {
                n->actions->dmenu_str = NULL;
                for (int i = 0; i < n->actions->count; i += 2) {
                        char *human_readable = n->actions->actions[i + 1];
                        string_replace_char('[', '(', human_readable); // kill square brackets
                        string_replace_char(']', ')', human_readable);

                        n->actions->dmenu_str =
                            string_append(n->actions->dmenu_str,
                                          g_strdup_printf("#%s [%s]", human_readable,
                                                                      n->appname),
                                          "\n");
                }
        }

        free(tmp);

        if (settings.print_notifications)
                notification_print(n);

        return n->id;
}
Example #10
0
/** cgi_handoff - hand off to CGI v1.1 (subset of)
 * @see http://tools.ietf.org/html/draft-robinson-www-interface-00
 * @param url requested
 * @param client to serve to
 * @param data - cgiroot
 *
 * TODO:
 *   - fix input/output to child.  I should be able to dup the socket
 *     such that the child processes stdin is the un-read payload data in
 *     in the socket and its stdout writes to the socket yet I haven't figured
 *     that out yet.  In the meantime I'm saving the payload to a file
 *     and providing that to the CGI as PAYLOAD_FILE
 */
gboolean
cgi_handoff(MediaURL *url, GstHTTPClient *client, gpointer data)
{
	const char *cgiroot = (const char*) data;
	gchar *path;
	gchar *scriptname;
	char *physpath;
	int pid;
	int outfd[2];
	int infd[2];
#ifdef CAPTURE_PAYLOAD
	int payload_len = 0;
#endif

	scriptname = url->path + strlen(CGI_PATH) + 2;
	path = g_strconcat(cgiroot, "/", scriptname, NULL);
	physpath = realpath(path, NULL);
	if (!physpath)
		goto err;
	/* ensure physpath is within cgiroot */
	if (strncmp(physpath, cgiroot, strlen(cgiroot)) ||
	   ((physpath[strlen(cgiroot)] != 0) && (physpath[strlen(cgiroot)] != '/')) )
	{
		goto err;
	}
	/* ensure file is executable */
	if (access(physpath, X_OK) < 0)
	{
		goto err;
	}

	/* capture post data to a file */
#ifdef CAPTURE_PAYLOAD
{
	gsize rz;
	gsize sz;
	gchar buf[100];
	gchar *str;
	int len;

	str = gst_http_client_get_header(client, "Content-Length");
	if (str)
		payload_len = atoi(str);

	if (payload_len) {
		len = payload_len;
		GST_DEBUG("Reading %d byte payload\n", len);
		GIOChannel *out = g_io_channel_new_file(CAPTURE_PAYLOAD, "w+", NULL);
		if (!out) {
			GST_ERROR("failed to open payload file %s: %s (%d)\n", CAPTURE_PAYLOAD,
				strerror(errno), errno);
		} else {
			while (len) {
				sz = sizeof(buf);
				if (len < sz)
					sz = len;
				g_io_channel_read_chars(client->gio, buf, sz, &rz, NULL);
// why does g_io_channel_read_chars work and read block?
//			rz = read(client->sock, &buf, sz);
				len -= rz;
				g_io_channel_write_chars(out, buf, rz, &sz, NULL);
			}
			g_io_channel_flush(out, NULL);
			g_io_channel_close(out);
		}
	}
}
#endif

	GST_INFO("Executing %s to %s:%d", physpath, client->peer_ip, client->port);

	pipe(outfd); // where the parent is going to write to
	pipe(infd);  // from where parent is going to read

	pid = fork();
	if (pid < 0) {
		GST_ERROR("fork failed: %d\n", errno);
		goto err;
	}

	// child
	if (pid == 0) {
		char *envp[32];
		int envc = 0;

#ifdef CAPTURE_PAYLOAD
		if (payload_len)
			envp[envc++] = g_strdup_printf("PAYLOAD_FILE=%s", CAPTURE_PAYLOAD);
#endif
		envp[envc++] = g_strdup_printf("REQUEST_URI=%s", url->path);
		envp[envc++] = g_strdup_printf("DOCUMENT_ROOT=%s", docroot);
		envp[envc++] = g_strdup_printf("SERVER_PROTOCOL=1.0");
		envp[envc++] = g_strdup_printf("SERVER_SOFTWARE=gst-httpd/" VERSION);
		envp[envc++] = g_strdup_printf("CONTENT_LENGTH=%s",
			gst_http_client_get_header(client, "Content-Length"));
		envp[envc++] = g_strdup_printf("CONTENT_TYPE=%s",
			gst_http_client_get_header(client, "Content-Type"));
		envp[envc++] = g_strdup_printf("REQUEST_METHOD=%s", url->method);
		envp[envc++] = g_strdup_printf("SCRIPT_FILENAME=%s", physpath);
		envp[envc++] = g_strdup_printf("SCRIPT_NAME=%s", scriptname);
		envp[envc++] = g_strdup_printf("QUERY_STRING=%s", url->query);
		envp[envc++] = g_strdup_printf("REMOTE_ADDR=%s", client->peer_ip);
		envp[envc++] = 0;

		close(STDOUT_FILENO);
		close(STDIN_FILENO);

		dup2(outfd[0], STDIN_FILENO);
		dup2(infd[1], STDOUT_FILENO);

		// not required for child
		close(outfd[0]);
		close(outfd[1]);
		close(infd[0]);
		close(infd[1]);

		//	execl(physpath, physpath, NULL);
		execle(physpath, physpath, NULL, envp);

		/* should not get here unless error */
		exit(0);
	}

	// parent
	else {
		int sz;
		char buf[1024];
		siginfo_t status;
		int res;
		int waiting;

		GST_INFO("spawned CGI child pid=%d\n", pid);

		// these are being used by the child
		close(outfd[0]);
		close(infd[1]);

/*
		write(outfd[1], "foobar\n", 7); // write to childs stdin
		char input[100];
		input[read(infd[0], input, 100)] = 0; // read for child's stdin
*/

		/* send childs stdout to client socket */
		waiting = 1;
		while (waiting) {
			if ((sz = read(infd[0], buf, sizeof(buf))) > 0) {
				write(client->sock, buf, sz);
			}
			status.si_pid = 0;
			res = waitid(P_PID, pid, &status, WEXITED | WSTOPPED | WNOHANG | WNOWAIT);
			if (status.si_pid == 0)
				continue;
			switch (status.si_code) {
				case CLD_EXITED: // child called exit (normal)
				case CLD_KILLED: // child killed by signal
				case CLD_DUMPED: // child killed by signal and dumped core
				case CLD_STOPPED: // child stopped by signal
				case CLD_TRAPPED: // child trapped
					waiting = 0;
					break;
			}
		}
		GST_DEBUG("cgi returned %d\n", status.si_status);
		write(client->sock, "", 0);

		close(outfd[1]);
		close(infd[0]);

		// reap the process
		waitpid(pid, NULL, 0);
	}
	free(physpath);
	g_free(path);
	return TRUE;

err:
	GST_ERROR("404 Not Found: %s", path);
	if (physpath)
		free(physpath);
	g_free(path);
	return TRUE;
}
Example #11
0
/*********************************************************************
 * ...
 * 
 * 
 ********************************************************************/
gboolean fm_file_info_job_run (FmJob *fmjob)
{
	FmFileInfoJob *job = (FmFileInfoJob*) fmjob;
    GError *err = NULL;

	GList *l;
	for (l = fm_list_peek_head_link (job->file_infos); !fm_job_is_cancelled (fmjob) && l; )
	{
		FmFileInfo *file_info = (FmFileInfo*) l->data;
        GList *next = l->next;

        job->current = file_info->path;

		if (fm_path_is_native (file_info->path))
		{
			char *path_str = fm_path_to_str (file_info->path);
			
            
            // FileInfo rework: new function for testing...
            // this one is not cancellable and doesn't handle errors...
            // if (!fm_file_info_job_get_info_for_native_file (FM_JOB (job), file_info, path_str, &err))
            if (!fm_file_info_set_for_native_file (file_info, path_str))
            {
                //~ FmJobErrorAction act = fm_job_emit_error (FM_JOB(job), err, FM_JOB_ERROR_MILD);
                //~ 
                //~ g_error_free (err);
                //~ err = NULL;
                //~ 
                //~ if (act == FM_JOB_RETRY)
                    //~ continue;

                DEBUG ("fm_file_info_set_for_native_file: error reading %s\n", path_str);
                
                next = l->next;
                fm_list_delete_link (job->file_infos, l); // Also calls unref...
            }
			
            g_free (path_str);
		}
		else
		{
            GFile *gf;
            
            if (fm_path_is_virtual (file_info->path))
            {
                // This is a xdg menu
                if (fm_path_is_xdg_menu (file_info->path))
                {
                    MenuCache *mc;
                    MenuCacheDir *dir;
                    
                    char *path_str = fm_path_to_str (file_info->path);
                    char *menu_name = path_str + 5, ch;
                    char *dir_name;
                    
                    while (*menu_name == '/')
                        ++menu_name;
                    
                    dir_name = menu_name;
                    
                    while (*dir_name && *dir_name != '/')
                        ++dir_name;
                    
                    ch = *dir_name;
                    *dir_name = '\0';
                    
                    menu_name = g_strconcat (menu_name, ".menu", NULL);
                    mc = menu_cache_lookup_sync (menu_name);
                    g_free (menu_name);

                    if (*dir_name && !(*dir_name == '/' && dir_name[1] == '\0'))
                    {
                        char *tmp = g_strconcat ("/",
                                                 menu_cache_item_get_id (MENU_CACHE_ITEM(menu_cache_get_root_dir (mc))),
                                                 dir_name, NULL);
                        
                        dir = menu_cache_get_dir_from_path (mc, tmp);
                        
                        g_free (tmp);
                    }
                    else
                    {
                        dir = menu_cache_get_root_dir (mc);
                    }
                    
                    if (dir)
                    {
                        fm_file_info_set_from_menu_cache_item (file_info, (MenuCacheItem*) dir);
                    }
                    else
                    {
                        next = l->next;
                        fm_list_delete_link (job->file_infos, l); // Also calls unref...
                    }
                    
                    g_free (path_str);
                    menu_cache_unref (mc);
                    
                    l = l->next;
                    continue;
                }
            }

			gf = fm_path_to_gfile (file_info->path);
			
            if (!fm_file_info_job_get_info_for_gfile (FM_JOB (job), file_info, gf, &err))
            {
                FmJobErrorAction act = fm_job_emit_error (FM_JOB (job), err, FM_JOB_ERROR_MILD);
                
                g_error_free (err);
                err = NULL;
                
                if (act == FM_JOB_RETRY)
                    continue;

                next = l->next;
                
                fm_list_delete_link (job->file_infos, l);   // Also calls unref...
            }
			
            g_object_unref (gf);
		}
        
        l = next;
	}
	
    return TRUE;
}
Example #12
0
/** serve_page - serve a page via HTTP
 * @param url requested
 * @param client to serve to
 * @param data - docroot
 */
gboolean
serve_page(MediaURL *url, GstHTTPClient *client, gpointer data)
{
	int fd;
	char buf[1024];
	int sz;
	struct stat sb;
	const char *docroot = (const char*) data;
	gchar *path;
	char *physpath;
	const char *mimetype;

	if (strcmp(url->path, "/") == 0)
		path = g_strconcat(docroot, url->path, "index.html", NULL);
	else
		path = g_strconcat(docroot, url->path, NULL);
	physpath = realpath(path, NULL);
	if (!physpath)
		goto err;
	/* ensure physpath is within docroot */
	if (strncmp(physpath, docroot, strlen(docroot)) ||
	   ((physpath[strlen(docroot)] != 0) && (physpath[strlen(docroot)] != '/')) )
	{
		goto err;
	}
	/* ensure file is readable */
	if ( (stat(physpath, &sb) < 0)
	  || (fd = open(physpath, O_RDONLY)) == -1)
	{
		goto err;
	}
	if (!S_ISREG(sb.st_mode)) {
		close(fd);
		goto err;
	}
	/* obtain mimetype */
	mimetype = mime_lookup(physpath);

	GST_INFO("Serving %d byte %s to %s:%d as %s", (int)sb.st_size, physpath,
		client->peer_ip, client->port, mimetype);

	WRITELN(client, "Last-Modified: %s", unix2date(sb.st_mtime));
	WRITELN(client, "Content-Length: %ld", sb.st_size);
	WRITELN(client, "Content-Type: %s\r\n", mimetype);

	while ( (sz = read(fd, buf, sizeof(buf))) > 0) {
		write(client->sock, buf, sz);
	}
	write(client->sock, "", 0);
	close(fd);
	
	free(physpath);
	g_free(path);
	return TRUE;

err:
	GST_ERROR("404 Not Found: %s", path);
	if (physpath)
		free(physpath);
	g_free(path);
	return TRUE;
}
Example #13
0
DonnaTask *
donna_fs_engine_basic_io_task (DonnaProviderFs    *pfs,
                               DonnaApp           *app,
                               DonnaIoType         type,
                               GPtrArray          *sources,
                               DonnaNode          *dest,
                               const gchar        *new_name,
                               fs_parse_cmdline    parser,
                               fs_file_created     file_created,
                               fs_file_deleted     file_deleted,
                               GError            **error)
{
    DonnaTaskProcess *taskp;
    struct data *data;
    gchar *cmdline;
    gchar *s = NULL;
    guint i;

    data = g_slice_new0 (struct data);
    data->pfs = g_object_ref (pfs);
    data->app = app;
    data->file_created = file_created;
    data->file_deleted = file_deleted;

    if (type == DONNA_IO_DELETE)
    {
        data->removed_prefix = (gchar *) "removed ";
        data->removed_prefix_len = 8; /* x = strlen ("removed ") */
    }

    data->openq = data->closeq = "'";
    switch (type)
    {
        case DONNA_IO_COPY:
            if (new_name && sources->len == 1)
            {
                gchar *ss = g_shell_quote (new_name);
                cmdline = s = g_strconcat ("cp -irvaT %s %d/", ss, NULL);
                g_free (ss);
            }
            else
                cmdline = (gchar *) "cp -irvat %d %s";
            snprintf (data->prefix, LEN_PREFIX + 1, "cp: ");
            break;

        case DONNA_IO_MOVE:
            if (new_name && sources->len == 1)
            {
                gchar *ss = g_shell_quote (new_name);
                cmdline = s = g_strconcat ("mv -ivT %s %d/", ss, NULL);
                g_free (ss);
            }
            else
                cmdline = (gchar *) "mv -ivt %d %s";
            snprintf (data->prefix, LEN_PREFIX + 1, "mv: ");
            break;

        case DONNA_IO_DELETE:
            cmdline = (gchar *) "rm -Irv %s";
            snprintf (data->prefix, LEN_PREFIX + 1, "rm: ");
            data->is_rm = TRUE;
            break;

        default:
            free_data (data);
            g_set_error (error, DONNA_PROVIDER_ERROR,
                    DONNA_PROVIDER_ERROR_NOT_SUPPORTED,
                    "FS Engine 'basic': Operation not supported (%d)", type);
            return NULL;
    }

    cmdline = parser (cmdline, sources, dest, error);
    if (G_UNLIKELY (!cmdline))
    {
        free_data (data);
        g_prefix_error (error, "FS Engine 'basic': Failed to parse command line: ");
        g_free (s);
        return NULL;
    }
    g_free (s);


    taskp = (DonnaTaskProcess *) donna_task_process_new_full (
            (task_init_fn) set_cmdline, cmdline, g_free,
            TRUE /* wait */,
            NULL, NULL, NULL, /* default pauser */
            (task_stdin_fn) handle_stdin, data, NULL,
            (task_closer_fn) closer, data, NULL);
    if (G_UNLIKELY (!taskp))
    {
        free_data (data);
        g_set_error (error, DONNA_PROVIDER_ERROR,
                DONNA_PROVIDER_ERROR_OTHER,
                "FS Engine 'basic': Failed to create new task-process");
        g_free (cmdline);
        return NULL;
    }

    donna_task_process_set_ui_msg (taskp);

    if (G_UNLIKELY (!donna_task_process_set_workdir_to_curdir (taskp, app)))
    {
        g_set_error (error, DONNA_PROVIDER_ERROR,
                DONNA_PROVIDER_ERROR_OTHER,
                "FS Engine 'basic': Failed to set workdir for task-process");
        g_object_unref (taskp);
        return NULL;
    }

    if (type == DONNA_IO_COPY || type == DONNA_IO_MOVE)
    {
        /* construct the list of location to watch for return nodes */
        data->loc_sources = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, NULL);
        for (i = 0; i < sources->len; ++i)
            g_hash_table_add (data->loc_sources,
                    donna_node_get_location (sources->pdata[i]));
        /* return value */
        data->ret_nodes = g_ptr_array_new_full (sources->len, g_object_unref);
    }

    g_signal_connect (taskp, "pipe-data-received", (GCallback) pipe_data_received, data);
    g_signal_connect (taskp, "pipe-new-line", (GCallback) pipe_new_line, data);
    g_signal_connect_swapped (taskp, "process-ended", (GCallback) free_data, data);

    return (DonnaTask *) taskp;
}
Example #14
0
static gboolean
convert_file (ConvertData *data)
{
    GFile *file;
    DocItem *item;
    const gchar *uri;
    xmlNodePtr node;
    xmlNodePtr cur;
    gint total, current;
    gchar *text;

    if (!data->current)
        return FALSE;

    item = (DocItem *) data->current->data;
    uri = (const gchar *)item->uri;
    node = item->cur;
    data->current = g_list_next (data->current);

    /* Update progress information */
    total = g_list_length (data->items);
    current = ++(data->n_item);

    text = g_strdup_printf (_("Converting %s"), uri);
    gtk_label_set_text (GTK_LABEL (data->label), text);
    g_free (text);

    text = g_strdup_printf (_("%d of %d documents converted"), current, total);
    gtk_progress_bar_set_text (GTK_PROGRESS_BAR (data->progress), text);
    g_free (text);
    gtk_progress_bar_set_fraction (GTK_PROGRESS_BAR (data->progress),
                                   (gdouble)(current - 1) / total);

    file = g_file_new_for_uri (uri);
    if (!g_file_query_exists (file, NULL)) {
        g_printerr ("Uri %s does not exist\n", uri);
        g_object_unref (file);

        return data->current != NULL;
    }

    for (cur = node->xmlChildrenNode; cur != NULL; cur = cur->next) {
        xmlChar *key;
        xmlChar *value;

        if (xmlStrcmp (cur->name, (const xmlChar *)"entry") != 0)
            continue;

        key = xmlGetProp (cur, (const xmlChar *)"key");
        value = xmlGetProp (cur, (const xmlChar *)"value");
        if (key && value) {
            GFileInfo *info;
            gchar *gio_key;
            GError *error = NULL;

            info = g_file_info_new ();

            gio_key = g_strconcat (EV_METADATA_NAMESPACE"::", key, NULL);
            g_file_info_set_attribute_string (info, gio_key, (const gchar *)value);
            g_free (gio_key);

            if (!g_file_set_attributes_from_info (file, info, 0, NULL, &error)) {
                g_printerr ("Error setting metadata for %s: %s\n",
                            uri, error->message);
                g_error_free (error);
            }

            g_object_unref (info);
        }

        if (key)
            xmlFree (key);
        if (value)
            xmlFree (value);
    }

    g_object_unref (file);

    return data->current != NULL;
}
Example #15
0
void
plug_in_menus_setup (GimpUIManager *manager,
                     const gchar   *ui_path)
{
  GimpPlugInManager *plug_in_manager;
  GTree             *menu_entries;
  GSList            *list;
  guint              merge_id;
  gint               i;

  g_return_if_fail (GIMP_IS_UI_MANAGER (manager));
  g_return_if_fail (ui_path != NULL);

  plug_in_manager = manager->gimp->plug_in_manager;

  merge_id = gtk_ui_manager_new_merge_id (GTK_UI_MANAGER (manager));

  for (i = 0; i < manager->gimp->config->plug_in_history_size; i++)
    {
      gchar *action_name;
      gchar *action_path;

      action_name = g_strdup_printf ("plug-in-recent-%02d", i + 1);
      action_path = g_strdup_printf ("%s/Filters/Recently Used/Plug-Ins",
                                     ui_path);

      gtk_ui_manager_add_ui (GTK_UI_MANAGER (manager), merge_id,
                             action_path, action_name, action_name,
                             GTK_UI_MANAGER_MENUITEM,
                             FALSE);

      g_free (action_name);
      g_free (action_path);
    }

  menu_entries = g_tree_new_full ((GCompareDataFunc) strcmp, NULL,
                                  g_free,
                                  (GDestroyNotify) plug_in_menu_entry_free);

  for (list = plug_in_manager->plug_in_procedures;
       list;
       list = g_slist_next (list))
    {
      GimpPlugInProcedure *plug_in_proc = list->data;

      if (! plug_in_proc->file)
        continue;

      g_signal_connect_object (plug_in_proc, "menu-path-added",
                               G_CALLBACK (plug_in_menus_menu_path_added),
                               manager, 0);

      if (plug_in_proc->menu_paths &&
          ! plug_in_proc->file_proc)
        {
          GList *path;

          for (path = plug_in_proc->menu_paths; path; path = g_list_next (path))
            {
              if (g_str_has_prefix (path->data, manager->name))
                {
                  PlugInMenuEntry *entry = g_slice_new0 (PlugInMenuEntry);
                  GFile           *file;
                  const gchar     *locale_domain;

                  entry->proc      = plug_in_proc;
                  entry->menu_path = path->data;

                  file = gimp_plug_in_procedure_get_file (plug_in_proc);

                  locale_domain =
                    gimp_plug_in_manager_get_locale_domain (plug_in_manager,
                                                            file, NULL);

                  if (plug_in_proc->menu_label)
                    {
                      gchar *menu;

                      menu = g_strconcat (dgettext (locale_domain,
                                                    path->data),
                                          "/",
                                          dgettext (locale_domain,
                                                    plug_in_proc->menu_label),
                                          NULL);

                      plug_in_menus_tree_insert (menu_entries, menu, entry);
                      g_free (menu);
                    }
                  else
                    {
                      plug_in_menus_tree_insert (menu_entries,
                                                 dgettext (locale_domain,
                                                           path->data),
                                                 entry);
                    }
                }
            }
        }
    }

  g_object_set_data (G_OBJECT (manager), "ui-path", (gpointer) ui_path);

  g_tree_foreach (menu_entries,
                  (GTraverseFunc) plug_in_menus_tree_traverse,
                  manager);

  g_object_set_data (G_OBJECT (manager), "ui-path", NULL);

  g_tree_destroy (menu_entries);

  g_signal_connect_object (manager->gimp->pdb, "register-procedure",
                           G_CALLBACK (plug_in_menus_register_procedure),
                           manager, 0);
  g_signal_connect_object (manager->gimp->pdb, "unregister-procedure",
                           G_CALLBACK (plug_in_menus_unregister_procedure),
                           manager, 0);
}
Example #16
0
static void
ibus_hangul_engine_update_hanja_list (IBusHangulEngine *hangul)
{
    gchar* hanja_key;
    gchar* preedit_utf8;
    const ucschar* hic_preedit;
    UString* preedit;
    int lookup_method;
    IBusText* ibus_text = NULL;
    guint cursor_pos = 0;
    guint anchor_pos = 0;

    if (hangul->hanja_list != NULL) {
        hanja_list_delete (hangul->hanja_list);
        hangul->hanja_list = NULL;
    }

    hic_preedit = hangul_ic_get_preedit_string (hangul->context);

    hanja_key = NULL;
    lookup_method = LOOKUP_METHOD_PREFIX;

    preedit = ustring_dup (hangul->preedit);
    ustring_append_ucs4 (preedit, hic_preedit, -1);

    if (ustring_length(preedit) > 0) {
        preedit_utf8 = ustring_to_utf8 (preedit, -1);
        if (word_commit || hangul->hanja_mode) {
            hanja_key = preedit_utf8;
            lookup_method = LOOKUP_METHOD_PREFIX;
        } else {
            gchar* substr;
            ibus_engine_get_surrounding_text ((IBusEngine *)hangul, &ibus_text,
                    &cursor_pos, &anchor_pos);

            substr = h_ibus_text_get_substring (ibus_text,
                    cursor_pos - 64, cursor_pos);

            if (substr != NULL) {
                hanja_key = g_strconcat (substr, preedit_utf8, NULL);
                g_free (preedit_utf8);
            } else {
                hanja_key = preedit_utf8;
            }
            lookup_method = LOOKUP_METHOD_SUFFIX;
        }
    } else {
        ibus_engine_get_surrounding_text ((IBusEngine *)hangul, &ibus_text,
                &cursor_pos, &anchor_pos);
        if (cursor_pos != anchor_pos) {
            // If we have selection in surrounding text, we use that.
            hanja_key = h_ibus_text_get_substring (ibus_text,
                    cursor_pos, anchor_pos);
            lookup_method = LOOKUP_METHOD_EXACT;
        } else {
            hanja_key = h_ibus_text_get_substring (ibus_text,
                    cursor_pos - 64, cursor_pos);
            lookup_method = LOOKUP_METHOD_SUFFIX;
        }
    }

    if (hanja_key != NULL) {
        hangul->hanja_list = ibus_hangul_engine_lookup_hanja_table (hanja_key,
                lookup_method);
        hangul->last_lookup_method = lookup_method;
        g_free (hanja_key);
    }

    ustring_delete (preedit);

    if (ibus_text != NULL)
        g_object_unref (ibus_text);
}
Example #17
0
static void sig_print_text(TEXT_DEST_REC *dest, const char *text,
			   const char *stripped)
{
	HILIGHT_REC *hilight;
	char *color, *newstr;
	int old_level, hilight_start, hilight_end, hilight_len;
	int nick_match;

	if (dest->level & MSGLEVEL_NOHILIGHT)
		return;

        hilight_start = hilight_end = 0;
	hilight = hilight_match(dest->server, dest->target,
				NULL, NULL, dest->level, stripped,
				&hilight_start,
				&hilight_end);
	if (hilight == NULL)
		return;

	nick_match = hilight->nick && (dest->level & (MSGLEVEL_PUBLIC|MSGLEVEL_ACTIONS)) == MSGLEVEL_PUBLIC;

	old_level = dest->level;
	if (!nick_match || (dest->level & MSGLEVEL_HILIGHT)) {
		/* update the level / hilight info */
		hilight_update_text_dest(dest, hilight);
	}

	if (nick_match)
		return; /* fe-messages.c should have taken care of this */

	if (old_level & MSGLEVEL_HILIGHT) {
		/* nick is highlighted, just set priority */
		return;
	}

	color = hilight_get_color(hilight);
	hilight_len = hilight_end-hilight_start;

	if (!hilight->word) {
		/* hilight whole line */
		char *tmp = strip_codes(text);
		newstr = g_strconcat(color, tmp, NULL);
                g_free(tmp);
	} else {
		/* hilight part of the line */
                GString *tmp;
                char *middle, *lastcolor;
		int pos, color_pos, color_len;

                tmp = g_string_new(NULL);

                /* start of the line */
		pos = strip_real_length(text, hilight_start, NULL, NULL);
		g_string_append(tmp, text);
                g_string_truncate(tmp, pos);

		/* color */
                g_string_append(tmp, color);

		/* middle of the line, stripped */
		middle = strip_codes(text+pos);
                pos = tmp->len;
		g_string_append(tmp, middle);
                g_string_truncate(tmp, pos+hilight_len);
                g_free(middle);

		/* end of the line */
		pos = strip_real_length(text, hilight_end,
					&color_pos, &color_len);
		if (color_pos > 0)
			lastcolor = g_strndup(text+color_pos, color_len);
                else {
                        /* no colors in line, change back to default */
			lastcolor = g_malloc0(3);
			lastcolor[0] = 4;
                        lastcolor[1] = FORMAT_STYLE_DEFAULTS;
		}
		g_string_append(tmp, lastcolor);
		g_string_append(tmp, text+pos);
		g_free(lastcolor);

                newstr = tmp->str;
                g_string_free(tmp, FALSE);
	}

	signal_emit("print text", 3, dest, newstr, stripped);

	g_free(color);
	g_free(newstr);

	signal_stop();
}
Example #18
0
static void
panel_menu_items_append_from_desktop (GtkWidget *menu,
				      char      *path,
				      char      *force_name,
                                      gboolean   use_icon)
{
	GKeyFile  *key_file;
	gboolean   loaded;
	GtkWidget *item;
	char      *path_freeme;
	char      *full_path;
	char      *uri;
	char      *type;
	gboolean   is_application;
	char      *tryexec;
	char      *icon;
	char      *name;
	char      *comment;

	path_freeme = NULL;

	key_file = g_key_file_new ();

	if (g_path_is_absolute (path)) {
		loaded = g_key_file_load_from_file (key_file, path,
						    G_KEY_FILE_NONE, NULL);
		full_path = path;
	} else {
		char *lookup_file;
		char *desktop_path;

		if (!g_str_has_suffix (path, ".desktop")) {
			desktop_path = g_strconcat (path, ".desktop", NULL);
		} else {
			desktop_path = path;
		}

		lookup_file = g_strconcat ("applications", G_DIR_SEPARATOR_S,
					   desktop_path, NULL);
		loaded = g_key_file_load_from_data_dirs (key_file, lookup_file,
							 &path_freeme,
							 G_KEY_FILE_NONE,
							 NULL);
		full_path = path_freeme;
		g_free (lookup_file);

		if (desktop_path != path)
			g_free (desktop_path);
	}

	if (!loaded) {
		g_key_file_free (key_file);
		if (path_freeme)
			g_free (path_freeme);
		return;
	}

	/* For Application desktop files, respect TryExec */
	type = panel_key_file_get_string (key_file, "Type");
	if (!type) {
		g_key_file_free (key_file);
		if (path_freeme)
			g_free (path_freeme);
		return;
	}
	is_application = (strcmp (type, "Application") == 0);
	g_free (type);

	if (is_application) {
		tryexec = panel_key_file_get_string (key_file, "TryExec");
		if (tryexec) {
			char *prog;

			prog = g_find_program_in_path (tryexec);
			g_free (tryexec);

			if (!prog) {
				/* FIXME: we could add some file monitor magic,
				 * so that the menu items appears when the
				 * program appears, but that's really complex
				 * for not a huge benefit */
				g_key_file_free (key_file);
				if (path_freeme)
					g_free (path_freeme);
				return;
			}

			g_free (prog);
		}
	}

	/* Now, simply build the menu item */
	icon    = panel_key_file_get_locale_string (key_file, "Icon");
	comment = panel_key_file_get_locale_string (key_file, "Comment");

	if (PANEL_GLIB_STR_EMPTY (force_name))
		name = panel_key_file_get_locale_string (key_file, "Name");
	else
		name = g_strdup (force_name);

	if (use_icon) {
		item = panel_image_menu_item_new ();
        } else {
		item = gtk_image_menu_item_new ();
	}

	setup_menuitem_with_icon (item, panel_menu_icon_get_size (),
				  NULL, icon, name);

	panel_util_set_tooltip_text (item, comment);

	gtk_menu_shell_append (GTK_MENU_SHELL (menu), item);
	g_signal_connect_data (item, "activate",
			       G_CALLBACK (panel_menu_item_activate_desktop_file),
			       g_strdup (full_path),
			       (GClosureNotify) g_free, 0);
	g_signal_connect (G_OBJECT (item), "button_press_event",
			  G_CALLBACK (menu_dummy_button_press_event), NULL);

	uri = g_filename_to_uri (full_path, NULL, NULL);

	setup_uri_drag (item, uri, icon, GDK_ACTION_COPY);
	g_free (uri);

	g_key_file_free (key_file);

	if (icon)
		g_free (icon);

	if (name)
		g_free (name);

	if (comment)
		g_free (comment);

	if (path_freeme)
		g_free (path_freeme);
}
Example #19
0
/** \brief Create a module window.
 *
 * This function is used to create a module window when opening modules
 * that should not be packed into the notebook.
 */
static void
create_module_window (GtkWidget *module)
{
    gint       w,h;
    gchar     *icon;      /* icon file name */
    gchar     *title;     /* window title */


    /* get stored size; use size from main window if size not explicitly stoed */
    if (g_key_file_has_key (GTK_SAT_MODULE (module)->cfgdata,
                            MOD_CFG_GLOBAL_SECTION,
                            MOD_CFG_WIN_WIDTH,
                            NULL)) {
        w = g_key_file_get_integer (GTK_SAT_MODULE (module)->cfgdata,
                                    MOD_CFG_GLOBAL_SECTION,
                                    MOD_CFG_WIN_WIDTH,
                                    NULL);
    }
    else {
        w = module->allocation.width;
    }
    if (g_key_file_has_key (GTK_SAT_MODULE (module)->cfgdata,
                            MOD_CFG_GLOBAL_SECTION,
                            MOD_CFG_WIN_HEIGHT,
                            NULL)) {
        h = g_key_file_get_integer (GTK_SAT_MODULE (module)->cfgdata,
                                    MOD_CFG_GLOBAL_SECTION,
                                    MOD_CFG_WIN_HEIGHT,
                                    NULL);
    }
    else {
        h = module->allocation.height;
    }
        
    /* increase reference count of module */
    //g_object_ref (module);

    /* we don't need the positions */
    //GTK_SAT_MODULE (module)->vpanedpos = -1;
    //GTK_SAT_MODULE (module)->hpanedpos = -1;

    /* undock from mod-mgr */
    //mod_mgr_undock_module (module);

    /* create window */
    GTK_SAT_MODULE (module)->win = gtk_window_new (GTK_WINDOW_TOPLEVEL);
    title = g_strconcat ("GPREDICT: ",
                         GTK_SAT_MODULE (module)->name,
                         " (", GTK_SAT_MODULE (module)->qth->name, ")",
                         NULL);
    gtk_window_set_title (GTK_WINDOW (GTK_SAT_MODULE (module)->win), title);
    g_free (title);
    gtk_window_set_default_size (GTK_WINDOW (GTK_SAT_MODULE (module)->win), w, h);
    g_signal_connect (G_OBJECT (GTK_SAT_MODULE (module)->win), "configure_event",
                      G_CALLBACK (module_window_config_cb), module);

    /* window icon */
    icon = icon_file_name ("gpredict-icon.png");
    if (g_file_test (icon, G_FILE_TEST_EXISTS)) {
        gtk_window_set_icon_from_file (GTK_WINDOW (GTK_SAT_MODULE (module)->win), icon, NULL);
    }
    g_free (icon);

    /* move window to stored position if requested by configuration */
    if (sat_cfg_get_bool (SAT_CFG_BOOL_MOD_WIN_POS) &&
        g_key_file_has_key (GTK_SAT_MODULE (module)->cfgdata,
                            MOD_CFG_GLOBAL_SECTION,
                            MOD_CFG_WIN_POS_X,
                            NULL) &&
        g_key_file_has_key (GTK_SAT_MODULE (module)->cfgdata,
                            MOD_CFG_GLOBAL_SECTION,
                            MOD_CFG_WIN_POS_Y,
                            NULL)) {
                
        gtk_window_move (GTK_WINDOW (GTK_SAT_MODULE (module)->win),
                         g_key_file_get_integer (GTK_SAT_MODULE (module)->cfgdata,
                                                 MOD_CFG_GLOBAL_SECTION,
                                                 MOD_CFG_WIN_POS_X, NULL),
                         g_key_file_get_integer (GTK_SAT_MODULE (module)->cfgdata,
                                                 MOD_CFG_GLOBAL_SECTION,
                                                 MOD_CFG_WIN_POS_Y,
                                                 NULL));

    }

    /* add module to window */
    gtk_container_add (GTK_CONTAINER (GTK_SAT_MODULE (module)->win), module);

    /* show window */
    gtk_widget_show_all (GTK_SAT_MODULE (module)->win);
        
    /* reparent time manager window if visible */
    if (GTK_SAT_MODULE (module)->tmgActive) {
        gtk_window_set_transient_for (GTK_WINDOW (GTK_SAT_MODULE (module)->tmgWin),
                                      GTK_WINDOW (GTK_SAT_MODULE (module)->win));
    }


}
Example #20
0
/*
 *     ---------------------- SYSTEM -------------------------
 * This procedure will actually bring up the virtual ethernet pairs, since
 * even if both ends of it are connected to some switches, they are in DOWN
 * state.
 * gchar* vnf_dev - the virtual ethernet device assigned to the vnf
 * gchar* sw_dev - the virtual ethernet device assigned to the switch
 * gint status - LINK_UP or LINK_DOWN
 * up
 * return gboolean - TRUE if everything went fine
 * 					 FALSE if something went wrong
 */
gboolean bringVirtualEthernetPairs(gchar* vnf_dev, gchar* sw_dev, gint status)
{
	//setting up the status
	gchar* st = "";
	if(status == LINK_DOWN)
	{
		st = " down ";
	}
	else if(status == LINK_UP)
	{
		st = " up ";
	}
	else
	{
		//status information was not correctly set
		return FALSE;
	}


	//assembling the first bring-up command
	gchar* command_1 = g_strconcat("ip link set ",
					 vnf_dev,
					 st,
					 NULL);

	//executing the first bring-up command
	int returnValue = system(command_1);
//	custom_log(LOG, g_strdup_printf("Return value: %d", returnValue));
	//checking whether execution was successful
	if(returnValue == 0)
	{
		//if everything went fine (return value of the command is 0)
		custom_log(INFO, g_strdup_printf("Device %s has been brought %s",
								  	  	  vnf_dev, st));

	}
	else
	{
		//something went wrong during executing the command
		custom_log(ERROR, g_strdup_printf("An error occurred during bringing %s"
								  " device %s",
								  st,
								  vnf_dev));
		return FALSE;
	}
	//we can free command_1, since we do not need anymore
	g_free(command_1);




	//assembling the second command
	gchar* command_2 = g_strconcat("ip link set ",
						  sw_dev,
						  st,
						  NULL);

	//executing the first bring-up command
	returnValue = system(command_2);
	//checking whether execution was successful
	if(returnValue == 0)
	{
		//if everything went fine (return value of the command is 0)
		custom_log(INFO, g_strdup_printf("Device %s has been brought %s",
								  	  	  sw_dev,
								  	  	  st));

	}
	else
	{
		//something went wrong during executing the command
		custom_log(ERROR, g_strdup_printf("An error occurred during bringing %s"
								  " device %s",
								  st,
								  sw_dev));
		return FALSE;
	}
	//we can free command_1, since we do not need anymore
	g_free(command_2);


	return TRUE;

}
Example #21
0
/**
 * ticalcs_calc_recv_tigroup:
 * @handle: a previously allocated handle
 * @filename: name of file
 * @mode: which vars/apps to receive
 *
 * Receive a TiGroup file.
 *
 * Return value: 0 if ready else ERR_NOT_READY.
 **/
TIEXPORT3 int TICALL ticalcs_calc_recv_tigroup(CalcHandle* handle, TigContent* content, TigMode mode)
{
	int i, j;
	int i_max, j_max;
	GNode *vars, *apps;
	int nvars = 0;
	int napps = 0;
	int b = 0;

	if(handle == NULL) return ERR_INVALID_HANDLE;
	if (content == NULL)
	{
		ticalcs_critical("ticalcs_calc_send_tigroup: content is NULL");
		return -1;
	}

	update_->cnt3 = 0;
	update_->pbar();

	// Do a directory list and check for something to backup
	TRYF(handle->calc->get_dirlist(handle, &vars, &apps));
	if((mode & TIG_RAM) || (mode & TIG_ARCHIVE))
		nvars = ticalcs_dirlist_ve_count(vars);
	if(mode & TIG_FLASH)
		napps = ticalcs_dirlist_ve_count(apps);

	update_->cnt3 = 0;
	update_->max3 = nvars + napps;
	update_->pbar();

	if(!nvars && !napps)
		return ERR_NO_VARS;

	// Check whether the last folder is empty
	b = g_node_n_children(g_node_nth_child(vars, g_node_n_children(vars) - 1));
	PAUSE(100); // needed by TI84+/USB

	// Receive all vars
	i_max = g_node_n_children(vars);
	if((mode & TIG_RAM) || (mode & TIG_ARCHIVE))
	for(i = 0; i < i_max; i++) 
	{
		GNode *parent = g_node_nth_child(vars, i);

		j_max = g_node_n_children(parent);
		for(j = 0; j < j_max; j++) 
		{
			GNode *node = g_node_nth_child(parent, j);
			VarEntry *ve = (VarEntry *) (node->data);
			TigEntry *te;
			char *filename;
			char *varname;
			char *fldname;

			PAUSE(100);
			TRYF(handle->calc->is_ready(handle));
			PAUSE(100);

			update_->cnt3++;
			update_->pbar();

			if(((mode & TIG_ARCHIVE) && (ve->attr == ATTRB_ARCHIVED)) ||
			   ((mode & TIG_RAM) && ve->attr != ATTRB_ARCHIVED))
			{
				fldname = ticonv_varname_to_filename(handle->model, ve->folder, -1);
				varname = ticonv_varname_to_filename(handle->model, ve->name, ve->type);
				if(handle->calc->features & FTS_FOLDER)
					filename = g_strconcat(fldname, ".", varname, ".", 
						tifiles_vartype2fext(handle->model, ve->type), NULL);
				else
					filename = g_strconcat(varname, ".", 
						tifiles_vartype2fext(handle->model, ve->type), NULL);
				g_free(fldname);
				g_free(varname);

				te = tifiles_te_create(filename, TIFILE_SINGLE, handle->model);
				g_free(filename);

				TRYF(handle->calc->recv_var(handle, 0, te->content.regular, ve));
				tifiles_content_add_te(content, te);
			}
		}
	}
	ticalcs_dirlist_destroy(&vars);

	// Receive all apps
	i_max = g_node_n_children(apps);
	if(mode & TIG_FLASH)
	for(i = 0; i < i_max; i++) 
	{
		GNode *parent = g_node_nth_child(apps, i);

		j_max = g_node_n_children(parent);
		for(j = 0; j < j_max; j++) 
		{
			GNode *node = g_node_nth_child(parent, j);
			VarEntry *ve = (VarEntry *) (node->data);
			TigEntry *te;
			char *filename;
			char *basename;

			TRYF(handle->calc->is_ready(handle));

			update_->cnt3++;
			update_->pbar();

			basename = ticonv_varname_to_filename(handle->model, ve->name, ve->type);
			filename = g_strconcat(basename, ".", tifiles_vartype2fext(handle->model, ve->type), NULL);
			g_free(basename);

			te = tifiles_te_create(filename, TIFILE_FLASH, handle->model);
			g_free(filename);

			TRYF(handle->calc->recv_app(handle, te->content.flash, ve));
			tifiles_content_add_te(content, te);
		}
	}	
	ticalcs_dirlist_destroy(&apps);

	return 0;
}
Example #22
0
/*
 *     ---------------------- DATASTRUCTURE -------------------------
 * This procedure automatically creates a new VNF structure with empty data
 * for effective storing. It also generates a unique ID for the newly created
 * VNF.
 * int port_num - number of ports a vnf requires
 * return gchar* - the new unique id of the VNF, e.g, vnf_X
 */
gchar* createVNF()
{
	//The new unique id of the vnf
	gchar* new_ID = NULL;

	//check whether there exists any VNF of not
	if(g_hash_table_size(vnfs) == 0)
	{
		//There is no VNF yet
		new_ID = g_strconcat("vnf_", "1", NULL);

	}
	else
	{
		/* if any VNF already exists in the hashtable, we need to check all ids
		in order to ensure that a newly created id will be unique as well */


		//for storing the highest vnf number
		gint highestNumber = 0;
		//getting the keys from hashtable 'vnfs'
		GList* ids = g_hash_table_get_keys(vnfs);
		//temporary variable for iterating the list of the keys
		GList* iterator = NULL;
		for(iterator = ids; iterator; iterator = iterator->next)
		{
			//we handling everything as gchar*, since it is easier
			gchar* vnf_number = NULL;

			//tokenizing vnf ids
			//we need to create a new variable
			gchar* current_vnf_id = g_strdup((gchar*)iterator->data);

			//this will produce 'vnf' from 'vnf_X'
			vnf_number = strtok(current_vnf_id, "_");

			//this will produce 'X'
			vnf_number = strtok(NULL, "_");

			//convert it to int in order to compare the values
			gint vnf_number_as_int = atoi(vnf_number);

			//comparing
			if(vnf_number_as_int > highestNumber)
			{
				//updating highest number
				highestNumber = vnf_number_as_int;
			}
		}

		//freeing temporary lists
		g_list_free(iterator);
		g_list_free(ids);

		//new id should be higher than the found maximum
		highestNumber++;


		//assembling the new vnf id
		new_ID = g_strconcat("vnf_", g_strdup_printf("%d",highestNumber), NULL);

	}


	//creating an empty vnf_data structure and initializing its variables
	vnf_data *data;
	//allocating space for vnf_data structure
	data = g_malloc(sizeof *data);

	//initializing the variables of the vnf structure

	data->pid = -1;
	data->control_ip = NULL;
	data->control_port = NULL;
	data->vnf_command = NULL;


	data->links = g_hash_table_new_full(g_str_hash,
										g_str_equal,
										g_free,
										g_free);





	//Add the created vnf to the main hashtable that stores all vnfs
	addVNF(new_ID, data);


	//pass back the ID of the newly created vnf
	return new_ID;
}
Example #23
0
/**
 * mono_dl_open:
 * @name: name of file containing shared module
 * @flags: flags
 * @error_msg: pointer for error message on failure
 *
 * Load the given file @name as a shared library or dynamically loadable
 * module. @name can be NULL to indicate loading the currently executing
 * binary image.
 * @flags can have the MONO_DL_LOCAL bit set to avoid exporting symbols
 * from the module to the shared namespace. The MONO_DL_LAZY bit can be set
 * to lazily load the symbols instead of resolving everithing at load time.
 * @error_msg points to a string where an error message will be stored in
 * case of failure.   The error must be released with g_free.
 *
 * Returns: a MonoDl pointer on success, NULL on failure.
 */
MonoDl*
mono_dl_open (const char *name, int flags, char **error_msg)
{
	MonoDl *module;
	void *lib;
	MonoDlFallbackHandler *dl_fallback = NULL;
	int lflags = mono_dl_convert_flags (flags);

	if (error_msg)
		*error_msg = NULL;

	module = (MonoDl *) g_malloc (sizeof (MonoDl));
	if (!module) {
		if (error_msg)
			*error_msg = g_strdup ("Out of memory");
		return NULL;
	}
	module->main_module = name == NULL? TRUE: FALSE;

	lib = mono_dl_open_file (name, lflags);

	if (!lib) {
		GSList *node;
		for (node = fallback_handlers; node != NULL; node = node->next){
			MonoDlFallbackHandler *handler = (MonoDlFallbackHandler *) node->data;
			if (error_msg)
				*error_msg = NULL;
			
			lib = handler->load_func (name, lflags, error_msg, handler->user_data);
			if (error_msg && *error_msg != NULL)
				g_free (*error_msg);
			
			if (lib != NULL){
				dl_fallback = handler;
				break;
			}
		}
	}
	if (!lib && !dl_fallback) {
		char *lname;
		char *llname;
		const char *suff;
		const char *ext;
		/* This platform does not support dlopen */
		if (name == NULL) {
			g_free (module);
			return NULL;
		}
		
		suff = ".la";
		ext = strrchr (name, '.');
		if (ext && strcmp (ext, ".la") == 0)
			suff = "";
		lname = g_strconcat (name, suff, NULL);
		llname = get_dl_name_from_libtool (lname);
		g_free (lname);
		if (llname) {
			lib = mono_dl_open_file (llname, lflags);
			g_free (llname);
		}
		if (!lib) {
			if (error_msg) {
				*error_msg = mono_dl_current_error_string ();
			}
			g_free (module);
			return NULL;
		}
	}
	module->handle = lib;
	module->dl_fallback = dl_fallback;
	return module;
}
Example #24
0
/*
 *     ---------------------- SYSTEM -------------------------
 * This procedure will create a practical veth pairs by system calls.
 * It also checks other existing veth pairs, and automatically determine, which
 * name should be assigned to the new veth pairs.
 * return gchar* - veth_pair_as_char consisting of the newly created veth pairs
 * in order to set it for a vnf by addVirtualEthernetPairs(...) function
 */
gchar* createVirtualEthernetPairs(void)
{

	//for storing all the uny_X devices' numbers (X)
	GSList *device_numbers = NULL;

	//a line for stdout
	char path[100];

	//found device, e.g., uny_3
	gchar *dev;

	//for running a command and read its stdout
	FILE *get_veths;


	//first we need to get actual uny_X devices
	get_veths = popen("ip link | grep uny| cut -d ' ' -f 2", "r");
	//the result is like: 'uny_2:'

	//checking that command was run successfully
	if(get_veths == NULL)
	{
		custom_log(ERROR, "Failed to run command");

	}
	//command execution succeeded
	else
	{
		//reading stdout
		while(fgets(path,sizeof(path)-1, get_veths) != NULL)
		{

			//this will produce 'uny' from 'uny_X:'
			dev = strtok(path,"_");

			//this will produce the number (id) after 'uny_' without the colon
			dev = strtok(NULL,":");
//			g_print(dev);
			//we store them as gchars, since they can be easier handled in a
			//GSList*

			//adding found device numbers (ids) to a list
			device_numbers = g_slist_append(
										device_numbers,
										g_strdup(dev)
										);

		}
	}

	//close FILE
	pclose(get_veths);


	//getting the highest device number
	gint highestDevID = atoi(getHighestDeviceID(device_numbers));

	//the new device id needs to be increased with one
	highestDevID++;
	//this will be the first new id (Y > max(X))
	gchar *newDevID_1 = g_strdup_printf("%d",highestDevID);
	//the second device id also needs to be increased with one
	highestDevID++;
	//this will be the second new id for the new peer dev (Y' > Y)
	gchar *newDevID_2 = g_strdup_printf("%d",highestDevID);

	//assembling command
	//ip link add uny_Y type veth peer name uny_Y'
	gchar *command = g_strconcat(
								"ip link add uny_",
								newDevID_1,
								" type veth peer name uny_",
								newDevID_2,
								NULL);
	//for executing the command
//	custom_log(INFO, g_strdup_printf("command:%s\n\n", command));
	int status = system(command);

	//command was successfully executed
	if(status == 0)
	{
		//if everything went fine (return value of the command is 0)
		custom_log(INFO, g_strdup_printf("A new veth pair has been created: "
								 "(uny_%s - uny_%s)",
								 newDevID_1,
								 newDevID_2));

		//we can free up gchar* command, since we do not require it anymore
		g_free(command);

		//concatenating the return value, e.g., uny_1-uny_2
		gchar* veth_pair_as_char = g_strconcat("uny_",
												newDevID_1,
												"-uny_",
												newDevID_2,
												NULL);
		return veth_pair_as_char;
	}

	else if(status == 2 || status == 512)
	{
		//return value of the command is 2 or 512 -> operation not permitted
		custom_log(ERROR, "Operation not permitted! You must be ROOT!");
		return NULL;
	}
	else
	{
		//other return values are not being examined, just 'throw' an error

		custom_log(ERROR, "An error occurred during creating veth pairs!\n"
				  "Operation may not permitted - You must be ROOT!");

		return NULL;
	}

}
Example #25
0
gboolean
mcview_load (WView * view, const char *command, const char *file, int start_line,
             off_t search_start, off_t search_end)
{
    gboolean retval = FALSE;
    vfs_path_t *vpath = NULL;

#ifdef HAVE_ASSERT_H
    assert (view->bytes_per_line != 0);
#endif

    view->filename_vpath = vfs_path_from_str (file);

    /* get working dir */
    if (file != NULL && file[0] != '\0')
    {
        vfs_path_free (view->workdir_vpath);

        if (!g_path_is_absolute (file))
        {
            vfs_path_t *p;

            p = vfs_path_clone (vfs_get_raw_current_dir ());
            view->workdir_vpath = vfs_path_append_new (p, file, (char *) NULL);
            vfs_path_free (p);
        }
        else
        {
            /* try extract path from filename */
            const char *fname;
            char *dir;

            fname = x_basename (file);
            dir = g_strndup (file, (size_t) (fname - file));
            view->workdir_vpath = vfs_path_from_str (dir);
            g_free (dir);
        }
    }

    if (!mcview_is_in_panel (view))
        view->dpy_text_column = 0;

    mcview_set_codeset (view);

    if (command != NULL && (view->magic_mode || file == NULL || file[0] == '\0'))
        retval = mcview_load_command_output (view, command);
    else if (file != NULL && file[0] != '\0')
    {
        int fd;
        char tmp[BUF_MEDIUM];
        struct stat st;

        /* Open the file */
        vpath = vfs_path_from_str (file);
        fd = mc_open (vpath, O_RDONLY | O_NONBLOCK);
        if (fd == -1)
        {
            g_snprintf (tmp, sizeof (tmp), _("Cannot open \"%s\"\n%s"),
                        file, unix_error_string (errno));
            mcview_close_datasource (view);
            mcview_show_error (view, tmp);
            vfs_path_free (view->filename_vpath);
            view->filename_vpath = NULL;
            vfs_path_free (view->workdir_vpath);
            view->workdir_vpath = NULL;
            goto finish;
        }

        /* Make sure we are working with a regular file */
        if (mc_fstat (fd, &st) == -1)
        {
            mc_close (fd);
            g_snprintf (tmp, sizeof (tmp), _("Cannot stat \"%s\"\n%s"),
                        file, unix_error_string (errno));
            mcview_close_datasource (view);
            mcview_show_error (view, tmp);
            vfs_path_free (view->filename_vpath);
            view->filename_vpath = NULL;
            vfs_path_free (view->workdir_vpath);
            view->workdir_vpath = NULL;
            goto finish;
        }

        if (!S_ISREG (st.st_mode))
        {
            mc_close (fd);
            mcview_close_datasource (view);
            mcview_show_error (view, _("Cannot view: not a regular file"));
            vfs_path_free (view->filename_vpath);
            view->filename_vpath = NULL;
            vfs_path_free (view->workdir_vpath);
            view->workdir_vpath = NULL;
            goto finish;
        }

        if (st.st_size == 0 || mc_lseek (fd, 0, SEEK_SET) == -1)
        {
            /* Must be one of those nice files that grow (/proc) */
            mcview_set_datasource_vfs_pipe (view, fd);
        }
        else
        {
            if (view->magic_mode)
            {
                int type;

                type = get_compression_type (fd, file);

                if (type != COMPRESSION_NONE)
                {
                    char *tmp_filename;
                    vfs_path_t *vpath1;
                    int fd1;

                    tmp_filename = g_strconcat (file, decompress_extension (type), (char *) NULL);
                    vpath1 = vfs_path_from_str (tmp_filename);
                    g_free (tmp_filename);
                    fd1 = mc_open (vpath1, O_RDONLY | O_NONBLOCK);
                    vfs_path_free (vpath1);

                    if (fd1 == -1)
                    {
                        g_snprintf (tmp, sizeof (tmp), _("Cannot open \"%s\" in parse mode\n%s"),
                                    file, unix_error_string (errno));
                        mcview_close_datasource (view);
                        mcview_show_error (view, tmp);
                    }
                    else
                    {
                        mc_close (fd);
                        fd = fd1;
                        mc_fstat (fd, &st);
                    }
                }
            }

            mcview_set_datasource_file (view, fd, &st);
        }
        retval = TRUE;
    }

  finish:
    view->command = g_strdup (command);
    view->dpy_start = 0;
    view->dpy_paragraph_skip_lines = 0;
    mcview_state_machine_init (&view->dpy_state_top, 0);
    view->dpy_wrap_dirty = FALSE;
    view->force_max = -1;
    view->dpy_text_column = 0;

    mcview_compute_areas (view);
    mcview_update_bytes_per_line (view);

    if (mcview_remember_file_position && view->filename_vpath != NULL && start_line == 0)
    {
        long line, col;
        off_t new_offset, max_offset;

        load_file_position (view->filename_vpath, &line, &col, &new_offset, &view->saved_bookmarks);
        max_offset = mcview_get_filesize (view) - 1;
        if (max_offset < 0)
            new_offset = 0;
        else
            new_offset = MIN (new_offset, max_offset);
        if (!view->hex_mode)
        {
            view->dpy_start = mcview_bol (view, new_offset, 0);
            view->dpy_wrap_dirty = TRUE;
        }
        else
        {
            view->dpy_start = new_offset - new_offset % view->bytes_per_line;
            view->hex_cursor = new_offset;
        }
    }
    else if (start_line > 0)
        mcview_moveto (view, start_line - 1, 0);

    view->search_start = search_start;
    view->search_end = search_end;
    view->hexedit_lownibble = FALSE;
    view->hexview_in_text = FALSE;
    view->change_list = NULL;
    vfs_path_free (vpath);
    return retval;
}
Example #26
0
/*
 *     ---------------------- SYSTEM -------------------------
 * This function collects the ports and corresponding device ids of the given
 * switch
 * gchar* sw_id - id of the switch, e.g., s3
 * return GHashTable* - hashtable of the results ([port_num]=dev_id)
 */
GHashTable* getAllSwitchPorts(gchar* sw_id)
{
	//for storing all the device ids and the corresponding ports
	GHashTable *switch_ports_and_dev_ids =
			g_hash_table_new_full (g_str_hash, g_str_equal, g_free, g_free);

	//a line for stdout
	char path[100];

	//found ports and devices, e.g., 2(s3-eth2)
	gchar *ports_and_devices;

	//for running a command and reading its stdout
	FILE *get_ports_and_devices;

	//assembling the command
	//the corresponding line always consists of a mac address info, for instance
	//addr:46:be....., so we can grep 'addr' on the stdout.
	//The results will look like the following:
	//2(s3-eth2): addr:5a:42:6f:11:25:81
	//We can further use system calls for easing handling such as 'cut'
	gchar* command = g_strconcat(
								OVS_OFCTL_COMMAND,
								" show ",
								sw_id,
								"| grep addr|cut -d ':' -f 1",
								NULL);


	//run the command
	get_ports_and_devices = popen(command, "r");
	//This result, which must be parsed will look like this: 2(uny_X)

	//checking that command was run successfully
	if(get_ports_and_devices == NULL)
	{
		//error occurred during executing command
		custom_log(ERROR, g_strdup_printf("Failed to run command (%s)",command));

	}
	else
	{
		//command execution succeeded

		//reading stdout
		while(fgets(path,sizeof(path)-1, get_ports_and_devices) != NULL)
		{
			gchar* port;
			gchar* device_id;

			//tokenizing read line

			//this will produce '2' from '2(uny_X)'
			//this will produce 2
			ports_and_devices = strtok(path,"(");

			//duplicating variable
			port = g_strdup(ports_and_devices);

			//tokenize further
			//this will produce uny_X
			ports_and_devices = strtok(NULL,")");

			//storing uny_X in device_id
			device_id = g_strdup(ports_and_devices);

			//we need to remove the first whitespace character from port, so
			//here comes a trick with the tokenizer
			port = strtok(port," ");

//			g_print("port:%s\n", port);
//			g_print("dev_id:%s\n\n",device_id);

			//adding port and device ids to the hashtable
			add_string_element(switch_ports_and_dev_ids,
								g_strdup(device_id),
								g_strdup(port),
								TRUE);



		}
	}

	//close FILE
	pclose(get_ports_and_devices);
	//freeing gchar* command, since we do not need it anymore
	g_free(command);

	return switch_ports_and_dev_ids;
}
Example #27
0
/*!
 *\brief	Close and free preferences file
 *		Creates final file from temp, creates backup
 *
 *\param	pfile Preferences file struct
 *
 *\return	0 on success, -1 on failure
 */
gint prefs_file_close(PrefFile *pfile)
{
	FILE *fp, *orig_fp;
	gchar *path;
	gchar *tmppath;
	gchar *bakpath = NULL;
	gchar buf[BUFFSIZE];

	cm_return_val_if_fail(pfile != NULL, -1);

	fp = pfile->fp;
	orig_fp = pfile->orig_fp;
	path = pfile->path;

	if (!pfile->writing) {
		fclose(fp);
		g_free(pfile);
		g_free(path);
		return 0;
	}

	if (orig_fp) {
    		while (fgets(buf, sizeof(buf), orig_fp) != NULL) {
			/* next block */
			if (buf[0] == '[') {
				if (fputs(buf, fp)  == EOF) {
					g_warning("failed to write configuration to file");
					prefs_file_close_revert(pfile);
				
					return -1;
				}
				break;
			}
		}
		
		while (fgets(buf, sizeof(buf), orig_fp) != NULL)
			if (fputs(buf, fp) == EOF) {
				g_warning("failed to write configuration to file");
				prefs_file_close_revert(pfile);			
				
				return -1;
			}
		fclose(orig_fp);
	}

	tmppath = g_strconcat(path, ".tmp", NULL);

	
	if (prefs_common_get_flush_metadata() && fsync(fileno(fp)) < 0) {
		FILE_OP_ERROR(tmppath, "fsync");
		fclose(fp);
		claws_unlink(tmppath);
		g_free(path);
		g_free(tmppath);
		return -1;
	}

	if (fclose(fp) == EOF) {
		FILE_OP_ERROR(tmppath, "fclose");
		claws_unlink(tmppath);
		g_free(path);
		g_free(tmppath);
		return -1;
	}

	if (is_file_exist(path)) {
		bakpath = g_strconcat(path, ".bak", NULL);
#ifdef G_OS_WIN32
                claws_unlink(bakpath);
#endif
		if (g_rename(path, bakpath) < 0) {
			FILE_OP_ERROR(path, "rename");
			claws_unlink(tmppath);
			g_free(path);
			g_free(tmppath);
			g_free(bakpath);
			return -1;
		}
	}

#ifdef G_OS_WIN32
        claws_unlink(path);
#endif
	if (g_rename(tmppath, path) < 0) {
		FILE_OP_ERROR(tmppath, "rename");
		claws_unlink(tmppath);
		g_free(path);
		g_free(tmppath);
		g_free(bakpath);
		return -1;
	}

	g_free(pfile);
	g_free(path);
	g_free(tmppath);
	g_free(bakpath);
	return 0;
}
Example #28
0
/*
 * This procedure will gracefully stop a VNF
 * gchar vnf_id - the id of the vnf
 * return gboolean - TRUE if everythin went fine,
 * 					 FALSE if something went wrong
 */
gboolean stopVNF(gchar* vnf_id)
{
	log_error_bar();
	//getting the vnf
	vnf_data *found_vnf = getVNF(vnf_id);

	custom_log(INFO, g_strdup_printf("[VNF DATASTRUCTURE] Deleting all data of %s",
							  vnf_id));
	//clearing some simple variables - practical freeing will handled by GLIB
	//set the gchar* that holds vnf command to NULL
	found_vnf->vnf_command = NULL;
	custom_log(INFO, "\tCommand is deleted");


	//set the gchar* that holds vnf's control port to NULL
	found_vnf->control_port = NULL;
	custom_log(INFO, "\tControl port is deleted");

	//free the gchar* that holds vnf's control IP
	found_vnf->control_ip = NULL;
	custom_log(INFO, "\tControl IP is deleted");

	//removing interfaces and ports
	g_hash_table_foreach(found_vnf->links, (GHFunc)removeLink, NULL);
	//removing links
	g_hash_table_remove_all(found_vnf->links);
	//destroy hashtable
	g_hash_table_destroy(found_vnf->links);





	custom_log(INFO, "\tKilling VNF");
	//assembling killing command
	gchar* command = g_strconcat(
						"pkill -TERM -P ",
						g_strdup_printf("%d",found_vnf->pid),
						NULL);
	custom_log(LOG, g_strdup_printf("Kill command: %s", command));
	//killing process
//	int status = system(command);
	system(command);
	//checking whether kill was successful
	//DON'T KNOW WHY, BUT SYSTEM() RETURNS -1, BUT PROCESS TREE HAS BEEN
	//SUCCESSFULLY TERMINATED, THEREFORE THE FOLLOWING PART IS COMMENTED
//	if(status == 0)
//	{
//		custom_log(INFO, g_strdup_printf("VNF (pid: %d) was successfully killed!",
//						 	 	 	 	 found_vnf->pid));
//
//	}
//	else
//	{
//
//		custom_log(ERROR, g_strdup_printf("Error occurred during killing VNF (pid: %d)",
//						 	 	 	 	 found_vnf->pid));
//
//		//checking whether pid is real
//		if(status == 1 || status == 256)
//		{
//			//Process ID not found
//			custom_log(ERROR, g_strdup_printf("There is no PID like %d",found_vnf->pid));
//		}
//
//		//print return value
//		custom_log(ERROR, g_strdup_printf("Return value of pkill: %d", status));
//
//		return FALSE;
//	}

	//set the gchar* that holds vnf's PID to NULL
	found_vnf->pid = -1;


	//removing vnf datastructure from the main vnf hashtable
	removeVNF(vnf_id);

	return TRUE;

}
Example #29
0
int 
main (int argc, char *argv[]) 
{
	int err, i;
	GNOME_Pilot_Survival survive;
	GError *error;
	GList *pilots = NULL;
	GOptionContext *option_context;
        
	bindtextdomain (PACKAGE, GNOMELOCALEDIR);
	textdomain (PACKAGE);
	bind_textdomain_codeset (GETTEXT_PACKAGE, "UTF-8");

	if (argc<2) {
		g_message ("usage : %s [--now|--later] [--pilot PDA] [FILE ...]", argv[0]);
		exit (1);
	}

	option_context = g_option_context_new (PACKAGE);
	g_option_context_add_main_entries (option_context, options, NULL);
	if (!g_option_context_parse(option_context, &argc, &argv, &error)) {
		g_error (_("Error parsing commandline arguments: %s"), error->message);
		exit (1);
	}

	gtk_init (&argc, &argv);

	gpc = GNOME_PILOT_CLIENT (gnome_pilot_client_new ());
	g_object_ref_sink (G_OBJECT (gpc));
	g_signal_connect (G_OBJECT (gpc),"completed_request", G_CALLBACK(gpilotd_request_completed), NULL);
	gnome_pilot_client_connect_to_daemon (gpc);

	if (pilot_arg!=NULL) {
		pilots = g_list_append (pilots, g_strdup (pilot_arg));
	} else {
		err = gnome_pilot_client_get_pilots (gpc, &pilots);
		if (err !=GPILOTD_OK || pilots == NULL) {
			g_warning (_("Unable to get PDA names"));
			show_warning_dialog (_("Unable to get PDA names"));
			exit (1);
		}
	}

	notfailed = failed = handles = NULL;

	survive = GNOME_Pilot_IMMEDIATE;
	if (later) survive = GNOME_Pilot_PERSISTENT;
	
	i=0;

	while (filenames && filenames[i]!=NULL) {
		gint err;
		err = gnome_pilot_client_install_file (gpc,
						       pilots->data, /* get first pilot */
						       filenames[i],
						       survive,
						       0,
						       &handle);
		if (err == GPILOTD_OK) {
			handles = g_slist_prepend (handles,GINT_TO_POINTER(handle));
			notfailed = g_slist_prepend (notfailed, (void *) filenames[i]);
		} else {
			failed = g_slist_prepend (failed, (void *) filenames[i]);
		}
		i++;
	}

	if (!later) {
		gchar *message;
		
		message = NULL;
		if (failed != NULL) {
			GSList *e;
			message = g_strdup (_("Following files failed :\n"));
			for (e=failed;e;e = g_slist_next (e)) {
				gchar *tmp;
				tmp = g_strconcat (message,"\t- ", e->data,"\n", NULL);
				g_free (message);
				message = tmp;
			}
			g_slist_free (failed);
		}
		{
			GSList *e;
			if (message == NULL)
				message = g_strdup_printf (_("Installing to %s:\n"), (char*)pilots->data);
			else {
				gchar *tmp;
				tmp = g_strconcat (message,"\nInstalling to ", 
						   (char*)pilots->data, ":\n", NULL);
				g_free (message);
				message = tmp;
			}
			for (e=notfailed;e;e = g_slist_next (e)) {
				gchar *tmp;
				tmp = g_strconcat (message,"\t- ", e->data,"\n", NULL);
				g_free (message);
				message = tmp;
			}
			g_slist_free (notfailed);
		}
		{
			gchar *tmp;
			gchar *info;

			if (handles == NULL) 
				info = g_strdup (_("No files to install"));
			else {
				
				info = g_strdup (_("Press synchronize on the cradle to install\n" 
						  " or cancel the operation."));
                                err = gnome_pilot_client_conduit (gpc,
                                                            pilots->data,
                                                            "File",
                                                            GNOME_Pilot_CONDUIT_DEFAULT,
                                                            survive,
                                                            0,
                                                            &handle);
			}
						
			tmp = g_strconcat (message==NULL?"":message,
					  "\n",
					  info,
					  NULL);
			g_free (message);
			g_free (info);
			message = tmp;
		}
		dialog = gtk_message_dialog_new (NULL, GTK_DIALOG_MODAL,
		    GTK_MESSAGE_OTHER, GTK_BUTTONS_CANCEL, "%s",
		    message);
		gint response = gtk_dialog_run(GTK_DIALOG(dialog));
		if (dialog != NULL) /* if not destroyed by callback */
			gtk_widget_destroy(dialog);
		if (response == GTK_RESPONSE_CANCEL) {
			GSList *e;
			for (e=handles;e;e = g_slist_next (e)) {
				gnome_pilot_client_remove_request
				    (gpc,GPOINTER_TO_INT(e->data));  
			}
			g_slist_free (handles);
		}
		g_free (message);
	}

	g_object_unref (G_OBJECT (gpc));

	return 0;
}
Example #30
0
void
gncOwnerSetLotLinkMemo (Transaction *ll_txn)
{
    gchar *memo_prefix = _("Offset between documents: ");
    gchar *new_memo;
    SplitList *lts_iter;
    SplitList *splits = NULL, *siter;
    GList *titles = NULL, *titer;

    if (!ll_txn)
        return;

    if (xaccTransGetTxnType (ll_txn) != TXN_TYPE_LINK)
        return;

    // Find all splits in the lot link transaction that are also in a document lot
    for (lts_iter = xaccTransGetSplitList (ll_txn); lts_iter; lts_iter = lts_iter->next)
    {
        Split *split = lts_iter->data;
        GNCLot *lot;
        GncInvoice *invoice;
        gchar *title;

        if (!split)
            continue;

        lot = xaccSplitGetLot (split);
        if (!lot)
            continue;

        invoice = gncInvoiceGetInvoiceFromLot (lot);
        if (!invoice)
            continue;

        title = g_strdup_printf ("%s %s", gncInvoiceGetTypeString (invoice), gncInvoiceGetID (invoice));

        titles = g_list_insert_sorted (titles, title, (GCompareFunc)g_strcmp0);
        splits = g_list_prepend (splits, split); // splits don't need to be sorted
    }

    if (!titles)
        return; // We didn't find document lots

    // Create the memo as we'd want it to be
    new_memo = g_strconcat (memo_prefix, titles->data, NULL);
    for (titer = titles->next; titer; titer = titer->next)
    {
        gchar *tmp_memo = g_strconcat (new_memo, " - ", titer->data, NULL);
        g_free (new_memo);
        new_memo = tmp_memo;
    }
    g_list_free_full (titles, g_free);

    // Update the memos of all the splits we found previously (if needed)
    for (siter = splits; siter; siter = siter->next)
    {
        if (g_strcmp0 (xaccSplitGetMemo (siter->data), new_memo) != 0)
            xaccSplitSetMemo (siter->data, new_memo);
    }

    g_list_free (splits);
    g_free (new_memo);
}