diff --git a/.clang-format b/.clang-format new file mode 100644 index 0000000..5491ed9 --- /dev/null +++ b/.clang-format @@ -0,0 +1,562 @@ +# SPDX-License-Identifier: GPL-2.0 +# +# clang-format configuration file. Intended for clang-format >= 4. +# +# For more information, see: +# +# Documentation/process/clang-format.rst +# https://clang.llvm.org/docs/ClangFormat.html +# https://clang.llvm.org/docs/ClangFormatStyleOptions.html +# +--- +AccessModifierOffset: -8 +AlignAfterOpenBracket: Align +AlignConsecutiveAssignments: false +AlignConsecutiveDeclarations: false +#AlignEscapedNewlines: Left # Unknown to clang-format-4.0 +AlignOperands: true +AlignTrailingComments: false +AllowAllParametersOfDeclarationOnNextLine: false +AllowShortBlocksOnASingleLine: false +AllowShortCaseLabelsOnASingleLine: false +AllowShortFunctionsOnASingleLine: None +AllowShortIfStatementsOnASingleLine: false +AllowShortLoopsOnASingleLine: false +AlwaysBreakAfterDefinitionReturnType: None +AlwaysBreakAfterReturnType: None +AlwaysBreakBeforeMultilineStrings: false +AlwaysBreakTemplateDeclarations: false +BinPackArguments: true +BinPackParameters: true +BraceWrapping: + AfterClass: false + AfterControlStatement: false + AfterEnum: false + AfterFunction: true + AfterNamespace: true + AfterObjCDeclaration: false + AfterStruct: false + AfterUnion: false + #AfterExternBlock: false # Unknown to clang-format-5.0 + BeforeCatch: false + BeforeElse: false + IndentBraces: false + #SplitEmptyFunction: true # Unknown to clang-format-4.0 + #SplitEmptyRecord: true # Unknown to clang-format-4.0 + #SplitEmptyNamespace: true # Unknown to clang-format-4.0 +BreakBeforeBinaryOperators: None +BreakBeforeBraces: Custom +#BreakBeforeInheritanceComma: false # Unknown to clang-format-4.0 +BreakBeforeTernaryOperators: false +BreakConstructorInitializersBeforeComma: false +#BreakConstructorInitializers: BeforeComma # Unknown to clang-format-4.0 +BreakAfterJavaFieldAnnotations: false +BreakStringLiterals: false +ColumnLimit: 120 +CommentPragmas: '^ IWYU pragma:' +#CompactNamespaces: false # Unknown to clang-format-4.0 +ConstructorInitializerAllOnOneLineOrOnePerLine: false +ConstructorInitializerIndentWidth: 8 +ContinuationIndentWidth: 8 +Cpp11BracedListStyle: false +DerivePointerAlignment: false +DisableFormat: false +ExperimentalAutoDetectBinPacking: false +#FixNamespaceComments: false # Unknown to clang-format-4.0 + +# Taken from: +# git grep -h '^#define [^[:space:]]*for_each[^[:space:]]*(' include/ \ +# | sed "s,^#define \([^[:space:]]*for_each[^[:space:]]*\)(.*$, - '\1'," \ +# | sort | uniq +ForEachMacros: + - 'apei_estatus_for_each_section' + - 'ata_for_each_dev' + - 'ata_for_each_link' + - '__ata_qc_for_each' + - 'ata_qc_for_each' + - 'ata_qc_for_each_raw' + - 'ata_qc_for_each_with_internal' + - 'ax25_for_each' + - 'ax25_uid_for_each' + - '__bio_for_each_bvec' + - 'bio_for_each_bvec' + - 'bio_for_each_bvec_all' + - 'bio_for_each_integrity_vec' + - '__bio_for_each_segment' + - 'bio_for_each_segment' + - 'bio_for_each_segment_all' + - 'bio_list_for_each' + - 'bip_for_each_vec' + - 'bitmap_for_each_clear_region' + - 'bitmap_for_each_set_region' + - 'blkg_for_each_descendant_post' + - 'blkg_for_each_descendant_pre' + - 'blk_queue_for_each_rl' + - 'bond_for_each_slave' + - 'bond_for_each_slave_rcu' + - 'bpf_for_each_spilled_reg' + - 'btree_for_each_safe128' + - 'btree_for_each_safe32' + - 'btree_for_each_safe64' + - 'btree_for_each_safel' + - 'card_for_each_dev' + - 'cgroup_taskset_for_each' + - 'cgroup_taskset_for_each_leader' + - 'cpufreq_for_each_entry' + - 'cpufreq_for_each_entry_idx' + - 'cpufreq_for_each_valid_entry' + - 'cpufreq_for_each_valid_entry_idx' + - 'css_for_each_child' + - 'css_for_each_descendant_post' + - 'css_for_each_descendant_pre' + - 'device_for_each_child_node' + - 'displayid_iter_for_each' + - 'dma_fence_chain_for_each' + - 'do_for_each_ftrace_op' + - 'drm_atomic_crtc_for_each_plane' + - 'drm_atomic_crtc_state_for_each_plane' + - 'drm_atomic_crtc_state_for_each_plane_state' + - 'drm_atomic_for_each_plane_damage' + - 'drm_client_for_each_connector_iter' + - 'drm_client_for_each_modeset' + - 'drm_connector_for_each_possible_encoder' + - 'drm_for_each_bridge_in_chain' + - 'drm_for_each_connector_iter' + - 'drm_for_each_crtc' + - 'drm_for_each_crtc_reverse' + - 'drm_for_each_encoder' + - 'drm_for_each_encoder_mask' + - 'drm_for_each_fb' + - 'drm_for_each_legacy_plane' + - 'drm_for_each_plane' + - 'drm_for_each_plane_mask' + - 'drm_for_each_privobj' + - 'drm_mm_for_each_hole' + - 'drm_mm_for_each_node' + - 'drm_mm_for_each_node_in_range' + - 'drm_mm_for_each_node_safe' + - 'flow_action_for_each' + - 'for_each_acpi_dev_match' + - 'for_each_active_dev_scope' + - 'for_each_active_drhd_unit' + - 'for_each_active_iommu' + - 'for_each_aggr_pgid' + - 'for_each_available_child_of_node' + - 'for_each_bio' + - 'for_each_board_func_rsrc' + - 'for_each_bvec' + - 'for_each_card_auxs' + - 'for_each_card_auxs_safe' + - 'for_each_card_components' + - 'for_each_card_dapms' + - 'for_each_card_pre_auxs' + - 'for_each_card_prelinks' + - 'for_each_card_rtds' + - 'for_each_card_rtds_safe' + - 'for_each_card_widgets' + - 'for_each_card_widgets_safe' + - 'for_each_cgroup_storage_type' + - 'for_each_child_of_node' + - 'for_each_clear_bit' + - 'for_each_clear_bit_from' + - 'for_each_cmsghdr' + - 'for_each_compatible_node' + - 'for_each_component_dais' + - 'for_each_component_dais_safe' + - 'for_each_comp_order' + - 'for_each_console' + - 'for_each_cpu' + - 'for_each_cpu_and' + - 'for_each_cpu_not' + - 'for_each_cpu_wrap' + - 'for_each_dapm_widgets' + - 'for_each_dev_addr' + - 'for_each_dev_scope' + - 'for_each_dma_cap_mask' + - 'for_each_dpcm_be' + - 'for_each_dpcm_be_rollback' + - 'for_each_dpcm_be_safe' + - 'for_each_dpcm_fe' + - 'for_each_drhd_unit' + - 'for_each_dss_dev' + - 'for_each_dtpm_table' + - 'for_each_efi_memory_desc' + - 'for_each_efi_memory_desc_in_map' + - 'for_each_element' + - 'for_each_element_extid' + - 'for_each_element_id' + - 'for_each_endpoint_of_node' + - 'for_each_evictable_lru' + - 'for_each_fib6_node_rt_rcu' + - 'for_each_fib6_walker_rt' + - 'for_each_free_mem_pfn_range_in_zone' + - 'for_each_free_mem_pfn_range_in_zone_from' + - 'for_each_free_mem_range' + - 'for_each_free_mem_range_reverse' + - 'for_each_func_rsrc' + - 'for_each_hstate' + - 'for_each_if' + - 'for_each_iommu' + - 'for_each_ip_tunnel_rcu' + - 'for_each_irq_nr' + - 'for_each_link_codecs' + - 'for_each_link_cpus' + - 'for_each_link_platforms' + - 'for_each_lru' + - 'for_each_matching_node' + - 'for_each_matching_node_and_match' + - 'for_each_member' + - 'for_each_memcg_cache_index' + - 'for_each_mem_pfn_range' + - '__for_each_mem_range' + - 'for_each_mem_range' + - '__for_each_mem_range_rev' + - 'for_each_mem_range_rev' + - 'for_each_mem_region' + - 'for_each_migratetype_order' + - 'for_each_msi_entry' + - 'for_each_msi_entry_safe' + - 'for_each_msi_vector' + - 'for_each_net' + - 'for_each_net_continue_reverse' + - 'for_each_netdev' + - 'for_each_netdev_continue' + - 'for_each_netdev_continue_rcu' + - 'for_each_netdev_continue_reverse' + - 'for_each_netdev_feature' + - 'for_each_netdev_in_bond_rcu' + - 'for_each_netdev_rcu' + - 'for_each_netdev_reverse' + - 'for_each_netdev_safe' + - 'for_each_net_rcu' + - 'for_each_new_connector_in_state' + - 'for_each_new_crtc_in_state' + - 'for_each_new_mst_mgr_in_state' + - 'for_each_new_plane_in_state' + - 'for_each_new_private_obj_in_state' + - 'for_each_node' + - 'for_each_node_by_name' + - 'for_each_node_by_type' + - 'for_each_node_mask' + - 'for_each_node_state' + - 'for_each_node_with_cpus' + - 'for_each_node_with_property' + - 'for_each_nonreserved_multicast_dest_pgid' + - 'for_each_of_allnodes' + - 'for_each_of_allnodes_from' + - 'for_each_of_cpu_node' + - 'for_each_of_pci_range' + - 'for_each_old_connector_in_state' + - 'for_each_old_crtc_in_state' + - 'for_each_old_mst_mgr_in_state' + - 'for_each_oldnew_connector_in_state' + - 'for_each_oldnew_crtc_in_state' + - 'for_each_oldnew_mst_mgr_in_state' + - 'for_each_oldnew_plane_in_state' + - 'for_each_oldnew_plane_in_state_reverse' + - 'for_each_oldnew_private_obj_in_state' + - 'for_each_old_plane_in_state' + - 'for_each_old_private_obj_in_state' + - 'for_each_online_cpu' + - 'for_each_online_node' + - 'for_each_online_pgdat' + - 'for_each_pci_bridge' + - 'for_each_pci_dev' + - 'for_each_pci_msi_entry' + - 'for_each_pcm_streams' + - 'for_each_physmem_range' + - 'for_each_populated_zone' + - 'for_each_possible_cpu' + - 'for_each_present_cpu' + - 'for_each_prime_number' + - 'for_each_prime_number_from' + - 'for_each_process' + - 'for_each_process_thread' + - 'for_each_prop_codec_conf' + - 'for_each_prop_dai_codec' + - 'for_each_prop_dai_cpu' + - 'for_each_prop_dlc_codecs' + - 'for_each_prop_dlc_cpus' + - 'for_each_prop_dlc_platforms' + - 'for_each_property_of_node' + - 'for_each_registered_fb' + - 'for_each_requested_gpio' + - 'for_each_requested_gpio_in_range' + - 'for_each_reserved_mem_range' + - 'for_each_reserved_mem_region' + - 'for_each_rtd_codec_dais' + - 'for_each_rtd_components' + - 'for_each_rtd_cpu_dais' + - 'for_each_rtd_dais' + - 'for_each_set_bit' + - 'for_each_set_bit_from' + - 'for_each_set_clump8' + - 'for_each_sg' + - 'for_each_sg_dma_page' + - 'for_each_sg_page' + - 'for_each_sgtable_dma_page' + - 'for_each_sgtable_dma_sg' + - 'for_each_sgtable_page' + - 'for_each_sgtable_sg' + - 'for_each_sibling_event' + - 'for_each_subelement' + - 'for_each_subelement_extid' + - 'for_each_subelement_id' + - '__for_each_thread' + - 'for_each_thread' + - 'for_each_unicast_dest_pgid' + - 'for_each_vsi' + - 'for_each_wakeup_source' + - 'for_each_zone' + - 'for_each_zone_zonelist' + - 'for_each_zone_zonelist_nodemask' + - 'fwnode_for_each_available_child_node' + - 'fwnode_for_each_child_node' + - 'fwnode_graph_for_each_endpoint' + - 'gadget_for_each_ep' + - 'genradix_for_each' + - 'genradix_for_each_from' + - 'hash_for_each' + - 'hash_for_each_possible' + - 'hash_for_each_possible_rcu' + - 'hash_for_each_possible_rcu_notrace' + - 'hash_for_each_possible_safe' + - 'hash_for_each_rcu' + - 'hash_for_each_safe' + - 'hctx_for_each_ctx' + - 'hlist_bl_for_each_entry' + - 'hlist_bl_for_each_entry_rcu' + - 'hlist_bl_for_each_entry_safe' + - 'hlist_for_each' + - 'hlist_for_each_entry' + - 'hlist_for_each_entry_continue' + - 'hlist_for_each_entry_continue_rcu' + - 'hlist_for_each_entry_continue_rcu_bh' + - 'hlist_for_each_entry_from' + - 'hlist_for_each_entry_from_rcu' + - 'hlist_for_each_entry_rcu' + - 'hlist_for_each_entry_rcu_bh' + - 'hlist_for_each_entry_rcu_notrace' + - 'hlist_for_each_entry_safe' + - 'hlist_for_each_entry_srcu' + - '__hlist_for_each_rcu' + - 'hlist_for_each_safe' + - 'hlist_nulls_for_each_entry' + - 'hlist_nulls_for_each_entry_from' + - 'hlist_nulls_for_each_entry_rcu' + - 'hlist_nulls_for_each_entry_safe' + - 'i3c_bus_for_each_i2cdev' + - 'i3c_bus_for_each_i3cdev' + - 'ide_host_for_each_port' + - 'ide_port_for_each_dev' + - 'ide_port_for_each_present_dev' + - 'idr_for_each_entry' + - 'idr_for_each_entry_continue' + - 'idr_for_each_entry_continue_ul' + - 'idr_for_each_entry_ul' + - 'in_dev_for_each_ifa_rcu' + - 'in_dev_for_each_ifa_rtnl' + - 'inet_bind_bucket_for_each' + - 'inet_lhash2_for_each_icsk_rcu' + - 'key_for_each' + - 'key_for_each_safe' + - 'klp_for_each_func' + - 'klp_for_each_func_safe' + - 'klp_for_each_func_static' + - 'klp_for_each_object' + - 'klp_for_each_object_safe' + - 'klp_for_each_object_static' + - 'kunit_suite_for_each_test_case' + - 'kvm_for_each_memslot' + - 'kvm_for_each_vcpu' + - 'list_for_each' + - 'list_for_each_codec' + - 'list_for_each_codec_safe' + - 'list_for_each_continue' + - 'list_for_each_entry' + - 'list_for_each_entry_continue' + - 'list_for_each_entry_continue_rcu' + - 'list_for_each_entry_continue_reverse' + - 'list_for_each_entry_from' + - 'list_for_each_entry_from_rcu' + - 'list_for_each_entry_from_reverse' + - 'list_for_each_entry_lockless' + - 'list_for_each_entry_rcu' + - 'list_for_each_entry_reverse' + - 'list_for_each_entry_safe' + - 'list_for_each_entry_safe_continue' + - 'list_for_each_entry_safe_from' + - 'list_for_each_entry_safe_reverse' + - 'list_for_each_entry_srcu' + - 'list_for_each_prev' + - 'list_for_each_prev_safe' + - 'list_for_each_safe' + - 'llist_for_each' + - 'llist_for_each_entry' + - 'llist_for_each_entry_safe' + - 'llist_for_each_safe' + - 'mci_for_each_dimm' + - 'media_device_for_each_entity' + - 'media_device_for_each_intf' + - 'media_device_for_each_link' + - 'media_device_for_each_pad' + - 'nanddev_io_for_each_page' + - 'netdev_for_each_lower_dev' + - 'netdev_for_each_lower_private' + - 'netdev_for_each_lower_private_rcu' + - 'netdev_for_each_mc_addr' + - 'netdev_for_each_uc_addr' + - 'netdev_for_each_upper_dev_rcu' + - 'netdev_hw_addr_list_for_each' + - 'nft_rule_for_each_expr' + - 'nla_for_each_attr' + - 'nla_for_each_nested' + - 'nlmsg_for_each_attr' + - 'nlmsg_for_each_msg' + - 'nr_neigh_for_each' + - 'nr_neigh_for_each_safe' + - 'nr_node_for_each' + - 'nr_node_for_each_safe' + - 'of_for_each_phandle' + - 'of_property_for_each_string' + - 'of_property_for_each_u32' + - 'pci_bus_for_each_resource' + - 'pcl_for_each_chunk' + - 'pcl_for_each_segment' + - 'pcm_for_each_format' + - 'ping_portaddr_for_each_entry' + - 'plist_for_each' + - 'plist_for_each_continue' + - 'plist_for_each_entry' + - 'plist_for_each_entry_continue' + - 'plist_for_each_entry_safe' + - 'plist_for_each_safe' + - 'pnp_for_each_card' + - 'pnp_for_each_dev' + - 'protocol_for_each_card' + - 'protocol_for_each_dev' + - 'queue_for_each_hw_ctx' + - 'radix_tree_for_each_slot' + - 'radix_tree_for_each_tagged' + - 'rb_for_each' + - 'rbtree_postorder_for_each_entry_safe' + - 'rdma_for_each_block' + - 'rdma_for_each_port' + - 'rdma_umem_for_each_dma_block' + - 'resource_list_for_each_entry' + - 'resource_list_for_each_entry_safe' + - 'rhl_for_each_entry_rcu' + - 'rhl_for_each_rcu' + - 'rht_for_each' + - 'rht_for_each_entry' + - 'rht_for_each_entry_from' + - 'rht_for_each_entry_rcu' + - 'rht_for_each_entry_rcu_from' + - 'rht_for_each_entry_safe' + - 'rht_for_each_from' + - 'rht_for_each_rcu' + - 'rht_for_each_rcu_from' + - '__rq_for_each_bio' + - 'rq_for_each_bvec' + - 'rq_for_each_segment' + - 'scsi_for_each_prot_sg' + - 'scsi_for_each_sg' + - 'sctp_for_each_hentry' + - 'sctp_skb_for_each' + - 'shdma_for_each_chan' + - '__shost_for_each_device' + - 'shost_for_each_device' + - 'sk_for_each' + - 'sk_for_each_bound' + - 'sk_for_each_entry_offset_rcu' + - 'sk_for_each_from' + - 'sk_for_each_rcu' + - 'sk_for_each_safe' + - 'sk_nulls_for_each' + - 'sk_nulls_for_each_from' + - 'sk_nulls_for_each_rcu' + - 'snd_array_for_each' + - 'snd_pcm_group_for_each_entry' + - 'snd_soc_dapm_widget_for_each_path' + - 'snd_soc_dapm_widget_for_each_path_safe' + - 'snd_soc_dapm_widget_for_each_sink_path' + - 'snd_soc_dapm_widget_for_each_source_path' + - 'tb_property_for_each' + - 'tcf_exts_for_each_action' + - 'udp_portaddr_for_each_entry' + - 'udp_portaddr_for_each_entry_rcu' + - 'usb_hub_for_each_child' + - 'v4l2_device_for_each_subdev' + - 'v4l2_m2m_for_each_dst_buf' + - 'v4l2_m2m_for_each_dst_buf_safe' + - 'v4l2_m2m_for_each_src_buf' + - 'v4l2_m2m_for_each_src_buf_safe' + - 'virtio_device_for_each_vq' + - 'while_for_each_ftrace_op' + - 'xa_for_each' + - 'xa_for_each_marked' + - 'xa_for_each_range' + - 'xa_for_each_start' + - 'xas_for_each' + - 'xas_for_each_conflict' + - 'xas_for_each_marked' + - 'xbc_array_for_each_value' + - 'xbc_for_each_key_value' + - 'xbc_node_for_each_array_value' + - 'xbc_node_for_each_child' + - 'xbc_node_for_each_key_value' + - 'zorro_for_each_dev' + +#IncludeBlocks: Preserve # Unknown to clang-format-5.0 +IncludeCategories: + - Regex: '.*' + Priority: 1 +IncludeIsMainRegex: '(Test)?$' +IndentCaseLabels: false +#IndentPPDirectives: None # Unknown to clang-format-5.0 +IndentWidth: 8 +IndentWrappedFunctionNames: false +JavaScriptQuotes: Leave +JavaScriptWrapImports: true +KeepEmptyLinesAtTheStartOfBlocks: false +MacroBlockBegin: '' +MacroBlockEnd: '' +MaxEmptyLinesToKeep: 1 +NamespaceIndentation: None +#ObjCBinPackProtocolList: Auto # Unknown to clang-format-5.0 +ObjCBlockIndentWidth: 8 +ObjCSpaceAfterProperty: true +ObjCSpaceBeforeProtocolList: true + +# Taken from git's rules +#PenaltyBreakAssignment: 10 # Unknown to clang-format-4.0 +PenaltyBreakBeforeFirstCallParameter: 30 +PenaltyBreakComment: 10 +PenaltyBreakFirstLessLess: 0 +PenaltyBreakString: 10 +PenaltyExcessCharacter: 100 +PenaltyReturnTypeOnItsOwnLine: 60 + +PointerAlignment: Right +ReflowComments: false +SortIncludes: false +#SortUsingDeclarations: false # Unknown to clang-format-4.0 +SpaceAfterCStyleCast: false +SpaceAfterTemplateKeyword: true +SpaceBeforeAssignmentOperators: true +#SpaceBeforeCtorInitializerColon: true # Unknown to clang-format-5.0 +#SpaceBeforeInheritanceColon: true # Unknown to clang-format-5.0 +SpaceBeforeParens: ControlStatements +#SpaceBeforeRangeBasedForLoopColon: true # Unknown to clang-format-5.0 +SpaceInEmptyParentheses: false +SpacesBeforeTrailingComments: 1 +SpacesInAngles: false +SpacesInContainerLiterals: false +SpacesInCStyleCastParentheses: false +SpacesInParentheses: false +SpacesInSquareBrackets: false +Standard: Cpp03 +TabWidth: 8 +UseTab: Always +... + diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..bd1b99c --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +.qmake.stash +Makefile +moc_* +*.o +selectdefaultapplication diff --git a/.vscode/c_cpp_properties.json b/.vscode/c_cpp_properties.json new file mode 100644 index 0000000..3956680 --- /dev/null +++ b/.vscode/c_cpp_properties.json @@ -0,0 +1,29 @@ +{ + "configurations": [ + { + "name": "Linux", + "includePath": [ + "${workspaceFolder}/**", + "/usr/include/qt6/QtCore", + "/usr/include/qt6", + "/usr/include/qt6/QtWidgets", + "/usr/include/qt6/QtGui" + ], + "defines": [], + "compilerPath": "/usr/bin/clang", + "cStandard": "c17", + "cppStandard": "c++20", + "intelliSenseMode": "linux-clang-x64", + "compilerArgs": [], + "mergeConfigurations": false, + "browse": { + "path": [ + "${workspaceFolder}/**", + "/usr/include/qt6/QtCore" + ], + "limitSymbolsToIncludedHeaders": true + } + } + ], + "version": 4 +} diff --git a/COPYING b/COPYING index 70190fb..d159169 100644 --- a/COPYING +++ b/COPYING @@ -1,12 +1,12 @@ - GNU GENERAL PUBLIC LICENSE - Version 2, June 1991 + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 - Copyright (C) 1989, 1991 Free Software Foundation, Inc. - 51 Franklin Steet, Fifth Floor, Boston, MA 02111-1307 USA + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. - Preamble + Preamble The licenses for most software are designed to take away your freedom to share and change it. By contrast, the GNU General Public @@ -15,7 +15,7 @@ software--to make sure the software is free for all its users. This General Public License applies to most of the Free Software Foundation's software and to any other program whose authors commit to using it. (Some other Free Software Foundation software is covered by -the GNU Library General Public License instead.) You can apply it to +the GNU Lesser General Public License instead.) You can apply it to your programs, too. When we speak of free software, we are referring to freedom, not @@ -55,8 +55,8 @@ patent must be licensed for everyone's free use or not licensed at all. The precise terms and conditions for copying, distribution and modification follow. - - GNU GENERAL PUBLIC LICENSE + + GNU GENERAL PUBLIC LICENSE TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 0. This License applies to any program or other work which contains @@ -110,7 +110,7 @@ above, provided that you also meet all of these conditions: License. (Exception: if the Program itself is interactive but does not normally print such an announcement, your work based on the Program is not required to print an announcement.) - + These requirements apply to the modified work as a whole. If identifiable sections of that work are not derived from the Program, and can be reasonably considered independent and separate works in @@ -168,7 +168,7 @@ access to copy from a designated place, then offering equivalent access to copy the source code from the same place counts as distribution of the source code, even though third parties are not compelled to copy the source along with the object code. - + 4. You may not copy, modify, sublicense, or distribute the Program except as expressly provided under this License. Any attempt otherwise to copy, modify, sublicense or distribute the Program is @@ -225,7 +225,7 @@ impose that choice. This section is intended to make thoroughly clear what is believed to be a consequence of the rest of this License. - + 8. If the distribution and/or use of the Program is restricted in certain countries either by patents or by copyrighted interfaces, the original copyright holder who places the Program under this License @@ -255,7 +255,7 @@ make exceptions for this. Our decision will be guided by the two goals of preserving the free status of all derivatives of our free software and of promoting the sharing and reuse of software generally. - NO WARRANTY + NO WARRANTY 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN @@ -277,9 +277,9 @@ YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. - END OF TERMS AND CONDITIONS - - How to Apply These Terms to Your New Programs + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it @@ -303,10 +303,9 @@ the "copyright" line and a pointer to where the full notice is found. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. - You should have received a copy of the GNU General Public License - along with this program; if not, write to the Free Software - Foundation, Inc., 51 Franklin Steet, Fifth Floor, Boston, MA 02111-1307 USA - + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. Also add information on how to contact you by electronic and paper mail. @@ -336,5 +335,5 @@ necessary. Here is a sample; alter the names: This General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the -library. If this is what you want to do, use the GNU Library General +library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. diff --git a/README.md b/README.md index 5d19b7d..ce60d5e 100644 --- a/README.md +++ b/README.md @@ -1,23 +1,26 @@ -Select Default Application -========================== +# Select Default Application A very simple application that lets you define default applications on Linux in a sane way. ![screenshot](/screenshot.png) - -How it works ------------- +## How it works Basically it just loads all installed applications by reading their .desktop files, reads the MimeType fields to see what it supports, and updates ~/.config/mimeapps.list with what the user wants. +## Links + +- https://specifications.freedesktop.org/mime-apps-spec/mime-apps-spec-latest.html +- https://specifications.freedesktop.org/desktop-entry-spec/desktop-entry-spec-latest.html +- https://specifications.freedesktop.org/shared-mime-info-spec/shared-mime-info-spec-latest.html -Links ------ +## Building - * https://specifications.freedesktop.org/mime-apps-spec/mime-apps-spec-latest.html - * https://specifications.freedesktop.org/desktop-entry-spec/desktop-entry-spec-latest.html - * https://specifications.freedesktop.org/shared-mime-info-spec/shared-mime-info-spec-latest.html +Just run +``` +qmake +make +``` \ No newline at end of file diff --git a/main.cpp b/main.cpp index 90b6d53..5495440 100644 --- a/main.cpp +++ b/main.cpp @@ -1,11 +1,29 @@ -#include "widget.h" +#include "selectdefaultapplication.h" #include +#include int main(int argc, char *argv[]) { - QApplication a(argc, argv); - Widget w; - w.show(); + QApplication::setAttribute(Qt::AA_EnableHighDpiScaling); - return a.exec(); + QApplication a(argc, argv); + a.setApplicationVersion("2.0"); + a.setApplicationDisplayName("Select Default Application"); + + QCommandLineParser parser; + parser.setApplicationDescription( + "A very simple application that lets you define default applications on Linux in a sane way."); + parser.addHelpOption(); + parser.addVersionOption(); + QCommandLineOption verbose(QStringList() << "V" + << "verbose", + "Print verbose information about how the desktop files are parsed"); + + parser.addOption(verbose); + parser.process(a); + + SelectDefaultApplication w(nullptr, parser.isSet(verbose)); + w.show(); + + return a.exec(); } diff --git a/selectdefaultapplication.cpp b/selectdefaultapplication.cpp new file mode 100644 index 0000000..d0cd348 --- /dev/null +++ b/selectdefaultapplication.cpp @@ -0,0 +1,679 @@ +#include "selectdefaultapplication.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +SelectDefaultApplication::SelectDefaultApplication(QWidget *parent, bool isVerbose) + : QWidget(parent), isVerbose(isVerbose) +{ + readCurrentDefaultMimetypes(); + for (const QString &dirPath : QStandardPaths::standardLocations(QStandardPaths::ApplicationsLocation)) { + qDebug() << "Loading applications from" << dirPath; + QDir applicationsDir(dirPath); + + for (const QFileInfo &file : applicationsDir.entryInfoList(QStringList("*.desktop"))) { + loadDesktopFile(file); + } + } + + // Preload icons up front, so it doesn't get sluggish when selecting applications + // supporting a lot + const QIcon unknownIcon = QIcon::fromTheme("unknown"); + + // TODO: check if QT_QPA_PLATFORMTHEME is set to plasma or sandsmark, + // if so just use the functioning QIcon::fromTheme() + // We do this manually because non-Plasma-platforms icon loading is extremely + // slow (I blame GTK and its crappy icon cache) + for (const QString &searchPath : (QIcon::themeSearchPaths() + QIcon::fallbackSearchPaths())) { + loadIcons(searchPath + QIcon::themeName()); + loadIcons(searchPath); + } + + // Set m_mimeTypeIcons[mimetypeName] to an appropriate icon + for (const QHash &application_associations : m_apps.values()) { + for (const QString &mimetypeName : application_associations.keys()) { + if (m_mimeTypeIcons.contains(mimetypeName)) { + continue; + } + // Here we actually want to use the real mimetype, because we need to access its iconName + const QMimeType mimetype = m_mimeDb.mimeTypeForName(mimetypeName); + + QString iconName = mimetype.iconName(); + QIcon icon(m_iconPaths.value(iconName)); + if (!icon.isNull()) { + m_mimeTypeIcons[mimetypeName] = icon; + continue; + } + icon = QIcon(m_iconPaths.value(mimetype.genericIconName())); + if (!icon.isNull()) { + m_mimeTypeIcons[mimetypeName] = icon; + continue; + } + int split = iconName.lastIndexOf('+'); + if (split != -1) { + iconName.truncate(split); + icon = QIcon(m_iconPaths.value(iconName)); + if (!icon.isNull()) { + m_mimeTypeIcons[mimetypeName] = icon; + continue; + } + } + split = iconName.lastIndexOf('-'); + if (split != -1) { + iconName.truncate(split); + icon = QIcon(m_iconPaths.value(iconName)); + if (!icon.isNull()) { + m_mimeTypeIcons[mimetypeName] = icon; + continue; + } + } + icon = QIcon(m_iconPaths.value(mimetype.genericIconName())); + if (!icon.isNull()) { + m_mimeTypeIcons[mimetypeName] = icon; + continue; + } + + m_mimeTypeIcons[mimetypeName] = unknownIcon; + } + } + + // The rest of this constructor sets up the GUI + // Left section + m_applicationList = new QListWidget; + m_applicationList->setSelectionMode(QAbstractItemView::SingleSelection); + populateApplicationList(""); + + m_searchBox = new QLineEdit; + m_searchBox->setPlaceholderText(tr("Search for Application")); + + m_groupChooser = new QPushButton; + m_groupChooser->setText(tr("All")); + + m_mimegroupMenu = new QMenu(m_groupChooser); + m_mimegroupMenu->addAction(tr("All")); + QStringList sorted_mimegroups = m_mimegroups.values(); + sorted_mimegroups.sort(); + for (const QString &mimegroup : sorted_mimegroups) { + m_mimegroupMenu->addAction(mimegroup); + } + m_groupChooser->setMenu(m_mimegroupMenu); + + QHBoxLayout *filterHolder = new QHBoxLayout; + filterHolder->addWidget(m_searchBox); + filterHolder->addWidget(m_groupChooser); + + QVBoxLayout *leftLayout = new QVBoxLayout; + leftLayout->addLayout(filterHolder); + leftLayout->addWidget(m_applicationList); + + // Middle section + m_middleBanner = new QLabel(tr("Select an application to see its defaults.")); + + m_mimetypeList = new QListWidget; + m_mimetypeList->setSelectionMode(QAbstractItemView::MultiSelection); + + m_setDefaultButton = new QPushButton(); + m_setDefaultButton->setText(tr("Set as default application for these file types")); + m_setDefaultButton->setEnabled(false); + + QVBoxLayout *middleLayout = new QVBoxLayout; + middleLayout->addWidget(m_middleBanner); + middleLayout->addWidget(m_mimetypeList); + middleLayout->addWidget(m_setDefaultButton); + + // Right section + m_rightBanner = new QLabel(""); + + m_infoButton = new QToolButton(); + m_infoButton->setText("?"); + + QHBoxLayout *infoHolder = new QHBoxLayout; + infoHolder->addWidget(m_rightBanner); + infoHolder->addWidget(m_infoButton); + + m_currentDefaultApps = new QListWidget; + m_currentDefaultApps->setSelectionMode(QAbstractItemView::NoSelection); + + QVBoxLayout *rightLayout = new QVBoxLayout; + rightLayout->addLayout(infoHolder); + rightLayout->addWidget(m_currentDefaultApps); + + // Main layout and connections + QHBoxLayout *mainLayout = new QHBoxLayout; + setLayout(mainLayout); + mainLayout->addLayout(leftLayout); + mainLayout->addLayout(middleLayout); + mainLayout->addLayout(rightLayout); + + connect(m_applicationList, &QListWidget::itemSelectionChanged, this, + &SelectDefaultApplication::onApplicationSelected); + connect(m_mimetypeList, &QListWidget::itemActivated, this, &SelectDefaultApplication::enableSetDefaultButton); + connect(m_setDefaultButton, &QPushButton::clicked, this, &SelectDefaultApplication::onSetDefaultClicked); + connect(m_infoButton, &QToolButton::clicked, this, &SelectDefaultApplication::showHelp); + connect(m_searchBox, &QLineEdit::textEdited, this, &SelectDefaultApplication::populateApplicationList); + connect(m_mimegroupMenu, &QMenu::triggered, this, &SelectDefaultApplication::constrictGroup); +} + +SelectDefaultApplication::~SelectDefaultApplication() +{ +} + +/** + * Populates the middle and right side of the screen. + * Selects all the mimetypes that application can natively support for the middle, and all currently selected for right + * Filters mimetypes based on if they start with m_filterMimegroup + * Extra function is needed for Qt slots, which is in turn needed to stop the screen from flashing, which is unfortunate + */ +void SelectDefaultApplication::onApplicationSelected() +{ + onApplicationSelectedLogic(true); +} +void SelectDefaultApplication::onApplicationSelectedLogic(bool allowEnabled) +{ + m_setDefaultButton->setEnabled(false); + m_mimetypeList->clear(); + + QList selectedItems = m_applicationList->selectedItems(); + if (selectedItems.count() != 1) { + return; + } + + const QListWidgetItem *item = selectedItems.first(); + const QString appName = item->data(0).toString(); + + // Set banners and right widget + m_middleBanner->setText(appName + tr(" can open:")); + m_rightBanner->setText(appName + tr(" currently opens:")); + m_currentDefaultApps->clear(); + for (QString &mimetype : m_defaultApps.keys(appName)) { + addToMimetypeList(m_currentDefaultApps, mimetype, false); + } + + const QHash &officiallySupported = m_apps.value(appName); + + // E. g. kwrite and kate only indicate support for "text/plain", but they're nice for things like C source files. + QSet impliedSupported; + for (const QString &mimetype : officiallySupported.keys()) { + for (const QString &child : m_childMimeTypes.values(mimetype)) { + // Ensure that the officially supported keys don't contain this value + if (!officiallySupported.contains(child)) { + impliedSupported.insert(child); + } + } + } + + for (const QString &mimetype : officiallySupported.keys()) { + if (mimetype.startsWith(m_filterMimegroup)) { + addToMimetypeList(m_mimetypeList, mimetype, true); + } + } + for (const QString &mimetype : impliedSupported) { + if (mimetype.startsWith(m_filterMimegroup)) { + addToMimetypeList(m_mimetypeList, mimetype, false); + } + } + + m_setDefaultButton->setEnabled(allowEnabled && m_mimetypeList->count() > 0); +} +void SelectDefaultApplication::addToMimetypeList(QListWidget *list, const QString &mimetypeName, const bool selected) +{ + QString description = mimetypeDescription(mimetypeName); + QListWidgetItem *item = new QListWidgetItem(description); + item->setData(Qt::UserRole, mimetypeName); + item->setIcon(m_mimeTypeIcons[mimetypeName]); + list->addItem(item); + item->setSelected(selected); +} + +void SelectDefaultApplication::onSetDefaultClicked() +{ + QList selectedItems = m_applicationList->selectedItems(); + if (selectedItems.count() != 1) { + return; + } + + const QListWidgetItem *item = selectedItems.first(); + + const QString application = item->data(0).toString(); + if (application.isEmpty()) { + return; + } + + QSet unselected; + QSet selected; + for (int i = 0; i < m_mimetypeList->count(); i++) { + QListWidgetItem *item = m_mimetypeList->item(i); + const QString name = item->data(Qt::UserRole).toString(); + if (item->isSelected()) { + selected.insert(name); + } else { + unselected.insert(name); + } + } + + setDefault(application, selected); +} + +void SelectDefaultApplication::loadDesktopFile(const QFileInfo &fileInfo) +{ + // Ugliest implementation of .desktop file reading ever + + QFile file(fileInfo.absoluteFilePath()); + if (!file.open(QIODevice::ReadOnly)) { + qWarning() << "Error: Failed to open" << fileInfo.fileName(); + return; + } + + // The filename of the desktop file + const QString &appFile = fileInfo.fileName(); + // The mimetypes the application can support + QStringList mimetypes; + // The name of the application in its desktop entry + // Used as the primary key with which associations are made + QString appName; + // The name of the icon as given in the desktop entry + QString appIcon; + + while (!file.atEnd()) { + // Removes all runs of whitespace, but won't make `Name=` and `Name =` the same + QString line = file.readLine().simplified(); + + if (line.startsWith('[')) { + if (line == "[Desktop Entry]") { + continue; + } + // Multiple groups may not have the same name, and [Desktop Entry] must be the first group. So we are done otherwise + break; + } else { + // Trim the strings because the '=' can be padded with spaces because FreeDesktop is stupid, even though not a single desktop file on my computer uses that + const QString key = line.section('=', 0, 0).trimmed(); + const QString value = line.section('=', 1).trimmed(); + + if (key == "Name") { + appName = value; + } else if (key == "MimeType") { + mimetypes = value.split(';', Qt::SkipEmptyParts); + } else if (key == "Icon") { + appIcon = value; + } + // Else ignore the key + } + } + + if (!appIcon.isEmpty() && m_applicationIcons[appFile].isEmpty()) { + m_applicationIcons[appName] = appIcon; + } + // Even if mimetypes is empty, set the icon in case a different one isn't + if (mimetypes.isEmpty()) { + return; + } + + // Note that this program is the one that can edit some files from the defaults, if it is + if (m_defaultDesktopEntries.contains(appFile)) { + for (QString &mimetype : m_defaultDesktopEntries.values(appFile)) { + m_defaultApps[mimetype] = appName; + } + } + + for (const QString &readMimeName : mimetypes) { + // Resolve aliases etc + QString mimetypeName = wrapperMimeTypeForName(readMimeName); + if (mimetypeName == "") { + // An invalid QMimeType returns "" for .name(), so if it occurs then we should ignore it + if (isVerbose) { + qDebug() << "In file " << appName << " mimetype " << readMimeName + << " is invalid. Ignoring..."; + } + continue; + } + + // Create a database of mimetypes this application is a child of + // So applications that can edit parent mimetypes can also have associations formed to their child mimetypes + // Unless the parent is 'application/octet-stream' because I guess a lot of stuff has that as its parent + // Example: Kate editing text/plain can edit C source code + const QMimeType mimetype = m_mimeDb.mimeTypeForName(readMimeName.trimmed()); + // if !mimetype.isValid() this just won't enter the loop + for (const QString &parent : mimetype.parentMimeTypes()) { + if (parent == "application/octet-stream") { + break; + } + m_childMimeTypes.insert(parent, mimetypeName); + } + + if (mimetypeName.count('/') != 1) { + qWarning() << "Warning: encountered mimetype " << mimetypeName + << " without exactly 1 '/' character in " << appFile + << " Unsure what to do, skipping..."; + continue; + } + // Now that we've checked this, we can get the mimegroup and add it to the global list + const QString mimegroup = mimetypeName.section('/', 0, 0); + m_mimegroups.insert(mimegroup); + + // Indexing in Qt creates a default element if one doesn't exist, so we don't need to explicitely check if m_apps[appName] exists + // If we've already got an association for this app from a different desktop file, don't overwrite it because we read highest-priority .desktops first + if (m_apps[appName].contains(mimetypeName)) { + // Annoyingly, some apps like KDE mobile apps add associations for *the same exact file type* through two different aliases, so this gets spammed a lot. + if (isVerbose) { + qDebug() << "Debug: " << appName << " already handles " << mimetypeName << " with " + << m_apps[appName][mimetypeName] << " so " << appFile << "will be ignored"; + } + continue; + } + m_apps[appName][mimetypeName] = appFile; + } +} + +// Removes values from mimetypes if warnings exist and the user requests to do a non-destructive change +void SelectDefaultApplication::setDefault(const QString &appName, QSet &mimetypes) +{ + const QString filePath = + QDir(QStandardPaths::writableLocation(QStandardPaths::ConfigLocation)).absoluteFilePath("mimeapps.list"); + QFile file(filePath); + + // Read in existing mimeapps.list, skipping the lines for the mimetypes we're updating + QList existingContent; + QList existingAssociations; + QHash warnings; + if (file.open(QIODevice::ReadOnly)) { + bool inCorrectGroup = false; + while (!file.atEnd()) { + const QByteArray line = file.readLine().trimmed(); + + if (line.isEmpty()) { + continue; + } + + if (line.startsWith('[')) { + inCorrectGroup = (line == "[Default Applications]"); + if (!inCorrectGroup) { + existingContent.append(line); + } + continue; + } + + if (!inCorrectGroup) { + existingContent.append(line); + continue; + } + + if (!line.contains('=')) { + existingAssociations.append(line); + continue; + } + + const QString mimetype = wrapperMimeTypeForName(line.split('=').first().trimmed()); + // If we aren't setting this mimetype, leave any entry, even others that this application owns + if (!mimetypes.contains(mimetype)) { + existingAssociations.append(line); + continue; + } + + // Ensure that if a mimetype is selected and is set as default for a different application, we warn about it + const QString handlingAppFile = line.split('=')[1].trimmed(); + const QString appFile = m_apps[appName].value(mimetype); + if (appFile != handlingAppFile && m_apps[appName].contains(mimetype)) { + warnings[mimetype] = handlingAppFile; + } + } + + file.close(); + } else { + qWarning() << "Unable to open file for reading" << file.errorString(); + // TODO If we can't open the file for reading, we better stop before opening for writing and deleting it + } + + // Display warnings and get user confirmation that we should proceed + if (!warnings.isEmpty()) { + overwriteConfirm confirm = getOverwriteConfirmation(warnings); + if (confirm == CANCEL_CHANGES) { + return; + } + if (confirm == NON_DESTRUCTIVE) { + for (QString warningType : warnings.keys()) { + // Add to existing associations + const QString warning = warningType + '=' + warnings[warningType]; + existingAssociations.append(warning.toUtf8()); + // Remove from values to set + mimetypes.remove(warningType); + } + } + } + + // Write the file + if (!file.open(QIODevice::WriteOnly)) { + QMessageBox::warning(this, tr("Failed to store settings"), file.errorString()); + return; + } + + for (const QByteArray &line : existingContent) { + file.write(line + '\n'); + } + file.write("\n[Default Applications]\n"); + for (const QByteArray &line : existingAssociations) { + file.write(line + '\n'); + } + + for (const QString &mimetype : mimetypes) { + const QString &appFile = m_apps[appName][mimetype]; + file.write(QString(mimetype + '=' + appFile + '\n').toUtf8()); + if (isVerbose) { + qDebug() << "Writing setting: " << mimetype << "=" + << "appFile"; + } + // Update UI also + m_defaultApps[mimetype] = appName; + } + + // Redraw and make the button unclickable so there is always user feedback + onApplicationSelectedLogic(false); +} + +void SelectDefaultApplication::readCurrentDefaultMimetypes() +{ + const QString filePath = + QDir(QStandardPaths::writableLocation(QStandardPaths::ConfigLocation)).absoluteFilePath("mimeapps.list"); + QFile file(filePath); + + // Read in existing mimeapps.list, skipping the lines for the mimetypes we're updating + if (file.open(QIODevice::ReadOnly)) { + bool inCorrectGroup = false; + while (!file.atEnd()) { + const QByteArray line = file.readLine().trimmed(); + + if (line.isEmpty()) { + continue; + } + + if (line.startsWith('[')) { + inCorrectGroup = (line == "[Default Applications]"); + continue; + } + + if (!inCorrectGroup) { + continue; + } + + if (!line.contains('=')) { + continue; + } + + const QString mimetype = wrapperMimeTypeForName(line.split('=').first().trimmed()); + const QString appFile = line.split('=')[1]; + m_defaultDesktopEntries.insert(appFile, mimetype); + } + + file.close(); + } else { + qWarning() << "Unable to open file for reading" << file.errorString(); + } +} + +void SelectDefaultApplication::populateApplicationList(const QString &filter) +{ + // Clear the list in case we are updating it (i.e. performing a search) + m_applicationList->clear(); + + // Filter entries based on the filter string + QStringList applications = m_apps.keys().filter(filter, Qt::CaseInsensitive); + // Iterate over the array, removing elements who have no desktop entries which can handle the correct mimetype + for (QStringList::size_type i = applications.size(); i--;) { + if (!applicationHasAnyCorrectMimetype(applications[i])) { + applications.removeAt(i); + } + } + + // Sort the remaining applications + applications.sort(); + + // Add each application to the left panel + for (const QString &appName : applications) { + QListWidgetItem *app = new QListWidgetItem(appName); + app->setIcon(QIcon::fromTheme(m_applicationIcons[appName])); + m_applicationList->addItem(app); + app->setSelected(false); + } +} + +void SelectDefaultApplication::loadIcons(const QString &path) +{ + QFileInfo icon_file(path); + if (!icon_file.exists() || !icon_file.isDir()) { + return; + } + // TODO: avoid hardcoding + QStringList imageTypes({ "*.svg", "*.svgz", "*.png", "*.xpm" }); + QDirIterator iter(path, imageTypes, QDir::Files, QDirIterator::Subdirectories); + + while (iter.hasNext()) { + iter.next(); + icon_file = iter.fileInfo(); + + const QString name = icon_file.completeBaseName(); + if (m_iconPaths.contains(name)) { + continue; + } + m_iconPaths[name] = icon_file.filePath(); + } +} + +void SelectDefaultApplication::constrictGroup(QAction *action) +{ + m_groupChooser->setText(action->text()); + m_filterMimegroup = (action->text() == tr("All")) ? "" : action->text(); + m_searchBox->clear(); + populateApplicationList(""); + onApplicationSelected(); +} + +void SelectDefaultApplication::enableSetDefaultButton() +{ + m_setDefaultButton->setEnabled(true); +} + +void SelectDefaultApplication::showHelp() +{ + QMessageBox *dialog = new QMessageBox(this); + dialog->setText(tr("Help about Select Default Application")); + dialog->setInformativeText(tr( + "To use this program, select any applications on the left panel.\n" + "Then select or deselect any mimetypes in the center that you want this application to open. Most of the time, you can leave this at the defaults; it will choose all the mimetypes the application has explicit support for.\n" + "Finally, press at the bottom of the screen to make the highlighted mimetypes open with the selected application by default.\n" + "You can see your changes on the right. Any application that you have configured will report it there.\n" + "---------------------------------------------------------------------------------------\n" + "Explanation of how this works: A FreeDesktop has Desktop Entries (.desktop files) in several locations; /usr/share/applications/, /usr/local/share/applications/, and ~/.local/share/applications/ by default.\n" + "These desktop entries tell application launchers how to run programs, including the tool 'xdg-open' which is the standard tool to open files and URLs.\n" + "xdg-open reads Desktop Entries in an unpredictable order in order to determine what application to handle that file; it uses the `MimeType` key present in a Desktop Entry to determine this.\n" + "There is also a user configuration file, `~/.config/mimeapps.list`, which it reads first and gives higher precedence.\n" + "This program parses all the Desktop Entries on the system, as well as the `mimeapps.list`, to determine what programs exist and which are set as defaults.\n" + "Then, when you click to 'set as default for these filetypes', it reads `mimeapps.list`, and sets the keys you have highlighted to the new values.\n")); + dialog->exec(); +} + +overwriteConfirm SelectDefaultApplication::getOverwriteConfirmation(const QHash &warnings) +{ + QMessageBox *dialog = new QMessageBox(this); + dialog->setText(tr("Changing will overwrite existing configuration:")); + + QString conflicts = ""; + for (QString warningType : warnings.keys()) { + conflicts += warningType + tr(" is opened by ") + warnings[warningType] + '\n'; + } + dialog->setInformativeText(conflicts); + + // We're sort of abusing the roles here + dialog->addButton("Overwrite settings", QMessageBox::ApplyRole); + dialog->addButton("Add non-conflicting rules", QMessageBox::AcceptRole); + dialog->addButton("Cancel all changes", QMessageBox::RejectRole); + // Because of forementioned abuse, make sure the code works at compile time + static_assert(QMessageBox::ApplyRole != QMessageBox::AcceptRole, "Collision in QMessageBox return types!"); + + int prompt = dialog->exec(); + // if (QMessageBox::ApplyRole == prompt) { // For some god-forsaken reason exec returns 1 and not its actual role, unsure how to ensure this is correct at compile-time + if (0 == prompt) { + return OVERWRITE_ALL; + // if (QMessageBox::AcceptRole == prompt) { // For some god-forsaken reason exec returns 1 and not its actual role + } else if (1 == prompt) { + return NON_DESTRUCTIVE; + } + return CANCEL_CHANGES; +} + +bool SelectDefaultApplication::applicationHasAnyCorrectMimetype(const QString &appName) +{ + for (QString appFile : m_apps[appName].keys()) { + if (appFile.startsWith(m_filterMimegroup)) { + return true; + } + } + return false; +} + +const char *X_SCHEME_HANDLER = "x-scheme-handler/"; +// Returns the value of m_mimeDb.mimeTypeForName(name) but +// mimeTypeForName(application/x-pkcs12) always returns application/x-pkcs12 instead of application/pkcs12 +// If starts with x-scheme-handler, instead just returns the argument +const QString SelectDefaultApplication::wrapperMimeTypeForName(const QString &name) { + if (name.startsWith(X_SCHEME_HANDLER)) { + // x-scheme-handler is not a valid mimetype for a file, but we do want to be able to set applications as the default handlers for it. + // Assumes all x-scheme-handler/* is valid + return name; + } + const QMimeType mimetype = m_mimeDb.mimeTypeForName(name); + QString mimetypeName = mimetype.name(); + // There appears to be a bug in Qt https://bugreports.qt.io/browse/QTBUG-99509, hack around it + if (mimetypeName == "application/pkcs12") { + mimetypeName = "application/x-pkcs12"; + } + return mimetypeName; +} + +const QString SelectDefaultApplication::mimetypeDescription(QString name) { + if (name.startsWith(X_SCHEME_HANDLER)) { + // x-scheme-handler is not a valid mimetype for a file, but we do want to be able to set applications as the default handlers for it. + // Assumes all x-scheme-handler/* is valid + return "Handles " + name.mid(strlen(X_SCHEME_HANDLER)) + ":// URIs\n" + name; + } + // There appears to be a bug in Qt https://bugreports.qt.io/browse/QTBUG-99509, hack around it + if (name == "application/pkcs12") { + name = "application/x-pkcs12"; + } + const QMimeType mimetype = m_mimeDb.mimeTypeForName(name); + QString desc = mimetype.filterString().trimmed(); + if (desc.isEmpty()) { + desc = mimetype.comment().trimmed(); + } + if (!desc.isEmpty()) { + desc += '\n'; + } + return desc + name; +} diff --git a/selectdefaultapplication.h b/selectdefaultapplication.h new file mode 100644 index 0000000..f8de738 --- /dev/null +++ b/selectdefaultapplication.h @@ -0,0 +1,92 @@ +#ifndef WIDGET_H +#define WIDGET_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +class QFileInfo; +class QTreeWidget; +class QListWidget; +class QPushButton; + +enum overwriteConfirm { + NON_DESTRUCTIVE, + OVERWRITE_ALL, + CANCEL_CHANGES, +}; + +class SelectDefaultApplication : public QWidget { + Q_OBJECT + +public: + SelectDefaultApplication(QWidget *parent, bool isVerbose); + ~SelectDefaultApplication(); + +private slots: + void onApplicationSelected(); + void onSetDefaultClicked(); + void populateApplicationList(const QString &filter); + void showHelp(); + void constrictGroup(QAction *action); + void enableSetDefaultButton(); + +private: + void loadDesktopFile(const QFileInfo &fileInfo); + void setDefault(const QString &appName, QSet &mimetypes); + void loadIcons(const QString &path); + void addToMimetypeList(QListWidget *list, const QString &mimetypeName, const bool selected); + void readCurrentDefaultMimetypes(); + bool applicationHasAnyCorrectMimetype(const QString &appName); + void onApplicationSelectedLogic(bool allowEnable); + const QString wrapperMimeTypeForName(const QString &name); + overwriteConfirm getOverwriteConfirmation(const QHash &warnings); + const QString mimetypeDescription(QString name); + + // Hashtable of application names to hashtables of mimetypes to .desktop file entries + QHash > m_apps; + // Hashtable of application names to icons + QHash m_applicationIcons; + // Multi-hashtable with keys as parent mime types and values as all children of that mimetype which are encountered + QMultiHash m_childMimeTypes; + + // Set containing all the mimegroups we saw + QSet m_mimegroups; + // Global variable to match selected mimegroup on + QString m_filterMimegroup; + // Multi-hashtable with keys as mimetypes and values as application names + QHash m_defaultApps; + // Multi-hashtable with keys as .desktop files and values as mimetypes, read from mimeapps.list + // Note this is opposite how they are actually stored. It is done this way so that we can read mimeapps.list before + // parsing anything else and then as we loop over all .desktop files, fill up the associations between programs and + // mimetypes. Remains constant after startup + QMultiHash m_defaultDesktopEntries; + + bool isVerbose; + + // for preloading icons, because that's (a bit) slooow + QHash m_mimeTypeIcons; + QHash m_iconPaths; + + QMimeDatabase m_mimeDb; + + // UI elements + QListWidget *m_applicationList; + QListWidget *m_mimetypeList; + QListWidget *m_currentDefaultApps; + QLineEdit *m_searchBox; + QPushButton *m_groupChooser; + QMenu *m_mimegroupMenu; + QPushButton *m_setDefaultButton; + QToolButton *m_infoButton; + QLabel *m_middleBanner; + QLabel *m_rightBanner; +}; + +#endif // WIDGET_H diff --git a/selectdefaultapplication.pro b/selectdefaultapplication.pro index 41558db..8657030 100644 --- a/selectdefaultapplication.pro +++ b/selectdefaultapplication.pro @@ -22,10 +22,9 @@ DEFINES += QT_DEPRECATED_WARNINGS # You can also select to disable deprecated APIs only up to a certain version of Qt. #DEFINES += QT_DISABLE_DEPRECATED_BEFORE=0x060000 # disables all the APIs deprecated before Qt 6.0.0 - SOURCES += \ main.cpp \ - widget.cpp + selectdefaultapplication.cpp HEADERS += \ - widget.h + selectdefaultapplication.h diff --git a/widget.cpp b/widget.cpp deleted file mode 100644 index ef3c3f6..0000000 --- a/widget.cpp +++ /dev/null @@ -1,435 +0,0 @@ -#include "widget.h" -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -Widget::Widget(QWidget *parent) - : QWidget(parent) -{ - for (const QString &dirPath : QStandardPaths::standardLocations(QStandardPaths::ApplicationsLocation)) { - qDebug() << "Loading applications from" << dirPath; - QDir applicationsDir(dirPath); - - for (const QFileInfo &file : applicationsDir.entryInfoList(QStringList("*.desktop"))) { - loadDesktopFile(file); - } - } - - // Check that we shit with multiple .desktop files, but some nodisplay files - for (const QString &appId : m_supportedMimetypes.keys()) { - if (!m_desktopFileNames.contains(appId)) { - qWarning() << appId << "does not have an associated desktop file!"; - continue; - } - - if (m_applicationNames[appId].isEmpty()) { - qWarning() << "Missing name" << appId; - m_applicationNames[appId] = appId; - } - } - - // Preload up front, so it doesn't get sluggish when selecting applications supporting a lot - const QIcon unknownIcon = QIcon::fromTheme("unknown"); - - // TODO: check if QT_QPA_PLATFORMTHEME is set to plasma or sandsmark, - // if so just use the functioning QIcon::fromTheme() - // We do this manually because non-Plasma-platforms icon loading is extremely slow (I blame GTK and its crappy icon cache) - for (const QString &searchPath : (QIcon::themeSearchPaths() + QIcon::fallbackSearchPaths())) { - loadIcons(searchPath + QIcon::themeName()); - loadIcons(searchPath); - } - - for (const QString &mimetypeName : m_supportedMimetypes.values()) { - if (m_mimeTypeIcons.contains(mimetypeName)) { - continue; - } - const QMimeType mimetype = m_mimeDb.mimeTypeForName(mimetypeName); - - QString iconName = mimetype.iconName(); - QIcon icon(m_iconPaths.value(iconName)); - if (!icon.isNull()) { - m_mimeTypeIcons[mimetypeName] = icon; - continue; - } - icon = QIcon(m_iconPaths.value(mimetype.genericIconName())); - if (!icon.isNull()) { - m_mimeTypeIcons[mimetypeName] = icon; - continue; - } - int split = iconName.lastIndexOf('+'); - if (split != -1) { - iconName.truncate(split); - icon = QIcon(m_iconPaths.value(iconName)); - if (!icon.isNull()) { - m_mimeTypeIcons[mimetypeName] = icon; - continue; - } - } - split = iconName.lastIndexOf('-'); - if (split != -1) { - iconName.truncate(split); - icon = QIcon(m_iconPaths.value(iconName)); - if (!icon.isNull()) { - m_mimeTypeIcons[mimetypeName] = icon; - continue; - } - } - icon = QIcon(m_iconPaths.value(mimetype.genericIconName())); - if (!icon.isNull()) { - m_mimeTypeIcons[mimetypeName] = icon; - continue; - } - - m_mimeTypeIcons[mimetypeName] = unknownIcon; - } - - QHBoxLayout *mainLayout = new QHBoxLayout; - setLayout(mainLayout); - m_applicationList = new QTreeWidget; - mainLayout->addWidget(m_applicationList); - - QGridLayout *rightLayout = new QGridLayout; - mainLayout->addLayout(rightLayout); - - m_setDefaultButton = new QPushButton(tr("Set as default application for these file types")); - m_setDefaultButton->setEnabled(false); - - m_mimetypeList = new QListWidget; - m_mimetypeList->setSelectionMode(QAbstractItemView::MultiSelection); - - rightLayout->addWidget(m_mimetypeList); - rightLayout->addWidget(m_setDefaultButton); - - QStringList types = m_applications.keys(); - std::sort(types.begin(), types.end()); - for (const QString &type : types) { - QTreeWidgetItem *typeItem = new QTreeWidgetItem(QStringList(type)); - QStringList applications = m_applications[type].values(); - std::sort(applications.begin(), applications.end(), [=](const QString &a, const QString &b) { - return m_applicationNames[a] < m_applicationNames[b]; - }); - for (const QString &application : applications) { - QTreeWidgetItem *appItem = new QTreeWidgetItem(QStringList(m_applicationNames[application])); - appItem->setData(0, Qt::UserRole, application); - appItem->setIcon(0, QIcon::fromTheme(m_applicationIcons[application])); - typeItem->addChild(appItem); - } - m_applicationList->addTopLevelItem(typeItem); - } - m_applicationList->setHeaderHidden(true); - - connect(m_applicationList, &QTreeWidget::itemSelectionChanged, this, &Widget::onMimetypeSelected); - connect(m_setDefaultButton, &QPushButton::clicked, this, &Widget::onSetDefaultClicked); -} - -Widget::~Widget() -{ - -} - -void Widget::onMimetypeSelected() -{ - m_setDefaultButton->setEnabled(false); - m_mimetypeList->clear(); - - QList selectedItems = m_applicationList->selectedItems(); - if (selectedItems.count() != 1) { - return; - } - - const QTreeWidgetItem *item = selectedItems.first(); - if (!item->parent()) { - return; - } - - const QString mimetypeGroup = item->parent()->text(0); - const QString application = item->data(0, Qt::UserRole).toString(); - - QStringList supported = m_supportedMimetypes.values(application); - - // E. g. kwrite and kate only indicate support for "text/plain", but - // they're nice for things like c source files. - QSet secondary; - const QStringList currentSupported = m_supportedMimetypes.values(application); - for (const QString &mimetype : currentSupported) { - for (const QString &child : m_childMimeTypes.values(mimetype)) { - supported.append(child); - secondary.insert(child); - } - } - supported.removeDuplicates(); - - for (const QString &supportedMime : supported) { - if (!supportedMime.startsWith(mimetypeGroup)) { - continue; - } - const QMimeType mimetype = m_mimeDb.mimeTypeForName(supportedMime); - const QString mimeName = mimetype.name(); - QString name = mimetype.filterString().trimmed(); - if (name.isEmpty()) { - name = mimetype.comment().trimmed(); - } - if (name.isEmpty()) { - name = mimeName; - } else { - name += '\n' + mimeName; - } - QListWidgetItem *item = new QListWidgetItem(name); - item->setData(Qt::UserRole, mimeName); - item->setIcon(m_mimeTypeIcons[supportedMime]); - m_mimetypeList->addItem(item); - item->setSelected(!secondary.contains(mimeName)); - } - - m_setDefaultButton->setEnabled(m_mimetypeList->count() > 0); -} - -void Widget::onSetDefaultClicked() -{ - QList selectedItems = m_applicationList->selectedItems(); - if (selectedItems.count() != 1) { - return; - } - - const QTreeWidgetItem *item = selectedItems.first(); - if (!item->parent()) { - return; - } - - const QString application = item->data(0, Qt::UserRole).toString(); - if (application.isEmpty()) { - return; - } - - QSet unselected; - QSet selected; - for (int i=0; icount(); i++) { - QListWidgetItem *item = m_mimetypeList->item(i); - const QString name = item->data(Qt::UserRole).toString(); - if (item->isSelected()) { - selected.insert(name); - } else { - unselected.insert(name); - } - } - - setDefault(application, selected, unselected); -} - -void Widget::loadDesktopFile(const QFileInfo &fileInfo) -{ - // Ugliest implementation of .desktop file reading ever - - QFile file(fileInfo.absoluteFilePath()); - if (!file.open(QIODevice::ReadOnly)) { - qDebug() << "Failed to open" << fileInfo.fileName(); - return; - } - - QStringList mimetypes; - QString appName; - QString appId = fileInfo.fileName(); - QString iconName; - - bool inCorrectGroup = false; - bool noDisplay = false; - - while (!file.atEnd()) { - QString line = file.readLine().simplified(); - - if (line.startsWith('[')) { - inCorrectGroup = (line == "[Desktop Entry]"); - continue; - } - - if (!inCorrectGroup) { - continue; - } - - if (line.startsWith("MimeType")) { - line.remove(0, line.indexOf('=') + 1); - mimetypes = line.split(';', Qt::SkipEmptyParts); - continue; - } - - if (line.startsWith("Name") && !line.contains('[')) { - line.remove(0, line.indexOf('=') + 1); - appName = line; - continue; - } - - if (line.startsWith("Icon")) { - line.remove(0, line.indexOf('=') + 1); - iconName = line; - continue; - } - - if (line.startsWith("Exec")) { - line.remove(0, line.indexOf('=') + 1); - if (line.isEmpty()) { - continue; - } - QStringList parts = line.split(' '); - if (parts.first() == "env" && parts.count() > 2) { - line = parts[2]; - } - - appId = line; - continue; - } - - if (line.startsWith("NoDisplay=") && line.contains("true", Qt::CaseInsensitive)) { - noDisplay = true; - } - } - - if (!iconName.isEmpty() && m_applicationIcons[appId].isEmpty()) { - m_applicationIcons[appId] = iconName; - } - - // If an application has a .desktop file without NoDisplay use that, otherwise use one of the ones with NoDisplay anyways - if (!noDisplay || !m_desktopFileNames.contains(appId)) { - m_desktopFileNames[appId] = fileInfo.fileName(); - } - - if (!appName.isEmpty() && m_applicationNames[appId].isEmpty()) { - m_applicationNames[appId] = appName; - } - - if (mimetypes.isEmpty()) { - return; - } - - const QMimeType octetStream = m_mimeDb.mimeTypeForName("application/octet-stream"); - for (const QString &readMimeName : mimetypes) { - // Resolve aliases etc - const QMimeType mimetype = m_mimeDb.mimeTypeForName(readMimeName.trimmed()); - if (!mimetype.isValid()) { - continue; - } - - const QString mimetypeName = mimetype.name(); - for (const QString &parent : mimetype.parentMimeTypes()) { - if (parent == "application/octet-stream") { - break; - } - m_childMimeTypes.insert(parent, mimetypeName); - } - if (m_supportedMimetypes.contains(appId, mimetypeName)) { - continue; - } - - const QStringList parts = mimetypeName.split('/'); - if (parts.count() != 2) { - continue; - } - - const QString type = parts[0].trimmed(); - - m_applications[type].insert(appId); - m_supportedMimetypes.insert(appId, mimetypeName); - } -} - -void Widget::setDefault(const QString &appName, const QSet &mimetypes, const QSet &unselectedMimetypes) -{ - QString desktopFile = m_desktopFileNames.value(appName); - if (desktopFile.isEmpty()) { - qWarning() << "invalid" << appName; - return; - } - - const QString filePath = QDir(QStandardPaths::writableLocation(QStandardPaths::ConfigLocation)).absoluteFilePath("mimeapps.list"); - QFile file(filePath); - - // Read in existing mimeapps.list, skipping the lines for the mimetypes we're updating - QList existingContent; - QList existingAssociations; - if (file.open(QIODevice::ReadOnly)) { - bool inCorrectGroup = false; - while (!file.atEnd()) { - const QByteArray line = file.readLine().trimmed(); - - if (line.isEmpty()) { - continue; - } - - if (line.startsWith('[')) { - inCorrectGroup = (line == "[Default Applications]"); - if (!inCorrectGroup) { - existingContent.append(line); - } - continue; - } - - if (!inCorrectGroup) { - existingContent.append(line); - continue; - } - - if (!line.contains('=')) { - existingAssociations.append(line); - continue; - } - - const QString mimetype = m_mimeDb.mimeTypeForName(line.split('=').first().trimmed()).name(); - if (!mimetypes.contains(mimetype) && !unselectedMimetypes.contains(mimetype)) { - existingAssociations.append(line); - } - } - - file.close(); - } else { - qDebug() << "Unable to open file for reading"; - } - - if (!file.open(QIODevice::WriteOnly)) { - QMessageBox::warning(this, tr("Failed to store settings"), file.errorString()); - return; - } - - for (const QByteArray &line : existingContent) { - file.write(line + '\n'); - } - file.write("\n[Default Applications]\n"); - for (const QByteArray &line : existingAssociations) { - file.write(line + '\n'); - } - - for (const QString &mimetype : mimetypes) { - file.write(QString(mimetype + '=' + m_desktopFileNames[appName] + '\n').toUtf8()); - } - - return; -} - -void Widget::loadIcons(const QString &path) -{ - QFileInfo fi(path); - if (!fi.exists() || !fi.isDir()) { - return; - } - // TODO: avoid hardcoding - QStringList imageTypes({"*.svg", "*.svgz", "*.png", "*.xpm"}); - QDirIterator it(path, imageTypes, QDir::Files, QDirIterator::Subdirectories); - - while (it.hasNext()) { - it.next(); - fi = it.fileInfo(); - - const QString name = fi.completeBaseName(); - if (m_iconPaths.contains(name)) { - continue; - } - m_iconPaths[name] = fi.filePath(); - } -} diff --git a/widget.h b/widget.h deleted file mode 100644 index e2f23fa..0000000 --- a/widget.h +++ /dev/null @@ -1,49 +0,0 @@ -#ifndef WIDGET_H -#define WIDGET_H - -#include -#include -#include - -class QFileInfo; -class QTreeWidget; -class QListWidget; -class QPushButton; - -class Widget : public QWidget -{ - Q_OBJECT - -public: - Widget(QWidget *parent = nullptr); - ~Widget(); - - -private slots: - void onMimetypeSelected(); - void onSetDefaultClicked(); - -private: - void loadDesktopFile(const QFileInfo &fileInfo); - void setDefault(const QString &appName, const QSet &mimetypes, const QSet &unselectedMimetypes); - void loadIcons(const QString &path); - - QMultiHash m_supportedMimetypes; - QMultiHash m_childMimeTypes; - QHash> m_applications; - QHash m_applicationIcons; - QHash m_applicationNames; - QHash m_desktopFileNames; - - QHash m_appIdToDesktopFile; - - QHash m_mimeTypeIcons; // for preloading icons, because that's (a bit) slooow - QHash m_iconPaths; - - QTreeWidget *m_applicationList; - QMimeDatabase m_mimeDb; - QListWidget *m_mimetypeList; - QPushButton *m_setDefaultButton; -}; - -#endif // WIDGET_H