[IDE Tool] AdvancedSearch

Working on new editor enhancements?
AZJIO
Addict
Addict
Posts: 2154
Joined: Sun May 14, 2017 1:48 am

[IDE Tool] AdvancedSearch

Post by AZJIO »

AdvancedSearch - tool for quick search by forming a search query
Download: yandex upload.ee

Linux
Image

Code: Select all

;- AZJIO 2024

EnableExplicit

; Определяет язык ОС
;- Language
Define UserIntLang
Define ForceLang

CompilerSelect #PB_Compiler_OS
	CompilerCase #PB_OS_Windows
		Define *Lang
		If OpenLibrary(0, "kernel32.dll")
			*Lang = GetFunction(0, "GetUserDefaultUILanguage")
			If *Lang And CallFunctionFast(*Lang) = 1049 ; ru (embed your language natively)
				UserIntLang = 1
			EndIf
			CloseLibrary(0)
		EndIf
	CompilerCase #PB_OS_Linux
		If ExamineEnvironmentVariables()
			While NextEnvironmentVariable()
				If Left(EnvironmentVariableName(), 4) = "LANG" And Left(EnvironmentVariableValue(), 2) = "ru" ; (embed your language natively)
					; LANG=ru_RU.UTF-8
					; LANGUAGE=ru
					UserIntLang = 1
					Break
				EndIf
			Wend
		EndIf
CompilerEndSelect


;- Language En
#CountStrLang = 16
Global Dim Lng.s(#CountStrLang)
Lng(1) = "Find"
Lng(2) = "Precision"
Lng(3) = "Ignore"
Lng(4) = "Domain"
Lng(5) = "Part of url"
Lng(6) = "Open ini"
Lng(7) = "Copy"
Lng(8) = "Clear all"
Lng(9) = "Continue?"
Lng(10) = "The word list is empty, continue?"
Lng(11) = "<title>"
Lng(12) = "Hold"
Lng(13) = "Add"
Lng(14) = "Delete"
Lng(15) = "Notes (F2)"
Lng(16) = "Help (F1)"


;- ● #Constants
#Window = 0

Enumeration
	#imgTitle
	#imgAdd
	#imgDel
	#imgSearch
	#imgGoogle
	#imgYandex
	#imgDuck
	#imgBing
	#imgYahoo
	#imgmsdn
	#imgBaidu
	#imgFaganFinder
	#imgMediasova
	#imgCopy
	#imgClear
	#imgini
	#imgHold
	#imgNotes
	#imgHelp
EndEnumeration

Enumeration
	#mEnter
	#mHelp
	#mDraft
	#mClear
EndEnumeration

Enumeration
	#txt1
	#txt2
	#txt3

	#strSearch
	#ChBox1
	#ChTitle
	#ChPrecision1
	#btnAddWord
	#btnDelWord

	#cboxDomain
	#ChBox2
	#ChPrecision2
	#btnAddDomain
	#btnDelDomain

	#strLinkPart
	#ChBox3
	#ChPrecision3
	#btnAddPart
	#btnDelPart

	#strOut
	#btnFind
	#btnClear
	#btnCopy
	#btnini
	#btnHold
	#btnNotes
	#btnHelp
	#cboxSearchEngine
EndEnumeration

;- ● Global
Global width = 640
Global height = 210
Global w2, h2
Global clipboard, idxres = 1, isOR = 1
Global Portable = 1
Global PathConfig$
Global ini$
Global NewList Word$()
Global NewList Domain$()
Global NewList LinkPart$()
Global NewList SearchEngine$()

Define tmp$, tmp2$, btnwidth, i, isINI, hGadget, y, isExit = 1, tmp

UseGIFImageDecoder()

CompilerIf #PB_Compiler_OS = #PB_OS_Linux
	; https://www.purebasic.fr/english/viewtopic.php?p=531374#p531374
	ImportC ""
		gtk_window_set_icon(a.l, b.l)
	EndImport

	DataSection
		IconTitle:
		IncludeBinary "icon.gif"
		IconTitleend:
	EndDataSection
	CatchImage(#imgTitle, ?IconTitle)
CompilerEndIf


;- ● Declare
Declare FormString()
Declare SizeWindowHandler()
Declare Find()
Declare Exit()
Declare AddWord()
Declare AddDomain(tmp$)
Declare IsDomain(*c.Character)
Declare ForceDirectories(Dir.s)
Declare Notes()
Declare Help()

;- ini
PathConfig$ = GetPathPart(ProgramFilename())
If FileSize(PathConfig$ + "AdvancedSearch.ini") = -1
	Portable = 0
	CompilerSelect #PB_Compiler_OS
		CompilerCase #PB_OS_Windows
			PathConfig$ = GetHomeDirectory() + "AppData\Roaming\AdvancedSearch\"
		CompilerCase #PB_OS_Linux
			PathConfig$ = GetHomeDirectory() + ".config/AdvancedSearch/"
	CompilerEndSelect
EndIf
ini$ = PathConfig$ + "AdvancedSearch.ini"

CompilerIf #PB_Compiler_OS = #PB_OS_Linux
; 	Если нет ini, то восстанавливаем его из папки конфигов, заранее установив его из пакета в /usr
	If FileSize(PathConfig$ + "AdvancedSearch.ini") = -1 And FileSize("/usr/share/azjio/AdvancedSearch/AdvancedSearch.ini") > 0 And ForceDirectories(PathConfig$)
		CopyFile("/usr/share/azjio/AdvancedSearch/AdvancedSearch.ini", PathConfig$ + "AdvancedSearch.ini")
	EndIf
CompilerEndIf

If OpenPreferences(ini$, #PB_Preference_NoSpace | #PB_Preference_GroupSeparator)
	isINI = 1
	PreferenceGroup("gui")
	width = ReadPreferenceInteger("width", width)
	If width < 500
		width = 500
	EndIf
	height = ReadPreferenceInteger("height", height)
	If height < 170
		height = 170
	EndIf
	clipboard = ReadPreferenceInteger("clipboard", clipboard)
	idxres = ReadPreferenceInteger("idxres", idxres)
	isExit = ReadPreferenceInteger("Exit", isExit)
	isOR = ReadPreferenceInteger("OR", isOR)
	ForceLang = ReadPreferenceInteger("forcelang", ForceLang)
	; можно задать ключевые слова, чтобы иметь возможность перенастроить на яндекс и указывать url: host: rhost: domain:
; 	site = ReadPreferenceString("site", site)
; 	inurl = ReadPreferenceString("inurl", inurl)
; 	fontsize = ReadPreferenceInteger("fontsize", fontsize)
; 	fontname = ReadPreferenceInteger("fontname", fontname)
; 	ClosePreferences()
EndIf

Procedure SetLangTxt(PathLang$)
	Protected file_id, Format, i, tmp$
	
	file_id = ReadFile(#PB_Any, PathLang$) 
	If file_id ; Если удалось открыть дескриптор файла, то
		Format = ReadStringFormat(file_id) ;  перемещаем указатель после метки BOM
		i=0
		While Eof(file_id) = 0        ; Цикл, пока не будет достигнут конец файла. (Eof = 'Конец файла')
			tmp$ =  ReadString(file_id, Format) ; читаем строку
								  ; If Left(tmp$, 1) = ";"
								  ; Continue
								  ; EndIf
; 			tmp$ = ReplaceString(tmp$ , #CR$ , "") ; коррекция если в Windows
			tmp$ = RTrim(tmp$ , #CR$) ; коррекция если в Windows
			If Asc(tmp$) And Asc(tmp$) <> ';'
				i+1
				If i > #CountStrLang ; массив Lng() уже задан, но если строк больше нужного, то не разрешаем лишнее
					Break
				EndIf
; 				Lng(i) = UnescapeString(tmp$) ; позволяет в строке иметь экранированные метасимволы, \n \t и т.д.
				Lng(i) = ReplaceString(tmp$, "\n", #LF$) ; В ini-файле проблема только с переносами, поэтому заменяем только \n
			Else
				Continue
			EndIf
		Wend
		CloseFile(file_id)
	EndIf
	; Else
	; SaveFile_Buff(PathLang$, ?LangFile, ?LangFileend - ?LangFile)
EndProcedure

; Принудительный язык
If ForceLang = 1
	UserIntLang = 0
ElseIf ForceLang = 2 ; force enable your language (use ini file)
	UserIntLang = 1
EndIf

; Если языковой файл существует, то использует его
If FileSize(PathConfig$ + "Lang.txt") > 100
	UserIntLang = 0
	SetLangTxt(PathConfig$ + "Lang.txt")
EndIf
	
;- Language Ru

If UserIntLang
	Lng(1) = "Найти"
	Lng(2) = "Точно"
	Lng(3) = "Игнор"
	Lng(4) = "Домен"
	Lng(5) = "Часть url"
	Lng(6) = "Открыть ini"
	Lng(7) = "Копировать"
	Lng(8) = "Очистить"
	Lng(9) = "Продолжить?"
	Lng(10) = "Список слов пуст, продолжить?"
	Lng(11) = "<title>"
	Lng(12) = "Удерживать окно"
	Lng(13) = "Добавить"
	Lng(14) = "Удалить"
	Lng(15) = "Заметки (F2)"
	Lng(16) = "Справка (F1)"
EndIf


;- Data
DataSection
	add:
	IncludeBinary "images" + #PS$ + "add.gif"
	del:
	IncludeBinary "images" + #PS$ + "del.gif"
	Hold:
	IncludeBinary "images" + #PS$ + "Hold.gif"
	ini:
	IncludeBinary "images" + #PS$ + "ini.gif"
	Copy:
	IncludeBinary "images" + #PS$ + "Copy.gif"
	Clear:
	IncludeBinary "images" + #PS$ + "Clear.gif"
	Search:
	IncludeBinary "images" + #PS$ + "Search.gif"
	Notes:
	IncludeBinary "images" + #PS$ + "Notes.gif"
	Help:
	IncludeBinary "images" + #PS$ + "Help.gif"
	Google:
	IncludeBinary "images" + #PS$ + "Google.gif"
	Yandex:
	IncludeBinary "images" + #PS$ + "Yandex.gif"
	Duck:
	IncludeBinary "images" + #PS$ + "Duck.gif"
	Bing:
	IncludeBinary "images" + #PS$ + "Bing.gif"
	Yahoo:
	IncludeBinary "images" + #PS$ + "Yahoo.gif"
	msdn:
	IncludeBinary "images" + #PS$ + "msdn.gif"
	Baidu:
	IncludeBinary "images" + #PS$ + "Baidu.gif"
	FaganFinder:
	IncludeBinary "images" + #PS$ + "FaganFinder.gif"
	Mediasova:
	IncludeBinary "images" + #PS$ + "Mediasova.gif"
EndDataSection

CatchImage(#imgAdd, ?add)
CatchImage(#imgDel, ?del)
CatchImage(#imgHold, ?Hold)
CatchImage(#imgini, ?ini)
CatchImage(#imgCopy, ?Copy)
CatchImage(#imgClear, ?Clear)
CatchImage(#imgSearch, ?Search)
CatchImage(#imgNotes, ?Notes)
CatchImage(#imgHelp, ?Help)
CatchImage(#imgGoogle, ?Google)
CatchImage(#imgYandex, ?Yandex)
CatchImage(#imgDuck, ?Duck)
CatchImage(#imgBing, ?Bing)
CatchImage(#imgYahoo, ?Yahoo)
CatchImage(#imgmsdn, ?msdn)
CatchImage(#imgBaidu, ?Baidu)
CatchImage(#imgFaganFinder, ?FaganFinder)
CatchImage(#imgMediasova, ?Mediasova)

w2 = width
h2 = height
hGadget = (height - 60) / 5
; Debug height
; Debug hGadget


;-┌──GUI──┐
If OpenWindow(#Window, 0, 0, width, height, "Advanced Search", #PB_Window_SystemMenu | #PB_Window_ScreenCentered | #PB_Window_SizeGadget | #PB_Window_MaximizeGadget | #PB_Window_MinimizeGadget)
	CompilerIf #PB_Compiler_OS = #PB_OS_Linux
		gtk_window_set_icon_(WindowID(#Window), ImageID(#imgTitle)) ; назначаем иконку в заголовке
	CompilerEndIf
	y + 10
	TextGadget(#txt1, 5, y, 75, hGadget, Lng(1))
	StringGadget(#strSearch, 80, y, width - 330, hGadget, "")

	i = hGadget / 2
	CompilerSelect #PB_Compiler_OS
		CompilerCase #PB_OS_Windows
			CheckBoxGadget(#ChTitle, width - 240, 8, 70, i, Lng(11))
			CheckBoxGadget(#ChPrecision1, width - 240, y + i + 4, 70, i, Lng(2))
		CompilerCase #PB_OS_Linux
			CheckBoxGadget(#ChTitle, width - 240, 0, 70, i, Lng(11))
			CheckBoxGadget(#ChPrecision1, width - 240, y + i - 4, 70, i, Lng(2))
	CompilerEndSelect
	CheckBoxGadget(#ChBox1, width - 160, y, 70, hGadget, Lng(3))
; 	ButtonGadget(#btnAddWord, width - 200, y, 90, hGadget, "Добавить")
; 	ButtonGadget(#btnDelWord, width - 100, y, 90, hGadget, "Убавить")
	ButtonImageGadget(#btnAddWord, width - 80, y, 30, hGadget, ImageID(#imgAdd))
	GadgetToolTip(#btnAddWord, Lng(13))
	ButtonImageGadget(#btnDelWord, width - 40, y, 30, hGadget, ImageID(#imgDel))
	GadgetToolTip(#btnDelWord, Lng(14))
	
	y + 10 + hGadget
	TextGadget(#txt2, 5, y, 75, hGadget, Lng(4))
	CheckBoxGadget(#ChBox2, width - 160, y, 70, hGadget, Lng(3))
; 	ButtonGadget(#btnAddDomain, width - 200, y, 90, hGadget, "Добавить")
; 	ButtonGadget(#btnDelDomain, width - 100, y, 90, hGadget, "Убавить")
	ButtonImageGadget(#btnAddDomain, width - 80, y, 30, hGadget, ImageID(#imgAdd))
	GadgetToolTip(#btnAddDomain, Lng(13))
	ButtonImageGadget(#btnDelDomain, width - 40, y, 30, hGadget, ImageID(#imgDel))
	GadgetToolTip(#btnDelDomain, Lng(14))

	ComboBoxGadget(#cboxDomain, 80, y, width - 250, hGadget, #PB_ComboBox_Editable)
; 	If OpenPreferences(ini$, #PB_Preference_NoSpace | #PB_Preference_GroupSeparator)
	If isINI
		If PreferenceGroup("domain")
			If ExaminePreferenceKeys()
				While NextPreferenceKey()
					AddGadgetItem(#cboxDomain, -1, PreferenceKeyValue())
				Wend
			EndIf
		EndIf
; 		ClosePreferences()
	EndIf
	If CountGadgetItems(#cboxDomain)
		SetGadgetState(#cboxDomain, 0)
	EndIf
	
	y + 10 + hGadget
	TextGadget(#txt3, 5, y, 75, hGadget, Lng(5))
	ComboBoxGadget(#strLinkPart, 80, y, width - 250, hGadget, #PB_ComboBox_Editable)
	CheckBoxGadget(#ChBox3, width - 160, y, 70, hGadget, Lng(3))
; 	ButtonGadget(#btnAddPart, width - 200, y, 90, hGadget, "Добавить")
; 	ButtonGadget(#btnDelPart, width - 100, y, 90, hGadget, "Убавить")
	ButtonImageGadget(#btnAddPart, width - 80, y, 30, hGadget, ImageID(#imgAdd))
	GadgetToolTip(#btnAddPart, Lng(13))
	ButtonImageGadget(#btnDelPart, width - 40, y, 30, hGadget, ImageID(#imgDel))
	GadgetToolTip(#btnDelPart, Lng(14))

; 	If OpenPreferences(ini$, #PB_Preference_NoSpace | #PB_Preference_GroupSeparator)
	If isINI
		If PreferenceGroup("inurl")
			If ExaminePreferenceKeys()
				While NextPreferenceKey()
					AddGadgetItem(#strLinkPart, -1, PreferenceKeyValue())
				Wend
			EndIf
		EndIf
	EndIf
	
;-├ Buttons
	y + 10 + hGadget
	StringGadget(#strOut, 5, y, width - 10, hGadget, "")
	btnwidth = (width - 95) / 10
	y + 10 + hGadget
	ComboBoxGadget(#cboxSearchEngine, 10, y, btnwidth * 3 + 10, hGadget, #PB_ComboBox_Image)
	ButtonImageGadget(#btnHold, (btnwidth + 10) * 3, y, btnwidth, hGadget, ImageID(#imgHold), #PB_Button_Toggle)
	GadgetToolTip(#btnHold, Lng(12))
	If Not isExit
		SetGadgetState(#btnHold, 1)
	EndIf
	ButtonImageGadget(#btnNotes, (btnwidth + 10) * 4, y, btnwidth, hGadget, ImageID(#imgNotes))
	GadgetToolTip(#btnNotes, Lng(15))
	ButtonImageGadget(#btnHelp, (btnwidth + 10) * 5, y, btnwidth, hGadget, ImageID(#imgHelp))
	GadgetToolTip(#btnHelp, Lng(16))
	ButtonImageGadget(#btnini, (btnwidth + 10) * 6, y, btnwidth, hGadget, ImageID(#imgini))
	GadgetToolTip(#btnini, Lng(6))
	ButtonImageGadget(#btnCopy, (btnwidth + 10) * 7, y, btnwidth, hGadget, ImageID(#imgCopy))
	GadgetToolTip(#btnCopy, Lng(7))
	ButtonImageGadget(#btnClear, (btnwidth + 10) * 8, y, btnwidth, hGadget,  ImageID(#imgClear))
	GadgetToolTip(#btnClear, Lng(8))
	ButtonImageGadget(#btnFind, (btnwidth + 10) * 9, y, btnwidth, hGadget,  ImageID(#imgSearch))
	GadgetToolTip(#btnFind, Lng(1))


; 	If OpenPreferences(ini$, #PB_Preference_NoSpace | #PB_Preference_GroupSeparator)
	If isINI
		If PreferenceGroup("searchstring")
			If ExaminePreferenceKeys()
				i = 0
				While NextPreferenceKey()
					Select PreferenceKeyName()
						Case "Google"
							tmp = ImageID(#imgGoogle)
						Case "Yandex"
							tmp = ImageID(#imgYandex)
						Case "Duck"
							tmp = ImageID(#imgDuck)
						Case "Bing"
							tmp = ImageID(#imgBing)
						Case "Yahoo"
							tmp = ImageID(#imgYahoo)
						Case "msdn"
							tmp = ImageID(#imgmsdn)
						Case "Baidu"
							tmp = ImageID(#imgBaidu)
						Case "FaganFinder"
							tmp = ImageID(#imgFaganFinder)
						Case "Mediasova"
							tmp = ImageID(#imgMediasova)
						Default
							tmp = ImageID(#imgSearch)
					EndSelect
					
					AddGadgetItem(#cboxSearchEngine, i, PreferenceKeyName(), tmp)
					If AddElement(SearchEngine$())
						SearchEngine$() = PreferenceKeyValue()
						SetGadgetItemData(#cboxSearchEngine, i , i)
					EndIf
					i + 1
				Wend
			EndIf
		EndIf
		ClosePreferences() ; закрываем конфиг только после чтения последнего раздела
	EndIf
	
	i = CountGadgetItems(#cboxSearchEngine)
	If i
		If i < idxres
			idxres = i
		EndIf
		SetGadgetState(#cboxSearchEngine, idxres - 1) ; задаём выбор движка по индексу
	EndIf

	BindEvent(#PB_Event_SizeWindow, @SizeWindowHandler())
	WindowBounds(#Window, 500, 170, #PB_Default, #PB_Default)

	If CountProgramParameters()
		CompilerIf #PB_Compiler_OS = #PB_OS_Windows
			SetWindowLongPtr_(GadgetID(#btnFind), #GWL_STYLE, GetWindowLongPtr_(GadgetID(#btnFind), #GWL_STYLE) | #BS_DEFPUSHBUTTON)
		CompilerEndIf
		tmp$ = ProgramParameter(0)
		; проблема, если слово пусто, то домен воспрнимается как слово. Чтобы домен не вставлять в поиск делаем проверку,
		; что параметр один и он на 99% похож на домен, в нём точки и латинские символы, точки не по краям и нет две точки подряд.
		; Может стоит сделать префиксы в ком-строке "-w:word -d:domain"?
		If CountProgramParameters() = 1 And IsDomain(@tmp$)
			AddDomain(tmp$)
			SetGadgetText(#cboxDomain, tmp$)
			If clipboard
				tmp$ = GetClipboardText()
				SetGadgetText(#strSearch, tmp$)
				If AddElement(Word$())
					Word$() = tmp$
				EndIf
			EndIf
		Else
			SetGadgetText(#strSearch, tmp$)
			If AddElement(Word$())
				Word$() = tmp$
			EndIf
		EndIf
		If CountProgramParameters() > 1
			tmp$ = ProgramParameter(1)
			AddDomain(tmp$)
			SetGadgetText(#cboxDomain, tmp$) ; а надо ли, домен всё равно вычисляется, и можно было бы добавить второй домен.
		EndIf
		FormString()
	Else
		If clipboard
			CompilerIf #PB_Compiler_OS = #PB_OS_Windows
				SetWindowLongPtr_(GadgetID(#btnFind), #GWL_STYLE, GetWindowLongPtr_(GadgetID(#btnFind), #GWL_STYLE) | #BS_DEFPUSHBUTTON)
			CompilerEndIf
			tmp$ = GetClipboardText()
			SetGadgetText(#strSearch, tmp$)
			If AddElement(Word$())
				Word$() = tmp$
			EndIf
			AddDomain(GetGadgetText(#cboxDomain))
			FormString()
		Else
			SetActiveGadget(#strSearch)
		EndIf
	EndIf

	AddKeyboardShortcut(#Window, #PB_Shortcut_Return, #mEnter)
	AddKeyboardShortcut(#Window, #PB_Shortcut_F1, #mHelp)
	AddKeyboardShortcut(#Window, #PB_Shortcut_F2, #mDraft)
	AddKeyboardShortcut(#Window, #PB_Shortcut_Control | #PB_Shortcut_Back, #mClear)



;-┌──Loop──┐
	Repeat
		Select WaitWindowEvent()
;-├ Menu events
			Case #PB_Event_Menu
				Select EventMenu()
					Case #mClear ; Ctrl+Backspace
						SetGadgetText(#strSearch, "")
						SetActiveGadget(#strSearch)
					Case #mEnter ; Enter
						Select GetActiveGadget() ; т.е. если редактировано поле, то сначала пересобираем строку
							Case #strSearch ; использовать #PB_EventType_Change? Чтобы исключить ложное добавление. Или Map
								AddWord()
							Case #cboxDomain
								AddDomain(GetGadgetText(#cboxDomain))
; 							Case #strLinkPart
						EndSelect
						Find()
					Case #mDraft ; Вызов черновика
						Notes()
					Case #mHelp ; Вызов справки
						Help()
				EndSelect

;-├ Gadget Events
			Case #PB_Event_Gadget
				Select EventGadget()
						
					Case #ChTitle
						tmp$ = GetGadgetText(#strSearch)
						If Asc(tmp$)
							If GetGadgetState(#ChTitle) & #PB_Checkbox_Checked
								SetGadgetText(#strSearch, "intitle:" + tmp$)
							Else
								SetGadgetText(#strSearch, ReplaceString(tmp$, "intitle:", "", #PB_String_NoCase, 1, 1))
							EndIf
						EndIf
						
					Case #ChPrecision1
						tmp$ = GetGadgetText(#strSearch)
						If Asc(tmp$)
							i = FindString(tmp$, "intitle:")
							If i
								tmp$ = ReplaceString(tmp$, "intitle:", "", #PB_String_NoCase, i, 1)
							EndIf
							If GetGadgetState(#ChPrecision1) & #PB_Checkbox_Checked
								tmp$ = Chr(34) + tmp$ + Chr(34)
							Else
								tmp$ = Trim(tmp$, Chr(34))
							EndIf
							If i
								tmp$ = "intitle:" + tmp$
							EndIf
							SetGadgetText(#strSearch, tmp$)
						EndIf
						
					Case #btnHelp ; Вызов справки
						Help()
					Case #btnNotes ; Открыть файл заметок
						Notes()
						
					Case #btnAddWord
						AddWord()
						
					Case #btnDelWord
						If ListSize(Word$())
							DeleteElement(Word$())
; 							LastElement(Word$())
							FormString()
						EndIf

					Case #btnAddDomain
						AddDomain(GetGadgetText(#cboxDomain))
					Case #btnDelDomain
						If ListSize(Domain$())
							DeleteElement(Domain$())
; 							LastElement(Domain$())
							FormString()
						EndIf

					Case #btnAddPart
						tmp$ = GetGadgetText(#strLinkPart)
						If Asc(tmp$) And AddElement(LinkPart$())
							If GetGadgetState(#ChBox3) & #PB_Checkbox_Checked
								LinkPart$() = "-inurl:" + tmp$
							Else
								LinkPart$() = "inurl:" + tmp$
							EndIf
							FormString()
						EndIf
					Case #btnDelPart
						If ListSize(LinkPart$())
							DeleteElement(LinkPart$())
; 							LastElement(LinkPart$())
							FormString()
						EndIf

					Case #btnFind
						Find()
					Case #btnClear
						ClearList(Word$())
						ClearList(Domain$())
						ClearList(LinkPart$())
						SetGadgetText(#strOut, "")
					Case #btnCopy
						tmp$ = GetGadgetText(#strOut)
						If Asc(tmp$)
							SetClipboardText(ReplaceString(tmp$, "+", " "))
						EndIf
					Case #btnini
						If FileSize(ini$) > -1
							CompilerSelect #PB_Compiler_OS
								CompilerCase #PB_OS_Windows
									RunProgram(ini$)
								CompilerCase #PB_OS_Linux
									RunProgram("xdg-open", Chr(34) + ini$ + Chr(34), "")
							CompilerEndSelect
						EndIf
				EndSelect
			Case #PB_Event_CloseWindow
				Exit()
		EndSelect
	ForEver
EndIf
;-└──Loop──┘


Procedure Exit()
	If (w2 <> width Or h2 <> height) And OpenPreferences(ini$, #PB_Preference_NoSpace | #PB_Preference_GroupSeparator)
		PreferenceGroup("gui")
		WritePreferenceInteger("width", width)
		WritePreferenceInteger("height", height)
		ClosePreferences()
	EndIf
	CloseWindow(#Window)
	End
EndProcedure


Procedure Help()
	Protected tmp$
	CompilerSelect #PB_Compiler_OS
		CompilerCase #PB_OS_Windows
			RunProgram(PathConfig$ + "AdvancedSearch.chm")
		CompilerCase #PB_OS_Linux
			tmp$ = PathConfig$ + "index.html"
			If FileSize(tmp$) = -1
				tmp$ = "/usr/share/help/ru/advancedsearch/index.html"
			EndIf
			If FileSize(tmp$) > 0 ; проверка пути, чтобы не получить ошибку вызова xdg-open
				tmp$ = "/usr/share/help/ru/advancedsearch/index.html"
				RunProgram("xdg-open", Chr(34) + tmp$ + Chr(34), "")
			EndIf
	CompilerEndSelect
EndProcedure


Procedure Notes()
	If FileSize(PathConfig$ + "AdvancedSearch.txt") = -1 And CreateFile(0, PathConfig$ + "AdvancedSearch.txt")
		CloseFile(0) 
	EndIf
	CompilerSelect #PB_Compiler_OS
		CompilerCase #PB_OS_Windows
			RunProgram(PathConfig$ + "AdvancedSearch.txt")
		CompilerCase #PB_OS_Linux
			RunProgram("xdg-open", Chr(34) + PathConfig$ + "AdvancedSearch.txt" + Chr(34), "")
	CompilerEndSelect
EndProcedure


Procedure AddWord()
	Protected tmp$
	tmp$ = GetGadgetText(#strSearch)
	If Asc(tmp$) And AddElement(Word$())
		If GetGadgetState(#ChBox1) & #PB_Checkbox_Checked
			Word$() = "-" + tmp$
		Else
			Word$() = tmp$
		EndIf
		FormString()
	EndIf
EndProcedure


Procedure IsDomain(*c.Character)
	Protected flag = 1
	Protected latin, TotalDot, dot
	
	If *c = 0 Or *c\c = 0 Or *c\c = '.'
		ProcedureReturn 0
	EndIf
	
	Repeat
		Select *c\c
			Case 'a' To 'z'
				latin + 1
				dot = 0
			Case '.'
				If latin = 1
					ProcedureReturn 0
				EndIf
				dot + 1
				TotalDot + 1
				latin = 0
				If dot > 1
					ProcedureReturn 0
				EndIf
			Default
				ProcedureReturn 0
		EndSelect
		
		*c + SizeOf(Character)
	Until Not *c\c
	
	*c - SizeOf(Character)
	If *c\c = '.'
		ProcedureReturn 0
	EndIf
	If Not TotalDot
		ProcedureReturn 0
	EndIf
	
	ProcedureReturn flag
EndProcedure


Procedure AddDomain(tmp$)
	Protected i, tmp2$
	If Asc(tmp$)
; 		If tmp$ = "0"
; 			ProcedureReturn 
; 		EndIf
		If FindString(tmp$, ",")
			i = 0
			Repeat
				i + 1
				tmp2$ = StringField(tmp$, i, ",")
				If Asc(tmp2$)
					If AddElement(Domain$())
						If GetGadgetState(#ChBox2) & #PB_Checkbox_Checked
							Domain$() = "-site:" + tmp2$
						Else
							Domain$() = "site:" + tmp2$
						EndIf
					EndIf
				Else
					Break
				EndIf
			ForEver
		Else
			If AddElement(Domain$())
				If GetGadgetState(#ChBox2) & #PB_Checkbox_Checked
					Domain$() = "-site:" + tmp$
				Else
					Domain$() = "site:" + tmp$
				EndIf
			EndIf
		EndIf
		FormString()
	EndIf
EndProcedure


Procedure Find()
	Protected tmp$, i, SearchEngineDef$
	SearchEngineDef$ = "https://www.google.com/search?source=hp&q=%s&oq=%s"
	tmp$ = GetGadgetText(#strOut)
	If Asc(tmp$)
		; Если список слов пуст, и строка содержит ":" что является фактором тега, то пытаемся запросить согласие на продолжение
		; если нет ":" то вероятно ручная правка строки при отсутсвии программного добавления слов.
		If Not ListSize(Word$()) And FindString(tmp$, ":") And MessageRequester(Lng(9), Lng(10), #PB_MessageRequester_YesNo) = #PB_MessageRequester_No
			ProcedureReturn ; 0
		EndIf
		tmp$ = ReplaceString(tmp$, Chr(34), "%22")

		i = GetGadgetState(#cboxSearchEngine)
		If i = -1
			tmp$ = ReplaceString(SearchEngineDef$, "%s", tmp$)
		Else
			i = GetGadgetItemData(#cboxSearchEngine, i)
			SelectElement(SearchEngine$(), i)
			If Not Asc(SearchEngine$())
				SearchEngine$() = SearchEngineDef$
			EndIf
			tmp$ = ReplaceString(SearchEngine$(), "%s", tmp$)
		EndIf
		
		CompilerSelect #PB_Compiler_OS
			CompilerCase #PB_OS_Windows
				RunProgram(tmp$)
			CompilerCase #PB_OS_Linux
				RunProgram("xdg-open", Chr(34) + tmp$ + Chr(34), "")
		CompilerEndSelect
		If Not GetGadgetState(#btnHold)
			Exit()
		EndIf
; 		ProcedureReturn 1
	EndIf
; 	ProcedureReturn 0
EndProcedure


Procedure SizeWindowHandler()
	Protected btnwidth, hGadget, y, i
	width = WindowWidth(#Window)
	height = WindowHeight(#Window)
	hGadget = (height - 60) / 5
	
	y + 10
	ResizeGadget(#txt1, #PB_Ignore, y, 75, hGadget)
	ResizeGadget(#strSearch, #PB_Ignore, y, width - 330, hGadget)
	ResizeGadget(#ChBox1, width - 160, y, #PB_Ignore, hGadget)
	i = hGadget / 2
	ResizeGadget(#ChTitle, width - 240, #PB_Ignore, #PB_Ignore, i)
	CompilerSelect #PB_Compiler_OS
		CompilerCase #PB_OS_Windows
			ResizeGadget(#ChPrecision1, width - 240, y + i + 4, #PB_Ignore, i)
		CompilerCase #PB_OS_Linux
			ResizeGadget(#ChPrecision1, width - 240, y + i - 4, #PB_Ignore, i)
	CompilerEndSelect
	ResizeGadget(#btnAddWord, width - 80, y, #PB_Ignore, hGadget)
	ResizeGadget(#btnDelWord, width - 40, y, #PB_Ignore, hGadget)

	y + 10 + hGadget
	ResizeGadget(#txt2, #PB_Ignore, y, 75, hGadget)
	ResizeGadget(#cboxDomain, #PB_Ignore, y, width - 250, hGadget)
	ResizeGadget(#ChBox2, width - 160, y, #PB_Ignore, hGadget)
	ResizeGadget(#btnAddDomain, width - 80, y, #PB_Ignore, hGadget)
	ResizeGadget(#btnDelDomain, width - 40, y, #PB_Ignore, hGadget)

	y + 10 + hGadget
	ResizeGadget(#txt3, #PB_Ignore, y, 75, hGadget)
	ResizeGadget(#strLinkPart, #PB_Ignore, y, width - 250, hGadget)
	ResizeGadget(#ChBox3, width - 160, y, #PB_Ignore, hGadget)
	ResizeGadget(#btnAddPart, width - 80, y, #PB_Ignore, hGadget)
	ResizeGadget(#btnDelPart, width - 40, y, #PB_Ignore, hGadget)

	y + 10 + hGadget
	ResizeGadget(#strOut, #PB_Ignore, y, width - 10, hGadget)

	y + 10 + hGadget
	btnwidth = (width - 95) / 10
	ResizeGadget(#cboxSearchEngine, #PB_Ignore, y, btnwidth * 3 + 10, hGadget)
	ResizeGadget(#btnHold, (btnwidth + 10) * 3, y, btnwidth, hGadget)
	ResizeGadget(#btnNotes, (btnwidth + 10) * 4, y, btnwidth, hGadget)
	ResizeGadget(#btnHelp, (btnwidth + 10) * 5, y, btnwidth, hGadget)
	ResizeGadget(#btnini, (btnwidth + 10) * 6, y, btnwidth, hGadget)
	ResizeGadget(#btnCopy, (btnwidth + 10) * 7, y, btnwidth, hGadget)
	ResizeGadget(#btnClear, (btnwidth + 10) * 8, y, btnwidth, hGadget)
	ResizeGadget(#btnFind, (btnwidth + 10) * 9, y, btnwidth, hGadget)
EndProcedure


Procedure FormString()
	Protected Out$, Sep$ = "+", isRequired, tmp$
; 	tmp$ = GetGadgetText(#cboxSearchEngine)
; 	If tmp$ = "Google" Or tmp$ = "Yandex"
; 		isRequired = 1
; 		Sep$ = "+"
; 	EndIf
	ForEach Word$()
; 		If isRequired
			If Asc(Word$()) = '"' Or (Asc(Word$()) = '-' And Mid(Word$(), 2, 1) = Chr(34))
				Out$ + Word$() + Sep$
			Else
				Out$ + ReplaceString(Word$(), " ", Sep$) + Sep$
			EndIf
; 		Else
; 			Out$ + Word$() + Sep$
; 		EndIf
	Next
	ForEach Domain$()
		If isOR
			Out$ + Domain$() + " OR "
		Else
			Out$ + Domain$() + Sep$
		EndIf
	Next
	ForEach LinkPart$()
		If isOR
			Out$ + LinkPart$() + " OR "
		Else
			Out$ + LinkPart$() + Sep$
		EndIf
	Next
	If isOR And (ListSize(Domain$()) Or ListSize(LinkPart$()))
		Out$ = Left(Out$ , Len(Out$) - 4)
	Else
		Out$ = RTrim(Out$, Sep$)
	EndIf
	SetGadgetText(#strOut, Out$)
EndProcedure


;==================================================================
;
; Author:    ts-soft
; Date:       March 5th, 2010
; Explain:
;     modified version from IBSoftware (CodeArchiv)
;     on vista and above check the Request for "User mode" or "Administrator mode" in compileroptions
;    (no virtualisation!)
; Модификация AZJIO всвязи с особыми условиями: так как функция работает в цикле, то убираем проверку слеша, добавил снова
;==================================================================
Procedure ForceDirectories(Dir.s)
	Static tmpDir.s, Init
	Protected result

	If Asc(Dir)
		If Not Init
			tmpDir = Dir
			Init   = #True
		EndIf
; 		Dir = RTrim(Dir, #PS$)
		If (Right(Dir, 1) = #PS$)
			Dir = Left(Dir, Len(Dir) - 1)
		EndIf
		If (Len(Dir) < 3) Or FileSize(Dir) = -2 Or GetPathPart(Dir) = Dir
			If FileSize(tmpDir) = -2
				result = #True
			EndIf
			tmpDir = ""
			Init = #False
			ProcedureReturn result
		EndIf
		ForceDirectories(GetPathPart(Dir))
		ProcedureReturn CreateDirectory(Dir)
	Else
		ProcedureReturn #False
	EndIf
EndProcedure
; IDE Options = PureBasic 6.04 LTS (Windows - x64)
; CursorPosition = 240
; FirstLine = 238
; Folding = ---
; Optimizer
; EnableXP
; DPIAware
; UseIcon = icon.ico
; Executable = AdvancedSearch.exe
; CompileSourceDirectory
; Compiler = PureBasic 6.04 LTS - C Backend (Windows - x64)
; DisableCompileCount = 4
; EnableBuildCount = 0
; EnableExeConstant
; IncludeVersionInfo
; VersionField0 = 0.5.3.%BUILDCOUNT
; VersionField2 = AZJIO
; VersionField3 = AdvancedSearch
; VersionField4 = 0.5.3
; VersionField6 = AdvancedSearch
; VersionField9 = AZJIO
Last edited by AZJIO on Fri Aug 23, 2024 3:28 pm, edited 7 times in total.
AZJIO
Addict
Addict
Posts: 2154
Joined: Sun May 14, 2017 1:48 am

Re: [IDE Tool] AdvancedSearch

Post by AZJIO »

Updated 3 times
You can read the description through Google Translator
User avatar
mk-soft
Always Here
Always Here
Posts: 6226
Joined: Fri May 12, 2006 6:51 pm
Location: Germany

Re: [IDE Tool] AdvancedSearch

Post by mk-soft »

My Projects ThreadToGUI / OOP-BaseClass / EventDesigner V3
PB v3.30 / v5.75 - OS Mac Mini OSX 10.xx - VM Window Pro / Linux Ubuntu
Downloads on my Webspace / OneDrive
boddhi
Enthusiast
Enthusiast
Posts: 524
Joined: Mon Nov 15, 2010 9:53 pm

Re: [IDE Tool] AdvancedSearch

Post by boddhi »

Thanks AZJIO for sharing this tool.

A checkbox "Close tool after" would be usefull to give user the possibility to make several searches (in case of typied text errors in string gadgets, for example) whitout having to restart the tool each time.
I can do this but if you appreciate the idea, it would be better to modify the orginal code post directly. :wink:
If my English syntax and lexicon are incorrect, please bear with Google translate and DeepL. They rarely agree with each other!
Except on this sentence...
AZJIO
Addict
Addict
Posts: 2154
Joined: Sun May 14, 2017 1:48 am

Re: [IDE Tool] AdvancedSearch

Post by AZJIO »

boddhi wrote: Sun Aug 04, 2024 1:12 pm :A checkbox "Close tool after"
1. Exit=0 (ini)
2. Copy (button)
boddhi
Enthusiast
Enthusiast
Posts: 524
Joined: Mon Nov 15, 2010 9:53 pm

Re: [IDE Tool] AdvancedSearch

Post by boddhi »

AZJIO wrote: 1. Exit=0 (ini)
2. Copy (button)
Ok :wink:
If my English syntax and lexicon are incorrect, please bear with Google translate and DeepL. They rarely agree with each other!
Except on this sentence...
AZJIO
Addict
Addict
Posts: 2154
Joined: Sun May 14, 2017 1:48 am

Re: [IDE Tool] AdvancedSearch

Post by AZJIO »

Update

0.5.7 (02.10.24)
Added parameters: urlencoder=1 and separator=

0.5.6 (18.09.24)
The editor and browser parameters in the ini file may contain comline parameters

0.5.5 (12.09.24)
+URLEncoder()

0.5.3 (19.08.24)
Added "Help" and "Notes" buttons (if the file does not exist, it is created)
Updated help with search operators page (page author knn)

0.5.2 (07.08.24)
Added replacement of quotes with a binary representation of the URL, i.e. by %22, since quotes are used in com string parameters.
Added icons for bottom row buttons
Added "Hold Window" button


0.5.1 (07.08.24)
Added search engine icons

0.5 (06.08.24)
Added intitle flag (search in titles)
In Linux, automatic copying of configs
The search delimiter is now "+" instead of a space, but when copied to the clipboard, the plus is replaced by a space.
If the word is not selected, but the domain is transmitted, then the word is taken from the clipboard
Fixed word truncation error when deleting a domain.
F2 - opens a draft file in the associated editor.
index.html can now be located in the config folder (Linux only) and can be opened using F1.
Lang.txt in the config folder can set the interface language.
Ctrl+Backspace - clear the word field and place the cursor on it to enter the word (Windows only).
AZJIO
Addict
Addict
Posts: 2154
Joined: Sun May 14, 2017 1:48 am

Re: [IDE Tool] AdvancedSearch

Post by AZJIO »

Added a temporary fork in the "AdvancedSearch2" folder, where domains can be distributed into sections.
One person added 100 domains, so I added sections if the list didn't fit on the screen.

Image
Post Reply