ACC SHELL

Path : /usr/share/YaST2/clients/
File Upload :
Current File : //usr/share/YaST2/clients/webpin_package_search.ycp

/**
 * File:	webpin_package_search.ycp
 * Package:	YaST packager - Client using Webpin XML API
 * Authors:	Katarina Machalkova <kmachalkova@suse.cz>
 *		Lukas Ocilka <locilka@suse.cz>
 *
 * $Id: webpin_package_search.ycp 60001 2009-12-08 13:00:37Z kmachalkova $
 *
 * This client provides UI for searching for packages
 * via Webpin XML.
 * See http://en.opensuse.org/Package_Search/Design for the API.
 */


{
  textdomain "packager";

  import "Label";
  import "Popup";
  import "Progress";
  import "Sequencer";
  import "WebpinPackageSearch";
  import "Wizard";
  import "Directory";
  import "Map";
  import "Report";

  map <string, map > search_results = $[];
  map <string, map > all_selected = $[];

  boolean SomethingSelected() {
	return ( all_selected != $[]);
  }

  boolean AbortDialog() {
	 if (SomethingSelected())
	     return Popup::YesNo( _("All changes will be lost. Really exit?"));
	else
	    return true;
  }

  boolean Abort() {
    any ret = UI::PollInput();

    if (ret == `abort)
	return AbortDialog();
    else
	return false;
  }

  string SearchExpression() {
	string ret = (string) UI::QueryWidget(`id("search_text"), `Value);

	if (ret == "") {
	     Popup::Message(_("Search expression must not be empty!")); 
	     UI::SetFocus(`id("search_text"));
	}
	return ret;
  }

  map <string, boolean> SearchParameters() {
    list p = (list) UI::QueryWidget(`id("search_in"), `SelectedItems);

    map <string, boolean> ret = listmap ( string key, [ "name", "description", "contents" ], {
	    return $[ key : contains (p, key)];
	});
    //y2internal("%1", ret);
    return ret;
  }

  string CurrentTable() {
	string ctable = UI::WidgetExists(`id("results")) ? "results" : "all";

	return ctable;
  }

  void CreatePackageDescription( ) {
    string ctable = CurrentTable();
    string checksum = (string) UI::QueryWidget(`id( ctable ), `CurrentItem );

    map citem = (ctable == "results") ? search_results[checksum]:$[] : all_selected[checksum]:$[];
    string ret = "";

    if ( citem != $[] ) {
        string descr = sformat(_("<b>Repository URL:</b> %1<br>"), citem["repoURL"]:"");
        string version = sformat(_("<b>Version:</b> %1<br>"), citem["version"]:"");

	string archs = sformat(_("<b>Architecture:</b> %1<br>"), mergestring( citem["archs"]:[],","));
	ret = "<p>" + descr + version + archs + "</p>";
    }

     UI::ChangeWidget(`id("description"),`Value, ret);
  }

  list CreatePackageListItems( map<string, map> results ) {
    list pkg_items = [];

   foreach ( string iD, map pkg_line, results, {
// Webpin seems to return "ppc" arch even for some i386 packages (e.g., "joe")
	// doesn't match the architecture
//	if (! WebpinPackageSearch::MatchesCurrentArchitecture (it["archs"]:["noarch"])) {
//	    y2milestone ("Doesn't match the current arch: %1", it);
//	    return;
//	}

	pkg_items = add( pkg_items, `item(`id(iD),pkg_line["name"]:"" + " - " + pkg_line["summary"]:"" ));
    });
    return pkg_items;
  }

  void PopulatePackageList( map <string, map> results ) {
	list items = CreatePackageListItems( results );
	string ctable = CurrentTable();

	list <string> IDs = (list <string> ) toset(Map::Keys(results));
	list <string> wantedIDs = (list <string>) toset(Map::Keys(all_selected));
	y2milestone("Package IDs: %1, previously selected: %2", IDs, wantedIDs);

	if (results != nil) {
	    UI::ChangeWidget(`id(ctable), `Items, items);

	    if(ctable == "all")
	        UI::ChangeWidget(`id(ctable), `SelectedItems, wantedIDs);
	    else
		UI::ChangeWidget(`id(ctable), `SelectedItems, multiset::intersection(IDs, wantedIDs)); 

	    UI::SetFocus(`id(ctable));
	}
	else
	    UI::SetFocus(`id("search_text"));

  }

  list <map> SelectedPackages() {
	list < map > result = [];
 
	foreach ( string s, map m, all_selected, {
	    result = add(result, m);
	});

	y2milestone("Passing these data to WebPin %1", result);
	return result;
  }

  void AddItemIfNotExists( string checksum, map data ) {
	if (!haskey (all_selected, checksum))
	    all_selected[checksum] = data;
  }

  void RemoveItemIfExists( string checksum ) {
	if ( haskey (all_selected, checksum) )
	    all_selected = remove(all_selected, checksum);
  }

  void UpdateSelectedPkgs(){

	string ctable = CurrentTable();
        list <string> selected_items =  toset((list <string>) UI::QueryWidget(`id(ctable), `SelectedItems));
        list <string> other_items = [];

        list <term> tt = (list <term>) UI::QueryWidget(`id(ctable), `Items);
        foreach(term t, tt, {
             string tmp = argsof(argsof(t)[0]:`none())[0]:"";
             if( !contains(selected_items, tmp) )
                 other_items = add (other_items, tmp);
        });

        other_items = toset(other_items);

        if (ctable == "results")
	{
	    foreach(string it, selected_items, {
		AddItemIfNotExists( it, search_results[it]:$[] );
	    });
	}
	foreach(string it, other_items, {
		RemoveItemIfExists( it );
	});


       y2milestone("Selecting these packages: %1", all_selected );

  }

  symbol ReadDialog() {
    list <string> steps = [
	_("Check Network Configuration"),
	_("Initialize Package Manager")
    ];

    list <string> actions = [
	_("Checking Network Configuration ..."),
	_("Initializing Package Manager ... ")
    ];

    Progress::New(
	_("Reading Package Search Setup..."),
	" ",
	size(steps),
	steps,
	actions,
	_("<p>Please wait while packager is initializing...</p>")
     );

     Progress::NextStage();
     if (Abort()) return `abort;
     sleep(100);

     Progress::NextStage();
     if (Abort()) return `abort;
     sleep(100);

     Progress::Finish();
     return `next;
  }

  symbol MainDialog() {

  term current_search_box = `MultiSelectionBox(`id ("results"), `opt (`notify, `hstretch),
                                                "", [] );
  term all_pkgs_box =       `MultiSelectionBox(`id ("all"), `opt (`notify, `hstretch),
                                                "", [] );

  Wizard::SetContents (
            // TRANSLATORS: dialog caption
            _("Package Search"),
            `VBox (
                `HBox (
		    `VBox(
                        `HBox(
		            `Bottom(`InputField (`id ("search_text"), `opt (`hstretch), _("Search &Expression"))),
                            // TRANSLATORS: push button
			    `HSpacing(1),
                            `Bottom(`PushButton (`id ("search"),  `opt(`default), _("&Search")))
		        ),
			`VStretch()
		    ),
		    `MultiSelectionBox(
		        `id("search_in"),
		       _("Search &In"),
		       [
			`item( `id("name"),_("Name"), true ),
			`item( `id("description"), _("Description"), true ),
			`item( `id("contents"), _("Contents"))
			]
		     )//,
                ),
				//`RadioButtonGroup(
		//    `id(`rb),
		//    `VBox(
		//        `Left(`Label( _("Search Repositories"))),
		//        `Frame( "",
		//	    `VBox(
		//                `Left(`RadioButton(`id("current_product"),_("Current product") ) ),
		//                `Left(`RadioButton(`id("factory"),_("Factory") ) ),
		//                `VStretch()
		//	    )
		//         )
		//    )
		//)
	    //)
		//),
                `VWeight (
                    2,
		    `DumbTab(`id("tab_bar"),
			[ `item(`id("search_tab"), _("&Found Packages"), true),
			  `item(`id("all_tab"), _("&All Selected Packages"))
			],
			`ReplacePoint(`id(`rp), current_search_box)
		    )
                ),
		//`HBox(
		    `Left( `Label( _("Package Description")) ),
		    //`HStretch(),
		    //`CheckBox(_("Keep Package Repositories Subscribed"), true)
		//),
		`VWeight(
		    1,
		    `RichText(`id("description"), "")
		)
	    ),
	    _("<p><big><b>Package Search</b></big><br>
This YaST module enables you to use the functionality of <i>Webpin package search</i>.
It searches within all known openSUSE build-service and openSUSE community repositories.</p>") +

_("<p><big><b>Security</b></big><br>
The software found is often not part of the distribution itself and the level of trust
depends on yourself. We do not take any responsibility for installing
such software.</p>
"),
	    //We don't need back button
	    false,
	    true
    );

    Wizard::SetTitleIcon ("yast-webpin");
    Wizard::SetAbortButton (`cancel, Label::CancelButton());

    UI::SetFocus(`id("search_text"));


    any dialog_ret = nil;
    while (true) {
	dialog_ret = UI::UserInput();

	if ( dialog_ret != "results" && dialog_ret != "all")
	    UpdateSelectedPkgs();

	if (dialog_ret == `next){
	    string temporary_xml = Directory::tmpdir + "/one_click_install_temporary_file.xml";

	    list <map> selected_packages = SelectedPackages();

	    if (selected_packages == nil || size (selected_packages) == 0) {
		Report::Message (_("Select some packages to install."));
		UI::SetFocus(`id("results"));
		continue;
	    }

	    WebpinPackageSearch::PrepareOneClickInstallDescription (selected_packages, temporary_xml);

	    any oci = WFM::CallFunction ("OneClickInstallUI", [temporary_xml]);
	    y2milestone ("OneClickInstallUI returned: %1", oci);
	    break;
	}
	else if (dialog_ret == "search") {

	    UI::ChangeWidget(`id("tab_bar"), `CurrentItem, "search_tab");
	    UI::ReplaceWidget(`id(`rp), current_search_box );
	    string search_expr = SearchExpression();

	    if (search_expr != "") {
		map <string, boolean> search_params =  SearchParameters();
		Popup::ShowFeedback("", _("Searching for packages..."));
	        list <map> tmp_results =
		    WebpinPackageSearch::SearchForPackages(
	                search_expr,
	                nil,
	                search_params
	        );
		search_results = listmap( map m, tmp_results, {
		    return $[ m["checksum"]:"" : m ];
		});
		Popup::ClearFeedback();
		PopulatePackageList( search_results );

    		if ( search_results == $[] || search_results == nil )
		    UI::ChangeWidget(`id("description"), `Value, _("<p><b>No packages matching entered criteria were found</b></p>"));
		else
		    CreatePackageDescription();
	    }
	    continue;
	}
	else if (dialog_ret == "search_tab") {
	    UI::ReplaceWidget(`id(`rp), current_search_box );
	    PopulatePackageList( search_results ); 
	    CreatePackageDescription();
	}
	else if (dialog_ret == "all_tab") {
	    UI::ReplaceWidget(`id(`rp), all_pkgs_box );
	    PopulatePackageList( all_selected );
	    CreatePackageDescription();
	}
	else if ( dialog_ret == "results" || dialog_ret == "all") {
	    CreatePackageDescription();
	}
	else if (dialog_ret == `abort || dialog_ret == `cancel) {
	    if (AbortDialog()) {
		dialog_ret = `abort;
		y2milestone ("Aborting...");
		break;
	    }
	}
	else {
	    y2error ("Unknown ret: %1", dialog_ret);
	}
    }
    return (symbol) dialog_ret;

  }
  
  symbol MainSequence () {
        map aliases = $[
            "read"      : ``( ReadDialog() ),
            "main"   : ``( MainDialog() ),
//	    "write"   : ``(WriteDialog())
        ];

        map sequence = $[
            "ws_start"  : "read",
            "read"      : $[
                `next   : "main",
                `abort  : `abort,
            ],
            "main"   : $[
                `abort  : `abort,
		`next	: `next
            ],
//	    "write" : $[
//		`abort : `abort,
//		`next  : `next
//	    ],
        ];

	any seq_ret = Sequencer::Run( aliases, sequence );

	return (symbol) seq_ret;
  }


  Wizard::CreateDialog();

  symbol client_ret = MainSequence();

  Wizard::CloseDialog();

  return client_ret;

}

ACC SHELL 2018