app_Main.py 458 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219
  1. # ###########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. # Modified by Marius Stanciu (2019) #
  8. # ###########################################################
  9. import urllib.request
  10. import urllib.parse
  11. import urllib.error
  12. import getopt
  13. import random
  14. import simplejson as json
  15. import shutil
  16. import lzma
  17. from datetime import datetime
  18. import time
  19. import ctypes
  20. import traceback
  21. from shapely.geometry import Point, MultiPolygon
  22. from io import StringIO
  23. from reportlab.graphics import renderPDF
  24. from reportlab.pdfgen import canvas
  25. from reportlab.lib.units import inch, mm
  26. from reportlab.lib.pagesizes import landscape, portrait
  27. from svglib.svglib import svg2rlg
  28. import gc
  29. from xml.dom.minidom import parseString as parse_xml_string
  30. from multiprocessing.connection import Listener, Client
  31. from multiprocessing import Pool
  32. import socket
  33. # ####################################################################################################################
  34. # ################################### Imports part of FlatCAM #############################################
  35. # ####################################################################################################################
  36. # Various
  37. from Common import LoudDict
  38. from Common import color_variant
  39. from Common import ExclusionAreas
  40. from Bookmark import BookmarkManager
  41. from appDatabase import ToolsDB2
  42. from vispy.gloo.util import _screenshot
  43. from vispy.io import write_png
  44. # FlatCAM defaults (preferences)
  45. from defaults import FlatCAMDefaults
  46. # FlatCAM Objects
  47. from appGUI.preferences.OptionsGroupUI import OptionsGroupUI
  48. from appGUI.preferences.PreferencesUIManager import PreferencesUIManager
  49. from appObjects.ObjectCollection import *
  50. from appObjects.FlatCAMObj import FlatCAMObj
  51. from appObjects.AppObject import AppObject
  52. # FlatCAM Parsing files
  53. from appParsers.ParseExcellon import Excellon
  54. from appParsers.ParseGerber import Gerber
  55. from camlib import to_dict, dict2obj, ET, ParseError, Geometry, CNCjob
  56. # FlatCAM appGUI
  57. from appGUI.PlotCanvas import *
  58. from appGUI.PlotCanvasLegacy import *
  59. from appGUI.MainGUI import *
  60. from appGUI.GUIElements import FCFileSaveDialog, message_dialog, FlatCAMSystemTray
  61. # FlatCAM Pre-processors
  62. from appPreProcessor import load_preprocessors
  63. # FlatCAM appEditors
  64. from appEditors.AppGeoEditor import AppGeoEditor
  65. from appEditors.AppExcEditor import AppExcEditor
  66. from appEditors.AppGerberEditor import AppGerberEditor
  67. from appEditors.AppTextEditor import AppTextEditor
  68. from appParsers.ParseHPGL2 import HPGL2
  69. # FlatCAM Workers
  70. from appProcess import *
  71. from appWorkerStack import WorkerStack
  72. # FlatCAM Tools
  73. from appTools import *
  74. # FlatCAM Translation
  75. import gettext
  76. import appTranslation as fcTranslate
  77. import builtins
  78. if sys.platform == 'win32':
  79. import winreg
  80. from win32comext.shell import shell, shellcon
  81. fcTranslate.apply_language('strings')
  82. if '_' not in builtins.__dict__:
  83. _ = gettext.gettext
  84. class App(QtCore.QObject):
  85. """
  86. The main application class. The constructor starts the GUI and all other classes used by the program.
  87. """
  88. # ###############################################################################################################
  89. # ########################################## App ################################################################
  90. # ###############################################################################################################
  91. # ###############################################################################################################
  92. # ######################################### LOGGING #############################################################
  93. # ###############################################################################################################
  94. log = logging.getLogger('base')
  95. log.setLevel(logging.DEBUG)
  96. # log.setLevel(logging.WARNING)
  97. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  98. handler = logging.StreamHandler()
  99. handler.setFormatter(formatter)
  100. log.addHandler(handler)
  101. # ###############################################################################################################
  102. # #################################### Get Cmd Line Options #####################################################
  103. # ###############################################################################################################
  104. cmd_line_shellfile = ''
  105. cmd_line_shellvar = ''
  106. cmd_line_headless = None
  107. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>\n" \
  108. "FlatCam.py --shellvar=<1,'C:\\path',23>\n" \
  109. "FlatCam.py --headless=1"
  110. try:
  111. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  112. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=",
  113. "shellvar=",
  114. "headless=",
  115. "multiprocessing-fork="])
  116. except getopt.GetoptError:
  117. print(cmd_line_help)
  118. sys.exit(2)
  119. for opt, arg in cmd_line_options:
  120. if opt == '-h':
  121. print(cmd_line_help)
  122. sys.exit()
  123. elif opt == '--shellfile':
  124. cmd_line_shellfile = arg
  125. elif opt == '--shellvar':
  126. cmd_line_shellvar = arg
  127. elif opt == '--headless':
  128. try:
  129. cmd_line_headless = eval(arg)
  130. except NameError:
  131. pass
  132. # ###############################################################################################################
  133. # ################################### Version and VERSION DATE ##################################################
  134. # ###############################################################################################################
  135. version = "Unstable Version"
  136. # version = 8.994
  137. version_date = "2020/07/05"
  138. beta = True
  139. engine = '3D'
  140. # current date now
  141. date = str(datetime.today()).rpartition('.')[0]
  142. date = ''.join(c for c in date if c not in ':-')
  143. date = date.replace(' ', '_')
  144. # ###############################################################################################################
  145. # ############################################ URLS's ###########################################################
  146. # ###############################################################################################################
  147. # URL for update checks and statistics
  148. version_url = "http://flatcam.org/version"
  149. # App URL
  150. app_url = "http://flatcam.org"
  151. # Manual URL
  152. manual_url = "http://flatcam.org/manual/index.html"
  153. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  154. gerber_spec_url = "https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  155. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  156. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  157. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  158. # this variable will hold the project status
  159. # if True it will mean that the project was modified and not saved
  160. should_we_save = False
  161. # flag is True if saving action has been triggered
  162. save_in_progress = False
  163. # ###############################################################################################################
  164. # ####################################### APP Signals ######################################################
  165. # ###############################################################################################################
  166. # Inform the user
  167. # Handled by: App.info() --> Print on the status bar
  168. inform = QtCore.pyqtSignal([str], [str, bool])
  169. # Handled by: App.info_shell() --> Print on the shell
  170. inform_shell = QtCore.pyqtSignal(str)
  171. app_quit = QtCore.pyqtSignal()
  172. # General purpose background task
  173. worker_task = QtCore.pyqtSignal(dict)
  174. # File opened
  175. # Handled by:
  176. # * register_folder()
  177. # * register_recent()
  178. # Note: Setting the parameters to unicode does not seem
  179. # to have an effect. Then are received as Qstring
  180. # anyway.
  181. # File type and filename
  182. file_opened = QtCore.pyqtSignal(str, str)
  183. # File type and filename
  184. file_saved = QtCore.pyqtSignal(str, str)
  185. # Percentage of progress
  186. progress = QtCore.pyqtSignal(int)
  187. # Emitted when a new object has been added or deleted from/to the collection
  188. object_status_changed = QtCore.pyqtSignal(object, str, str)
  189. message = QtCore.pyqtSignal(str, str, str)
  190. # Emmited when shell command is finished(one command only)
  191. shell_command_finished = QtCore.pyqtSignal(object)
  192. # Emitted when multiprocess pool has been recreated
  193. pool_recreated = QtCore.pyqtSignal(object)
  194. # Emitted when an unhandled exception happens
  195. # in the worker task.
  196. thread_exception = QtCore.pyqtSignal(object)
  197. # used to signal that there are arguments for the app
  198. args_at_startup = QtCore.pyqtSignal(list)
  199. # a reusable signal to replot a list of objects
  200. # should be disconnected after use so it can be reused
  201. replot_signal = pyqtSignal(list)
  202. # signal emitted when jumping
  203. jump_signal = pyqtSignal(tuple)
  204. # signal emitted when jumping
  205. locate_signal = pyqtSignal(tuple, str)
  206. # close app signal
  207. close_app_signal = pyqtSignal()
  208. # will perform the cleanup operation after a Graceful Exit
  209. # usefull for the NCC Tool and Paint Tool where some progressive plotting might leave
  210. # graphic residues behind
  211. cleanup = pyqtSignal()
  212. def __init__(self, user_defaults=True):
  213. """
  214. Starts the application.
  215. :return: app
  216. :rtype: App
  217. """
  218. super().__init__()
  219. App.log.info("FlatCAM Starting...")
  220. # ############################################################################################################
  221. # ################# Setup the listening thread for another instance launching with args ######################
  222. # ############################################################################################################
  223. if sys.platform == 'win32' or sys.platform == 'linux':
  224. # make sure the thread is stored by using a self. otherwise it's garbage collected
  225. self.listen_th = QtCore.QThread()
  226. self.listen_th.start(priority=QtCore.QThread.LowestPriority)
  227. self.new_launch = ArgsThread()
  228. self.new_launch.open_signal[list].connect(self.on_startup_args)
  229. self.new_launch.moveToThread(self.listen_th)
  230. self.new_launch.start.emit()
  231. # ############################################################################################################
  232. # ########################################## OS-specific #####################################################
  233. # ############################################################################################################
  234. portable = False
  235. # Folder for user settings.
  236. if sys.platform == 'win32':
  237. if platform.architecture()[0] == '32bit':
  238. App.log.debug("Win32!")
  239. else:
  240. App.log.debug("Win64!")
  241. # #######################################################################################################
  242. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY #############################################
  243. # #######################################################################################################
  244. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  245. try:
  246. with open(config_file, 'r'):
  247. pass
  248. except FileNotFoundError:
  249. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  250. try:
  251. with open(config_file, 'r') as f:
  252. try:
  253. for line in f:
  254. param = str(line).replace('\n', '').rpartition('=')
  255. if param[0] == 'portable':
  256. try:
  257. portable = eval(param[2])
  258. except NameError:
  259. portable = False
  260. if param[0] == 'headless':
  261. if param[2].lower() == 'true':
  262. self.cmd_line_headless = 1
  263. else:
  264. self.cmd_line_headless = None
  265. except Exception as e:
  266. log.debug('App.__init__() -->%s' % str(e))
  267. return
  268. except FileNotFoundError as e:
  269. log.debug(str(e))
  270. pass
  271. if portable is False:
  272. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  273. else:
  274. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  275. self.os = 'windows'
  276. else: # Linux/Unix/MacOS
  277. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  278. self.os = 'unix'
  279. # ############################################################################################################
  280. # ################################# Setup folders and files ##################################################
  281. # ############################################################################################################
  282. if not os.path.exists(self.data_path):
  283. os.makedirs(self.data_path)
  284. App.log.debug('Created data folder: ' + self.data_path)
  285. os.makedirs(os.path.join(self.data_path, 'preprocessors'))
  286. App.log.debug('Created data preprocessors folder: ' + os.path.join(self.data_path, 'preprocessors'))
  287. self.preprocessorpaths = os.path.join(self.data_path, 'preprocessors')
  288. if not os.path.exists(self.preprocessorpaths):
  289. os.makedirs(self.preprocessorpaths)
  290. App.log.debug('Created preprocessors folder: ' + self.preprocessorpaths)
  291. # create geo_tools_db.FlatDB file if there is none
  292. try:
  293. f = open(self.data_path + '/geo_tools_db.FlatDB')
  294. f.close()
  295. except IOError:
  296. App.log.debug('Creating empty geo_tool_db.FlatDB')
  297. f = open(self.data_path + '/geo_tools_db.FlatDB', 'w')
  298. json.dump({}, f)
  299. f.close()
  300. # create current_defaults.FlatConfig file if there is none
  301. try:
  302. f = open(self.data_path + '/current_defaults.FlatConfig')
  303. f.close()
  304. except IOError:
  305. App.log.debug('Creating empty current_defaults.FlatConfig')
  306. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  307. json.dump({}, f)
  308. f.close()
  309. # the factory defaults are written only once at the first launch of the application after installation
  310. FlatCAMDefaults.save_factory_defaults(os.path.join(self.data_path, "factory_defaults.FlatConfig"), self.version)
  311. # create a recent files json file if there is none
  312. try:
  313. f = open(self.data_path + '/recent.json')
  314. f.close()
  315. except IOError:
  316. App.log.debug('Creating empty recent.json')
  317. f = open(self.data_path + '/recent.json', 'w')
  318. json.dump([], f)
  319. f.close()
  320. # create a recent projects json file if there is none
  321. try:
  322. fp = open(self.data_path + '/recent_projects.json')
  323. fp.close()
  324. except IOError:
  325. App.log.debug('Creating empty recent_projects.json')
  326. fp = open(self.data_path + '/recent_projects.json', 'w')
  327. json.dump([], fp)
  328. fp.close()
  329. # Application directory. CHDIR to it. Otherwise, trying to load GUI icons will fail as their path is relative.
  330. # This will fail under cx_freeze ...
  331. self.app_home = os.path.dirname(os.path.realpath(__file__))
  332. log.debug("Application path is " + self.app_home)
  333. log.debug("Started in " + os.getcwd())
  334. # cx_freeze workaround
  335. if os.path.isfile(self.app_home):
  336. self.app_home = os.path.dirname(self.app_home)
  337. os.chdir(self.app_home)
  338. # ############################################################################################################
  339. # ################################# DEFAULTS - PREFERENCES STORAGE ###########################################
  340. # ############################################################################################################
  341. self.defaults = FlatCAMDefaults()
  342. self.defaults["root_folder_path"] = self.app_home
  343. current_defaults_path = os.path.join(self.data_path, "current_defaults.FlatConfig")
  344. if user_defaults:
  345. self.defaults.load(filename=current_defaults_path)
  346. if self.defaults['units'] == 'MM':
  347. self.decimals = int(self.defaults['decimals_metric'])
  348. else:
  349. self.decimals = int(self.defaults['decimals_inch'])
  350. if self.defaults["global_gray_icons"] is False:
  351. self.resource_location = 'assets/resources'
  352. else:
  353. self.resource_location = 'assets/resources/dark_resources'
  354. self.current_units = self.defaults['units']
  355. # ###########################################################################################################
  356. # #################################### SETUP OBJECT CLASSES #################################################
  357. # ###########################################################################################################
  358. self.setup_obj_classes()
  359. # ###########################################################################################################
  360. # ###################################### CREATE MULTIPROCESSING POOL #######################################
  361. # ###########################################################################################################
  362. self.pool = Pool()
  363. # ###########################################################################################################
  364. # ###################################### Clear GUI Settings - once at first start ###########################
  365. # ###########################################################################################################
  366. if self.defaults["first_run"] is True:
  367. # on first run clear the previous QSettings, therefore clearing the GUI settings
  368. qsettings = QSettings("Open Source", "FlatCAM")
  369. for key in qsettings.allKeys():
  370. qsettings.remove(key)
  371. # This will write the setting to the platform specific storage.
  372. del qsettings
  373. # ###########################################################################################################
  374. # ###################################### Setting the Splash Screen ##########################################
  375. # ###########################################################################################################
  376. splash_settings = QSettings("Open Source", "FlatCAM")
  377. if splash_settings.contains("splash_screen"):
  378. show_splash = splash_settings.value("splash_screen")
  379. else:
  380. splash_settings.setValue('splash_screen', 1)
  381. # This will write the setting to the platform specific storage.
  382. del splash_settings
  383. show_splash = 1
  384. if show_splash and self.cmd_line_headless != 1:
  385. splash_pix = QtGui.QPixmap(self.resource_location + '/splash.png')
  386. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  387. # self.splash.setMask(splash_pix.mask())
  388. # move splashscreen to the current monitor
  389. desktop = QtWidgets.QApplication.desktop()
  390. screen = desktop.screenNumber(QtGui.QCursor.pos())
  391. current_screen_center = desktop.availableGeometry(screen).center()
  392. self.splash.move(current_screen_center - self.splash.rect().center())
  393. self.splash.show()
  394. self.splash.showMessage(_("FlatCAM is initializing ..."),
  395. alignment=Qt.AlignBottom | Qt.AlignLeft,
  396. color=QtGui.QColor("gray"))
  397. else:
  398. show_splash = 0
  399. # ###########################################################################################################
  400. # ######################################### Initialize GUI ##################################################
  401. # ###########################################################################################################
  402. # FlatCAM colors used in plotting
  403. self.FC_light_green = '#BBF268BF'
  404. self.FC_dark_green = '#006E20BF'
  405. self.FC_light_blue = '#a5a5ffbf'
  406. self.FC_dark_blue = '#0000ffbf'
  407. theme_settings = QtCore.QSettings("Open Source", "FlatCAM")
  408. if theme_settings.contains("theme"):
  409. theme = theme_settings.value('theme', type=str)
  410. else:
  411. theme = 'white'
  412. if self.defaults["global_cursor_color_enabled"]:
  413. self.cursor_color_3D = self.defaults["global_cursor_color"]
  414. else:
  415. if theme == 'white':
  416. self.cursor_color_3D = 'black'
  417. else:
  418. self.cursor_color_3D = 'gray'
  419. # update the defaults dict with the setting in QSetting
  420. self.defaults['global_theme'] = theme
  421. self.ui = MainGUI(self)
  422. # set FlatCAM units in the Status bar
  423. self.set_screen_units(self.defaults['units'])
  424. # ###########################################################################################################
  425. # ########################################### AUTOSAVE SETUP ################################################
  426. # ###########################################################################################################
  427. self.block_autosave = False
  428. self.autosave_timer = QtCore.QTimer(self)
  429. self.save_project_auto_update()
  430. self.autosave_timer.timeout.connect(self.save_project_auto)
  431. # ###########################################################################################################
  432. # #################################### LOAD PREPROCESSORS ###################################################
  433. # ###########################################################################################################
  434. # ----------------------------------------- WARNING --------------------------------------------------------
  435. # Preprocessors need to be loaded before the Preferences Manager builds the Preferences
  436. # That's because the number of preprocessors can vary and here the comboboxes are populated
  437. # -----------------------------------------------------------------------------------------------------------
  438. # a dictionary that have as keys the name of the preprocessor files and the value is the class from
  439. # the preprocessor file
  440. self.preprocessors = load_preprocessors(self)
  441. # make sure that always the 'default' preprocessor is the first item in the dictionary
  442. if 'default' in self.preprocessors.keys():
  443. new_ppp_dict = {}
  444. # add the 'default' name first in the dict after removing from the preprocessor's dictionary
  445. default_pp = self.preprocessors.pop('default')
  446. new_ppp_dict['default'] = default_pp
  447. # then add the rest of the keys
  448. for name, val_class in self.preprocessors.items():
  449. new_ppp_dict[name] = val_class
  450. # and now put back the ordered dict with 'default' key first
  451. self.preprocessors = new_ppp_dict
  452. for name in list(self.preprocessors.keys()):
  453. # 'Paste' preprocessors are to be used only in the Solder Paste Dispensing Tool
  454. if name.partition('_')[0] == 'Paste':
  455. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  456. continue
  457. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  458. # HPGL preprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  459. if name == 'hpgl':
  460. continue
  461. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  462. # ###########################################################################################################
  463. # ##################################### UPDATE PREFERENCES GUI FORMS ########################################
  464. # ###########################################################################################################
  465. self.preferencesUiManager = PreferencesUIManager(defaults=self.defaults, data_path=self.data_path, ui=self.ui,
  466. inform=self.inform)
  467. self.preferencesUiManager.defaults_write_form()
  468. # When the self.defaults dictionary changes will update the Preferences GUI forms
  469. self.defaults.set_change_callback(self.on_defaults_dict_change)
  470. # ###########################################################################################################
  471. # ##################################### FIRST RUN SECTION ###################################################
  472. # ################################ It's done only once after install #####################################
  473. # ###########################################################################################################
  474. if self.defaults["first_run"] is True:
  475. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'minimal'
  476. initial_lay = 'minimal'
  477. self.ui.general_defaults_form.general_gui_group.on_layout(lay=initial_lay)
  478. # Set the combobox in Preferences to the current layout
  479. idx = self.ui.general_defaults_form.general_gui_group.layout_combo.findText(initial_lay)
  480. self.ui.general_defaults_form.general_gui_group.layout_combo.setCurrentIndex(idx)
  481. # after the first run, this object should be False
  482. self.defaults["first_run"] = False
  483. self.preferencesUiManager.save_defaults(silent=True)
  484. # ###########################################################################################################
  485. # ############################################ Data #########################################################
  486. # ###########################################################################################################
  487. self.recent = []
  488. self.recent_projects = []
  489. self.clipboard = QtWidgets.QApplication.clipboard()
  490. self.project_filename = None
  491. self.toggle_units_ignore = False
  492. self.main_thread = QtWidgets.QApplication.instance().thread()
  493. # ###########################################################################################################
  494. # ########################################## LOAD LANGUAGES ################################################
  495. # ###########################################################################################################
  496. self.languages = fcTranslate.load_languages()
  497. for name in sorted(self.languages.values()):
  498. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  499. # ###########################################################################################################
  500. # ####################################### APPLY APP LANGUAGE ################################################
  501. # ###########################################################################################################
  502. ret_val = fcTranslate.apply_language('strings')
  503. if ret_val == "no language":
  504. self.inform.emit('[ERROR] %s' % _("Could not find the Language files. The App strings are missing."))
  505. log.debug("Could not find the Language files. The App strings are missing.")
  506. else:
  507. # make the current language the current selection on the language combobox
  508. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  509. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  510. # ###########################################################################################################
  511. # ###################################### CREATE UNIQUE SERIAL NUMBER ########################################
  512. # ###########################################################################################################
  513. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  514. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  515. self.defaults['global_serial'] = ''.join([random.choice(chars) for __ in range(20)])
  516. self.preferencesUiManager.save_defaults(silent=True, first_time=True)
  517. self.defaults.propagate_defaults()
  518. # ###########################################################################################################
  519. # ######################################## UPDATE THE OPTIONS ###############################################
  520. # ###########################################################################################################
  521. self.options = LoudDict()
  522. # -----------------------------------------------------------------------------------------------------------
  523. # Update the self.options from the self.defaults
  524. # The self.defaults holds the application defaults while the self.options holds the object defaults
  525. # -----------------------------------------------------------------------------------------------------------
  526. # Copy app defaults to project options
  527. for def_key, def_val in self.defaults.items():
  528. self.options[def_key] = deepcopy(def_val)
  529. self.preferencesUiManager.show_preferences_gui()
  530. # ### End of Data ####
  531. # ###########################################################################################################
  532. # #################################### SETUP OBJECT COLLECTION ##############################################
  533. # ###########################################################################################################
  534. self.collection = ObjectCollection(app=self)
  535. self.ui.project_tab_layout.addWidget(self.collection.view)
  536. self.app_obj = AppObject(app=self)
  537. # ### Adjust tabs width ## ##
  538. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  539. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  540. self.collection.view.setMinimumWidth(290)
  541. self.log.debug("Finished creating Object Collection.")
  542. # ###########################################################################################################
  543. # ######################################## SETUP Plot Area ##################################################
  544. # ###########################################################################################################
  545. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  546. if self.defaults["global_graphic_engine"] == '3D':
  547. self.is_legacy = False
  548. else:
  549. self.is_legacy = True
  550. # Event signals disconnect id holders
  551. self.mp = None
  552. self.mm = None
  553. self.mr = None
  554. self.mdc = None
  555. self.mp_zc = None
  556. self.kp = None
  557. # Matplotlib axis
  558. self.axes = None
  559. if show_splash:
  560. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  561. "Canvas initialization started."),
  562. alignment=Qt.AlignBottom | Qt.AlignLeft,
  563. color=QtGui.QColor("gray"))
  564. start_plot_time = time.time() # debug
  565. self.plotcanvas = None
  566. self.app_cursor = None
  567. self.hover_shapes = None
  568. self.log.debug("Setting up canvas: %s" % str(self.defaults["global_graphic_engine"]))
  569. # setup the PlotCanvas
  570. self.on_plotcanvas_setup()
  571. end_plot_time = time.time()
  572. self.used_time = end_plot_time - start_plot_time
  573. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  574. if show_splash:
  575. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  576. "Canvas initialization started.\n"
  577. "Canvas initialization finished in"), '%.2f' % self.used_time),
  578. alignment=Qt.AlignBottom | Qt.AlignLeft,
  579. color=QtGui.QColor("gray"))
  580. self.ui.splitter.setStretchFactor(1, 2)
  581. # ###########################################################################################################
  582. # ############################################### SYS TRAY ##################################################
  583. # ###########################################################################################################
  584. if self.defaults["global_systray_icon"]:
  585. self.parent_w = QtWidgets.QWidget()
  586. if self.cmd_line_headless == 1:
  587. self.trayIcon = FlatCAMSystemTray(app=self,
  588. icon=QtGui.QIcon(self.resource_location +
  589. '/flatcam_icon32_green.png'),
  590. headless=True,
  591. parent=self.parent_w)
  592. else:
  593. self.trayIcon = FlatCAMSystemTray(app=self,
  594. icon=QtGui.QIcon(self.resource_location +
  595. '/flatcam_icon32_green.png'),
  596. parent=self.parent_w)
  597. # ###########################################################################################################
  598. # ############################################### Worker SETUP ##############################################
  599. # ###########################################################################################################
  600. if self.defaults["global_worker_number"]:
  601. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  602. else:
  603. self.workers = WorkerStack(workers_number=2)
  604. self.worker_task.connect(self.workers.add_task)
  605. self.log.debug("Finished creating Workers crew.")
  606. # ###########################################################################################################
  607. # ############################################# Activity Monitor ###########################################
  608. # ###########################################################################################################
  609. # self.activity_view = FlatCAMActivityView(app=self)
  610. # self.ui.infobar.addWidget(self.activity_view)
  611. self.proc_container = FCVisibleProcessContainer(self.ui.activity_view)
  612. # ###########################################################################################################
  613. # ############################################# Signal handling #############################################
  614. # ###########################################################################################################
  615. # ########################################## Custom signals ################################################
  616. # signal for displaying messages in status bar
  617. self.inform[str].connect(self.info)
  618. self.inform[str, bool].connect(self.info)
  619. # signal for displaying messages in the shell
  620. self.inform_shell.connect(self.info_shell)
  621. # signal to be called when the app is quiting
  622. self.app_quit.connect(self.quit_application, type=Qt.QueuedConnection)
  623. self.message.connect(lambda: message_dialog(parent=self.ui))
  624. # self.progress.connect(self.set_progress_bar)
  625. # signals emitted when file state change
  626. self.file_opened.connect(self.register_recent)
  627. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  628. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  629. # ########################################## Standard signals ###############################################
  630. # ### Menu
  631. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  632. self.ui.menufilenewgeo.triggered.connect(self.app_obj.new_geometry_object)
  633. self.ui.menufilenewgrb.triggered.connect(self.app_obj.new_gerber_object)
  634. self.ui.menufilenewexc.triggered.connect(self.app_obj.new_excellon_object)
  635. self.ui.menufilenewdoc.triggered.connect(self.app_obj.new_document_object)
  636. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  637. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  638. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  639. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  640. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  641. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  642. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  643. self.ui.menufileopenscriptexample.triggered.connect(self.on_fileopenscript_example)
  644. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  645. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  646. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  647. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  648. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  649. self.ui.menufileimport_hpgl2_as_geo.triggered.connect(self.on_fileopenhpgl2)
  650. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  651. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  652. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  653. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  654. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  655. self.ui.menufile_print.triggered.connect(lambda: self.on_file_save_objects_pdf(use_thread=True))
  656. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  657. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  658. # self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  659. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  660. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  661. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  662. self.ui.menufile_exit.triggered.connect(self.final_save)
  663. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  664. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  665. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  666. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  667. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  668. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  669. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  670. self.ui.menueditdelete.triggered.connect(self.on_delete)
  671. self.ui.menueditcopyobject.triggered.connect(self.on_copy_command)
  672. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  673. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  674. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  675. self.ui.menuedit_move2origin.triggered.connect(self.on_move2origin)
  676. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  677. self.ui.menueditlocate.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  678. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  679. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  680. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  681. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  682. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  683. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  684. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  685. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  686. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  687. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  688. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  689. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  690. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  691. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  692. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  693. self.ui.menuoptions_tools_db.triggered.connect(lambda: self.on_tools_database(source='app'))
  694. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  695. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  696. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  697. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  698. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  699. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  700. self.ui.menuview_replot.triggered.connect(self.plot_all)
  701. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  702. self.ui.menuview_toggle_fscreen.triggered.connect(self.ui.on_fullscreen)
  703. self.ui.menuview_toggle_parea.triggered.connect(self.ui.on_toggle_plotarea)
  704. self.ui.menuview_toggle_notebook.triggered.connect(self.ui.on_toggle_notebook)
  705. self.ui.menu_toggle_nb.triggered.connect(self.ui.on_toggle_notebook)
  706. self.ui.menuview_toggle_grid.triggered.connect(self.ui.on_toggle_grid)
  707. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_toggle)
  708. self.ui.menuview_toggle_grid_lines.triggered.connect(self.plotcanvas.on_toggle_grid_lines)
  709. self.ui.menuview_toggle_axis.triggered.connect(self.plotcanvas.on_toggle_axis)
  710. self.ui.menuview_toggle_hud.triggered.connect(self.plotcanvas.on_toggle_hud)
  711. self.ui.menutoolshell.triggered.connect(self.ui.toggle_shell_ui)
  712. self.ui.menuhelp_about.triggered.connect(self.on_about)
  713. self.ui.menuhelp_readme.triggered.connect(self.on_readme)
  714. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  715. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  716. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  717. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  718. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  719. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  720. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  721. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  722. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  723. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  724. self.ui.menuprojectcopy.triggered.connect(self.on_copy_command)
  725. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  726. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  727. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  728. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  729. # ToolBar signals
  730. self.connect_toolbar_signals(ui=self.ui)
  731. # Context Menu
  732. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  733. self.ui.popmenu_panel_toggle.triggered.connect(self.ui.on_toggle_notebook)
  734. self.ui.popmenu_new_geo.triggered.connect(self.app_obj.new_geometry_object)
  735. self.ui.popmenu_new_grb.triggered.connect(self.app_obj.new_gerber_object)
  736. self.ui.popmenu_new_exc.triggered.connect(self.app_obj.new_excellon_object)
  737. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  738. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  739. self.ui.clearplot.triggered.connect(self.clear_plots)
  740. self.ui.replot.triggered.connect(self.plot_all)
  741. self.ui.popmenu_copy.triggered.connect(self.on_copy_command)
  742. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  743. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  744. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  745. self.ui.popmenu_move.triggered.connect(self.obj_move)
  746. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  747. # Project Context Menu -> Color Setting
  748. for act in self.ui.menuprojectcolor.actions():
  749. act.triggered.connect(self.on_set_color_action_triggered)
  750. # ###########################################################################################################
  751. # #################################### GUI PREFERENCES SIGNALS ##############################################
  752. # ###########################################################################################################
  753. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  754. lambda: self.on_toggle_units(no_pref=False))
  755. # ##################################### Workspace Setting Signals ###########################################
  756. self.ui.general_defaults_form.general_app_set_group.wk_cb.currentIndexChanged.connect(
  757. self.on_workspace_modified)
  758. self.ui.general_defaults_form.general_app_set_group.wk_orientation_radio.activated_custom.connect(
  759. self.on_workspace_modified
  760. )
  761. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  762. # ###########################################################################################################
  763. # ######################################## GUI SETTINGS SIGNALS #############################################
  764. # ###########################################################################################################
  765. self.ui.general_defaults_form.general_app_set_group.cursor_radio.activated_custom.connect(self.on_cursor_type)
  766. # ######################################## Tools related signals ############################################
  767. # portability changed signal
  768. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  769. # Object list
  770. self.object_status_changed.connect(self.collection.on_collection_updated)
  771. # when there are arguments at application startup this get launched
  772. self.args_at_startup[list].connect(self.on_startup_args)
  773. # ###########################################################################################################
  774. # ####################################### FILE ASSOCIATIONS SIGNALS #########################################
  775. # ###########################################################################################################
  776. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  777. lambda: self.restore_extensions(ext_type='excellon'))
  778. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  779. lambda: self.restore_extensions(ext_type='gcode'))
  780. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  781. lambda: self.restore_extensions(ext_type='gerber'))
  782. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  783. lambda: self.delete_all_extensions(ext_type='excellon'))
  784. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  785. lambda: self.delete_all_extensions(ext_type='gcode'))
  786. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  787. lambda: self.delete_all_extensions(ext_type='gerber'))
  788. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  789. lambda: self.add_extension(ext_type='excellon'))
  790. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  791. lambda: self.add_extension(ext_type='gcode'))
  792. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  793. lambda: self.add_extension(ext_type='gerber'))
  794. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  795. lambda: self.del_extension(ext_type='excellon'))
  796. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  797. lambda: self.del_extension(ext_type='gcode'))
  798. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  799. lambda: self.del_extension(ext_type='gerber'))
  800. # connect the 'Apply' buttons from the Preferences/File Associations
  801. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  802. lambda: self.on_register_files(obj_type='excellon'))
  803. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  804. lambda: self.on_register_files(obj_type='gcode'))
  805. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  806. lambda: self.on_register_files(obj_type='gerber'))
  807. # ###########################################################################################################
  808. # ########################################### KEYWORDS SIGNALS ##############################################
  809. # ###########################################################################################################
  810. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  811. lambda: self.restore_extensions(ext_type='keyword'))
  812. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  813. lambda: self.delete_all_extensions(ext_type='keyword'))
  814. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  815. lambda: self.add_extension(ext_type='keyword'))
  816. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  817. lambda: self.del_extension(ext_type='keyword'))
  818. # ###########################################################################################################
  819. # ########################################### GUI SIGNALS ###################################################
  820. # ###########################################################################################################
  821. self.ui.hud_label.clicked.connect(self.plotcanvas.on_toggle_hud)
  822. self.ui.axis_status_label.clicked.connect(self.plotcanvas.on_toggle_axis)
  823. self.ui.pref_status_label.clicked.connect(self.on_toggle_preferences)
  824. # ###########################################################################################################
  825. # ####################################### VARIOUS SIGNALS ###################################################
  826. # ###########################################################################################################
  827. # connect the abort_all_tasks related slots to the related signals
  828. self.proc_container.idle_flag.connect(self.app_is_idle)
  829. # signal emitted when a tab is closed in the Plot Area
  830. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  831. # signal to close the application
  832. self.close_app_signal.connect(self.kill_app)
  833. # ################################# FINISHED CONNECTING SIGNALS #############################################
  834. # ###########################################################################################################
  835. # ###########################################################################################################
  836. # ###########################################################################################################
  837. self.log.debug("Finished connecting Signals.")
  838. # ###########################################################################################################
  839. # ########################################## Other setups ###################################################
  840. # ###########################################################################################################
  841. # to use for tools like Distance tool who depends on the event sources who are changed inside the appEditors
  842. # depending on from where those tools are called different actions can be done
  843. self.call_source = 'app'
  844. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  845. self.tool_tab_locked = False
  846. # decide if to show or hide the Notebook side of the screen at startup
  847. if self.defaults["global_project_at_startup"] is True:
  848. self.ui.splitter.setSizes([1, 1])
  849. else:
  850. self.ui.splitter.setSizes([0, 1])
  851. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  852. self.setup_component_editor()
  853. # ###########################################################################################################
  854. # ####################################### Auto-complete KEYWORDS ############################################
  855. # ###########################################################################################################
  856. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  857. 'aligndrill', 'aligndrillgrid', 'bbox', 'clear', 'cncjob', 'cutout',
  858. 'del', 'drillcncjob', 'export_dxf', 'edxf', 'export_excellon',
  859. 'export_exc',
  860. 'export_gcode', 'export_gerber', 'export_svg', 'ext', 'exteriors', 'follow',
  861. 'geo_union', 'geocutout', 'get_bounds', 'get_names', 'get_path', 'get_sys', 'help',
  862. 'interiors', 'isolate', 'join_excellon',
  863. 'join_geometry', 'list_sys', 'milld', 'mills', 'milldrills', 'millslots',
  864. 'mirror', 'ncc',
  865. 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  866. 'open_dxf', 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'open_svg',
  867. 'options', 'origin',
  868. 'paint', 'panelize', 'plot_all', 'plot_objects', 'plot_status', 'quit_flatcam',
  869. 'save', 'save_project',
  870. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_path', 'set_sys',
  871. 'skew', 'subtract_poly', 'subtract_rectangle',
  872. 'version', 'write_gcode'
  873. ]
  874. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'False', 'Marius', 'My Documents',
  875. 'Paste_1',
  876. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  877. 'Toolchange_manual', 'True', 'Users',
  878. 'all', 'auto', 'axis',
  879. 'axisoffset', 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect',
  880. 'contour', 'default',
  881. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dpp',
  882. 'dwelltime', 'extracut_length', 'endxy', 'enz', 'f', 'feedrate',
  883. 'feedrate_z', 'grbl_11', 'GRBL_laser', 'gridoffsety', 'gridx', 'gridy',
  884. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  885. 'milled_dias', 'minoffset', 'name', 'offset', 'opt_type', 'order',
  886. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  887. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  888. 'spacing_columns',
  889. 'spacing_rows', 'spindlespeed', 'startz', 'startxy',
  890. 'toolchange_xy', 'toolchangez', 'travelz',
  891. 'tooldia', 'use_threads', 'value',
  892. 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  893. ]
  894. self.tcl_keywords = [
  895. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  896. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  897. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  898. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  899. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  900. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  901. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  902. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  903. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  904. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  905. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  906. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  907. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  908. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  909. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  910. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  911. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  912. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  913. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  914. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  915. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  916. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  917. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  918. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  919. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  920. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  921. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  922. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  923. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  924. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  925. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  926. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  927. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  928. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  929. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  930. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  931. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  932. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  933. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  934. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  935. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  936. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  937. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  938. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  939. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  940. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  941. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  942. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  943. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  944. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  945. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  946. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  947. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  948. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  949. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  950. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  951. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  952. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  953. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  954. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  955. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  956. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  957. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  958. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  959. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  960. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  961. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  962. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  963. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  964. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  965. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  966. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  967. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  968. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  969. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  970. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  971. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  972. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  973. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  974. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  975. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  976. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  977. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  978. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  979. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  980. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  981. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  982. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  983. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  984. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  985. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  986. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  987. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  988. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  989. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  990. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  991. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  992. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  993. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  994. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  995. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  996. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  997. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  998. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  999. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  1000. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  1001. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  1002. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  1003. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  1004. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  1005. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  1006. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  1007. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  1008. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  1009. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  1010. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  1011. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  1012. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  1013. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  1014. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  1015. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  1016. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1017. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1018. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1019. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1020. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1021. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1022. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1023. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1024. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1025. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1026. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1027. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1028. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1029. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1030. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1031. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1032. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1033. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1034. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1035. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1036. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1037. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1038. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1039. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1040. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1041. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1042. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1043. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1044. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1045. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  1046. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  1047. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  1048. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  1049. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  1050. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  1051. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  1052. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  1053. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  1054. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  1055. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  1056. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  1057. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  1058. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  1059. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  1060. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  1061. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  1062. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  1063. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  1064. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  1065. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  1066. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  1067. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  1068. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  1069. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  1070. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  1071. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  1072. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  1073. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  1074. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  1075. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  1076. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  1077. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  1078. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  1079. ]
  1080. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  1081. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  1082. # ###########################################################################################################
  1083. # ########################################## Tools and Plugins ##############################################
  1084. # ###########################################################################################################
  1085. self.shell = None
  1086. self.dblsidedtool = None
  1087. self.distance_tool = None
  1088. self.distance_min_tool = None
  1089. self.panelize_tool = None
  1090. self.film_tool = None
  1091. self.paste_tool = None
  1092. self.calculator_tool = None
  1093. self.rules_tool = None
  1094. self.sub_tool = None
  1095. self.move_tool = None
  1096. self.cutout_tool = None
  1097. self.ncclear_tool = None
  1098. self.paint_tool = None
  1099. self.isolation_tool = None
  1100. self.drilling_tool = None
  1101. self.optimal_tool = None
  1102. self.transform_tool = None
  1103. self.properties_tool = None
  1104. self.pdf_tool = None
  1105. self.image_tool = None
  1106. self.pcb_wizard_tool = None
  1107. self.cal_exc_tool = None
  1108. self.qrcode_tool = None
  1109. self.copper_thieving_tool = None
  1110. self.fiducial_tool = None
  1111. self.edrills_tool = None
  1112. self.align_objects_tool = None
  1113. self.punch_tool = None
  1114. self.invert_tool = None
  1115. self.corners_tool = None
  1116. self.etch_tool = None
  1117. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1118. try:
  1119. self.install_tools()
  1120. except AttributeError as e:
  1121. log.debug("App.__init__() install_tools() --> %s" % str(e))
  1122. # ###########################################################################################################
  1123. # ############################################ SETUP RECENT ITEMS ###########################################
  1124. # ###########################################################################################################
  1125. self.setup_recent_items()
  1126. # ###########################################################################################################
  1127. # ######################################### BookMarks Manager ###############################################
  1128. # ###########################################################################################################
  1129. # install Bookmark Manager and populate bookmarks in the Help -> Bookmarks
  1130. self.install_bookmarks()
  1131. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"])
  1132. # ###########################################################################################################
  1133. # ########################################### Tools Database ################################################
  1134. # ###########################################################################################################
  1135. self.tools_db_tab = None
  1136. # ### System Font Parsing ###
  1137. # self.f_parse = ParseFont(self)
  1138. # self.parse_system_fonts()
  1139. # ###########################################################################################################
  1140. # ############################################## Shell SETUP ################################################
  1141. # ###########################################################################################################
  1142. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1143. if self.defaults["global_shell_at_startup"]:
  1144. self.ui.shell_dock.show()
  1145. else:
  1146. self.ui.shell_dock.hide()
  1147. # ###########################################################################################################
  1148. # ######################################### Check for updates ###############################################
  1149. # ###########################################################################################################
  1150. # Separate thread (Not worker)
  1151. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1152. if (self.beta is False or self.beta is None) and \
  1153. self.ui.general_defaults_form.general_app_group.version_check_cb.get_value() is True:
  1154. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1155. # self.thr2 = QtCore.QThread()
  1156. self.worker_task.emit({'fcn': self.version_check,
  1157. 'params': []})
  1158. # self.thr2.start(QtCore.QThread.LowPriority)
  1159. # ###########################################################################################################
  1160. # ##################################### Register files with FlatCAM; #######################################
  1161. # ################################### It works only for Windows for now ####################################
  1162. # ###########################################################################################################
  1163. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  1164. self.on_register_files()
  1165. # ###########################################################################################################
  1166. # ######################################## Variables for global usage #######################################
  1167. # ###########################################################################################################
  1168. # hold the App units
  1169. self.units = 'MM'
  1170. # coordinates for relative position display
  1171. self.rel_point1 = (0, 0)
  1172. self.rel_point2 = (0, 0)
  1173. # variable to store coordinates
  1174. self.pos = (0, 0)
  1175. self.pos_canvas = (0, 0)
  1176. self.pos_jump = (0, 0)
  1177. # variable to store mouse coordinates
  1178. self.mouse = [0, 0]
  1179. # variable to store the delta positions on cavnas
  1180. self.dx = 0
  1181. self.dy = 0
  1182. # decide if we have a double click or single click
  1183. self.doubleclick = False
  1184. # store here the is_dragging value
  1185. self.event_is_dragging = False
  1186. # variable to store if a command is active (then the var is not None) and which one it is
  1187. self.command_active = None
  1188. # variable to store the status of moving selection action
  1189. # None value means that it's not an selection action
  1190. # True value = a selection from left to right
  1191. # False value = a selection from right to left
  1192. self.selection_type = None
  1193. # List to store the objects that are currently loaded in FlatCAM
  1194. # This list is updated on each object creation or object delete
  1195. self.all_objects_list = []
  1196. self.objects_under_the_click_list = []
  1197. # List to store the objects that are selected
  1198. self.sel_objects_list = []
  1199. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1200. self.key_modifiers = None
  1201. # Variable to store the status of the code editor
  1202. self.toggle_codeeditor = False
  1203. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  1204. self.click_noproject = False
  1205. self.cursor = None
  1206. # Variable to store the GCODE that was edited
  1207. self.gcode_edited = ""
  1208. self.text_editor_tab = None
  1209. # reference for the self.ui.code_editor
  1210. self.reference_code_editor = None
  1211. self.script_code = ''
  1212. # if Tools DB are changed/edited in the Edit -> Tools Database tab the value will be set to True
  1213. self.tools_db_changed_flag = False
  1214. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  1215. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  1216. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'outline',
  1217. 'pho', 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top',
  1218. 'tsm']
  1219. self.exc_list = ['drd', 'drl', 'drill', 'exc', 'ncd', 'tap', 'txt', 'xln']
  1220. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  1221. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ngc', 'ncp', 'out', 'ply', 'rol',
  1222. 'sbp', 'tap', 'xpi']
  1223. self.svg_list = ['svg']
  1224. self.dxf_list = ['dxf']
  1225. self.pdf_list = ['pdf']
  1226. self.prj_list = ['flatprj']
  1227. self.conf_list = ['flatconfig']
  1228. # last used filters
  1229. self.last_op_gerber_filter = None
  1230. self.last_op_excellon_filter = None
  1231. self.last_op_gcode_filter = None
  1232. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1233. # flag for polygons not cleared
  1234. self.poly_not_cleared = False
  1235. # VisPy visuals
  1236. self.isHovering = False
  1237. self.notHovering = True
  1238. # Window geometry
  1239. self.x_pos = None
  1240. self.y_pos = None
  1241. self.width = None
  1242. self.height = None
  1243. # when True, the app has to return from any thread
  1244. self.abort_flag = False
  1245. # set the value used in the Windows Title
  1246. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  1247. # this holds a widget that is installed in the Plot Area when View Source option is used
  1248. self.source_editor_tab = None
  1249. self.pagesize = {}
  1250. # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry
  1251. # VisPy visuals
  1252. if self.is_legacy is False:
  1253. try:
  1254. self.tool_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  1255. except AttributeError:
  1256. self.tool_shapes = None
  1257. else:
  1258. from appGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  1259. self.tool_shapes = ShapeCollectionLegacy(obj=self, app=self, name="tool")
  1260. # used in the delayed shutdown self.start_delayed_quit() method
  1261. self.save_timer = None
  1262. # ###########################################################################################################
  1263. # ################################## ADDING FlatCAM EDITORS section #########################################
  1264. # ###########################################################################################################
  1265. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  1266. # at the first launch of the App , the editors will not be functional.
  1267. try:
  1268. self.geo_editor = AppGeoEditor(self)
  1269. except Exception as es:
  1270. log.debug("app_Main.__init__() --> Geo Editor Error: %s" % str(es))
  1271. try:
  1272. self.exc_editor = AppExcEditor(self)
  1273. except Exception as es:
  1274. log.debug("app_Main.__init__() --> Excellon Editor Error: %s" % str(es))
  1275. try:
  1276. self.grb_editor = AppGerberEditor(self)
  1277. except Exception as es:
  1278. log.debug("app_Main.__init__() --> Gerber Editor Error: %s" % str(es))
  1279. self.log.debug("Finished adding FlatCAM Editor's.")
  1280. self.set_ui_title(name=_("New Project - Not saved"))
  1281. # disable the Excellon path optimizations made with Google OR-Tools if the app is run on a 32bit platform
  1282. current_platform = platform.architecture()[0]
  1283. if current_platform != '64bit':
  1284. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  1285. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.setDisabled(True)
  1286. # ###########################################################################################################
  1287. # ########################################### EXCLUSION AREAS ###############################################
  1288. # ###########################################################################################################
  1289. self.exc_areas = ExclusionAreas(app=self)
  1290. # ###########################################################################################################
  1291. # ##################################### Finished the CONSTRUCTOR ############################################
  1292. # ###########################################################################################################
  1293. App.log.debug("END of constructor. Releasing control.")
  1294. # ###########################################################################################################
  1295. # ########################################## SHOW GUI #######################################################
  1296. # ###########################################################################################################
  1297. # if the app is not started as headless, show it
  1298. if self.cmd_line_headless != 1:
  1299. if show_splash:
  1300. # finish the splash
  1301. self.splash.finish(self.ui)
  1302. mgui_settings = QSettings("Open Source", "FlatCAM")
  1303. if mgui_settings.contains("maximized_gui"):
  1304. maximized_ui = mgui_settings.value('maximized_gui', type=bool)
  1305. if maximized_ui is True:
  1306. self.ui.showMaximized()
  1307. else:
  1308. self.ui.show()
  1309. else:
  1310. self.ui.show()
  1311. if self.defaults["global_systray_icon"]:
  1312. self.trayIcon.show()
  1313. else:
  1314. log.warning("******************* RUNNING HEADLESS *******************")
  1315. # ###########################################################################################################
  1316. # ######################################## START-UP ARGUMENTS ###############################################
  1317. # ###########################################################################################################
  1318. # test if the program was started with a script as parameter
  1319. if self.cmd_line_shellvar:
  1320. try:
  1321. cnt = 0
  1322. command_tcl = 0
  1323. for i in self.cmd_line_shellvar.split(','):
  1324. if i is not None:
  1325. # noinspection PyBroadException
  1326. try:
  1327. command_tcl = eval(i)
  1328. except Exception:
  1329. command_tcl = i
  1330. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  1331. cnt += 1
  1332. # if there are Windows paths then replace the path separator with a Unix like one
  1333. if sys.platform == 'win32':
  1334. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  1335. self.shell.exec_command(command_tcl_formatted, no_echo=True)
  1336. except Exception as ext:
  1337. print("ERROR: ", ext)
  1338. sys.exit(2)
  1339. if self.cmd_line_shellfile:
  1340. if self.cmd_line_headless != 1:
  1341. if self.ui.shell_dock.isHidden():
  1342. self.ui.shell_dock.show()
  1343. try:
  1344. with open(self.cmd_line_shellfile, "r") as myfile:
  1345. # if show_splash:
  1346. # self.splash.showMessage('%s: %ssec\n%s' % (
  1347. # _("Canvas initialization started.\n"
  1348. # "Canvas initialization finished in"), '%.2f' % self.used_time,
  1349. # _("Executing Tcl Script ...")),
  1350. # alignment=Qt.AlignBottom | Qt.AlignLeft,
  1351. # color=QtGui.QColor("gray"))
  1352. cmd_line_shellfile_text = myfile.read()
  1353. if self.cmd_line_headless != 1:
  1354. self.shell.exec_command(cmd_line_shellfile_text)
  1355. else:
  1356. self.shell.exec_command(cmd_line_shellfile_text, no_echo=True)
  1357. except Exception as ext:
  1358. print("ERROR: ", ext)
  1359. sys.exit(2)
  1360. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  1361. # the path/file_name must be enclosed in quotes if it contain spaces
  1362. if App.args:
  1363. self.args_at_startup.emit(App.args)
  1364. if self.defaults.old_defaults_found is True:
  1365. self.inform.emit('[WARNING_NOTCL] %s' % _("Found old default preferences files. "
  1366. "Please reboot the application to update."))
  1367. self.defaults.old_defaults_found = False
  1368. # ######################################### INIT FINISHED #######################################################
  1369. # #################################################################################################################
  1370. # #################################################################################################################
  1371. # #################################################################################################################
  1372. # #################################################################################################################
  1373. # #################################################################################################################
  1374. @staticmethod
  1375. def copy_and_overwrite(from_path, to_path):
  1376. """
  1377. From here:
  1378. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  1379. :param from_path: source path
  1380. :param to_path: destination path
  1381. :return: None
  1382. """
  1383. if os.path.exists(to_path):
  1384. shutil.rmtree(to_path)
  1385. try:
  1386. shutil.copytree(from_path, to_path)
  1387. except FileNotFoundError:
  1388. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\appGUI\\VisPyData\\data'
  1389. shutil.copytree(from_new_path, to_path)
  1390. def on_startup_args(self, args, silent=False):
  1391. """
  1392. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  1393. :param silent: when True it will not print messages on Tcl Shell and/or status bar
  1394. :param args: a list containing the application args at startup
  1395. :return: None
  1396. """
  1397. if args is not None:
  1398. args_to_process = args
  1399. else:
  1400. args_to_process = App.args
  1401. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  1402. for argument in args_to_process:
  1403. if '.FlatPrj'.lower() in argument.lower():
  1404. try:
  1405. project_name = str(argument)
  1406. if project_name == "":
  1407. if silent is False:
  1408. self.inform.emit(_("Cancelled."))
  1409. else:
  1410. # self.open_project(project_name)
  1411. run_from_arg = True
  1412. # self.worker_task.emit({'fcn': self.open_project,
  1413. # 'params': [project_name, run_from_arg]})
  1414. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  1415. except Exception as e:
  1416. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1417. elif '.FlatConfig'.lower() in argument.lower():
  1418. try:
  1419. file_name = str(argument)
  1420. if file_name == "":
  1421. if silent is False:
  1422. self.inform.emit(_("Open Config file failed."))
  1423. else:
  1424. run_from_arg = True
  1425. # self.worker_task.emit({'fcn': self.open_config_file,
  1426. # 'params': [file_name, run_from_arg]})
  1427. self.open_config_file(file_name, run_from_arg=run_from_arg)
  1428. except Exception as e:
  1429. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1430. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  1431. try:
  1432. file_name = str(argument)
  1433. if file_name == "":
  1434. if silent is False:
  1435. self.inform.emit(_("Open Script file failed."))
  1436. else:
  1437. if silent is False:
  1438. self.on_fileopenscript(name=file_name)
  1439. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  1440. self.on_filerunscript(name=file_name)
  1441. except Exception as e:
  1442. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  1443. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  1444. log.debug("App.on_startup_args() --> Quit event.")
  1445. sys.exit()
  1446. elif 'save'.lower() in argument.lower():
  1447. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  1448. self.preferencesUiManager.save_defaults()
  1449. else:
  1450. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  1451. proc_arg = argument.lower()
  1452. for ext in exc_list:
  1453. proc_ext = ext.replace(' ', '')
  1454. proc_ext = '.%s' % proc_ext
  1455. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1456. file_name = str(argument)
  1457. if file_name == "":
  1458. if silent is False:
  1459. self.inform.emit(_("Open Excellon file failed."))
  1460. else:
  1461. self.on_fileopenexcellon(name=file_name, signal=None)
  1462. return
  1463. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  1464. for ext in gco_list:
  1465. proc_ext = ext.replace(' ', '')
  1466. proc_ext = '.%s' % proc_ext
  1467. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1468. file_name = str(argument)
  1469. if file_name == "":
  1470. if silent is False:
  1471. self.inform.emit(_("Open GCode file failed."))
  1472. else:
  1473. self.on_fileopengcode(name=file_name, signal=None)
  1474. return
  1475. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  1476. for ext in grb_list:
  1477. proc_ext = ext.replace(' ', '')
  1478. proc_ext = '.%s' % proc_ext
  1479. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1480. file_name = str(argument)
  1481. if file_name == "":
  1482. if silent is False:
  1483. self.inform.emit(_("Open Gerber file failed."))
  1484. else:
  1485. self.on_fileopengerber(name=file_name, signal=None)
  1486. return
  1487. # if it reached here without already returning then the app was registered with a file that it does not
  1488. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  1489. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  1490. # for arg in args_to_process:
  1491. # if 'FlatCAM.exe' in arg:
  1492. # continue
  1493. # else:
  1494. # sys.exit(2)
  1495. def set_ui_title(self, name):
  1496. """
  1497. Sets the title of the main window.
  1498. :param name: String that store the project path and project name
  1499. :return: None
  1500. """
  1501. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  1502. (self.version,
  1503. ('BETA' if self.beta else ''),
  1504. platform.architecture()[0],
  1505. self.engine,
  1506. name)
  1507. )
  1508. def on_app_restart(self):
  1509. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  1510. # be left in the SySTray
  1511. try:
  1512. self.trayIcon.hide()
  1513. except Exception:
  1514. pass
  1515. fcTranslate.restart_program(app=self)
  1516. def clear_pool(self):
  1517. """
  1518. Clear the multiprocessing pool and calls garbage collector.
  1519. :return: None
  1520. """
  1521. self.pool.close()
  1522. self.pool = Pool()
  1523. self.pool_recreated.emit(self.pool)
  1524. gc.collect()
  1525. def install_tools(self):
  1526. """
  1527. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  1528. Instantiation of the Tools classes.
  1529. The order that the tools are installed is important as they can depend on each other install position.
  1530. :return: None
  1531. """
  1532. # shell tool has t obe initialized always first because other tools print messages in the Shell Dock
  1533. self.shell = FCShell(app=self, version=self.version)
  1534. self.distance_tool = Distance(self)
  1535. self.distance_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance16.png'), pos=self.ui.menuedit,
  1536. before=self.ui.menueditorigin,
  1537. separator=False)
  1538. self.distance_min_tool = DistanceMin(self)
  1539. self.distance_min_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance_min16.png'),
  1540. pos=self.ui.menuedit,
  1541. before=self.ui.menueditorigin,
  1542. separator=True)
  1543. self.dblsidedtool = DblSidedTool(self)
  1544. self.dblsidedtool.install(icon=QtGui.QIcon(self.resource_location + '/doubleside16.png'), separator=False)
  1545. self.cal_exc_tool = ToolCalibration(self)
  1546. self.cal_exc_tool.install(icon=QtGui.QIcon(self.resource_location + '/calibrate_16.png'), pos=self.ui.menutool,
  1547. before=self.dblsidedtool.menuAction,
  1548. separator=False)
  1549. self.align_objects_tool = AlignObjects(self)
  1550. self.align_objects_tool.install(icon=QtGui.QIcon(self.resource_location + '/align16.png'), separator=False)
  1551. self.edrills_tool = ToolExtractDrills(self)
  1552. self.edrills_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), separator=True)
  1553. self.panelize_tool = Panelize(self)
  1554. self.panelize_tool.install(icon=QtGui.QIcon(self.resource_location + '/panelize16.png'))
  1555. self.film_tool = Film(self)
  1556. self.film_tool.install(icon=QtGui.QIcon(self.resource_location + '/film16.png'))
  1557. self.paste_tool = SolderPaste(self)
  1558. self.paste_tool.install(icon=QtGui.QIcon(self.resource_location + '/solderpastebis32.png'))
  1559. self.calculator_tool = ToolCalculator(self)
  1560. self.calculator_tool.install(icon=QtGui.QIcon(self.resource_location + '/calculator16.png'), separator=True)
  1561. self.sub_tool = ToolSub(self)
  1562. self.sub_tool.install(icon=QtGui.QIcon(self.resource_location + '/sub32.png'),
  1563. pos=self.ui.menutool, separator=True)
  1564. self.rules_tool = RulesCheck(self)
  1565. self.rules_tool.install(icon=QtGui.QIcon(self.resource_location + '/rules32.png'),
  1566. pos=self.ui.menutool, separator=False)
  1567. self.optimal_tool = ToolOptimal(self)
  1568. self.optimal_tool.install(icon=QtGui.QIcon(self.resource_location + '/open_excellon32.png'),
  1569. pos=self.ui.menutool, separator=True)
  1570. self.move_tool = ToolMove(self)
  1571. self.move_tool.install(icon=QtGui.QIcon(self.resource_location + '/move16.png'), pos=self.ui.menuedit,
  1572. before=self.ui.menueditorigin, separator=True)
  1573. self.cutout_tool = CutOut(self)
  1574. self.cutout_tool.install(icon=QtGui.QIcon(self.resource_location + '/cut16_bis.png'), pos=self.ui.menutool,
  1575. before=self.sub_tool.menuAction)
  1576. self.ncclear_tool = NonCopperClear(self)
  1577. self.ncclear_tool.install(icon=QtGui.QIcon(self.resource_location + '/ncc16.png'), pos=self.ui.menutool,
  1578. before=self.sub_tool.menuAction, separator=True)
  1579. self.paint_tool = ToolPaint(self)
  1580. self.paint_tool.install(icon=QtGui.QIcon(self.resource_location + '/paint16.png'), pos=self.ui.menutool,
  1581. before=self.sub_tool.menuAction, separator=True)
  1582. self.isolation_tool = ToolIsolation(self)
  1583. self.isolation_tool.install(icon=QtGui.QIcon(self.resource_location + '/iso_16.png'), pos=self.ui.menutool,
  1584. before=self.sub_tool.menuAction, separator=True)
  1585. self.drilling_tool = ToolDrilling(self)
  1586. self.drilling_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), pos=self.ui.menutool,
  1587. before=self.sub_tool.menuAction, separator=True)
  1588. self.copper_thieving_tool = ToolCopperThieving(self)
  1589. self.copper_thieving_tool.install(icon=QtGui.QIcon(self.resource_location + '/copperfill32.png'),
  1590. pos=self.ui.menutool)
  1591. self.fiducial_tool = ToolFiducials(self)
  1592. self.fiducial_tool.install(icon=QtGui.QIcon(self.resource_location + '/fiducials_32.png'),
  1593. pos=self.ui.menutool)
  1594. self.qrcode_tool = QRCode(self)
  1595. self.qrcode_tool.install(icon=QtGui.QIcon(self.resource_location + '/qrcode32.png'),
  1596. pos=self.ui.menutool)
  1597. self.punch_tool = ToolPunchGerber(self)
  1598. self.punch_tool.install(icon=QtGui.QIcon(self.resource_location + '/punch32.png'), pos=self.ui.menutool)
  1599. self.invert_tool = ToolInvertGerber(self)
  1600. self.invert_tool.install(icon=QtGui.QIcon(self.resource_location + '/invert32.png'), pos=self.ui.menutool)
  1601. self.corners_tool = ToolCorners(self)
  1602. self.corners_tool.install(icon=QtGui.QIcon(self.resource_location + '/corners_32.png'), pos=self.ui.menutool)
  1603. self.etch_tool = ToolEtchCompensation(self)
  1604. self.etch_tool.install(icon=QtGui.QIcon(self.resource_location + '/etch_32.png'), pos=self.ui.menutool)
  1605. self.transform_tool = ToolTransform(self)
  1606. self.transform_tool.install(icon=QtGui.QIcon(self.resource_location + '/transform.png'),
  1607. pos=self.ui.menuoptions, separator=True)
  1608. self.properties_tool = Properties(self)
  1609. self.properties_tool.install(icon=QtGui.QIcon(self.resource_location + '/properties32.png'),
  1610. pos=self.ui.menuoptions)
  1611. self.pdf_tool = ToolPDF(self)
  1612. self.pdf_tool.install(icon=QtGui.QIcon(self.resource_location + '/pdf32.png'),
  1613. pos=self.ui.menufileimport,
  1614. separator=True)
  1615. self.image_tool = ToolImage(self)
  1616. self.image_tool.install(icon=QtGui.QIcon(self.resource_location + '/image32.png'),
  1617. pos=self.ui.menufileimport,
  1618. separator=True)
  1619. self.pcb_wizard_tool = PcbWizard(self)
  1620. self.pcb_wizard_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill32.png'),
  1621. pos=self.ui.menufileimport)
  1622. self.log.debug("Tools are installed.")
  1623. def remove_tools(self):
  1624. """
  1625. Will remove all the actions in the Tool menu.
  1626. :return: None
  1627. """
  1628. for act in self.ui.menutool.actions():
  1629. self.ui.menutool.removeAction(act)
  1630. def init_tools(self):
  1631. """
  1632. Initialize the Tool tab in the notebook side of the central widget.
  1633. Remove the actions in the Tools menu.
  1634. Instantiate again the FlatCAM tools (plugins).
  1635. All this is required when changing the layout: standard, compact etc.
  1636. :return: None
  1637. """
  1638. log.debug("init_tools()")
  1639. # delete the data currently in the Tools Tab and the Tab itself
  1640. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1641. if widget is not None:
  1642. widget.deleteLater()
  1643. self.ui.notebook.removeTab(2)
  1644. # rebuild the Tools Tab
  1645. self.ui.tool_tab = QtWidgets.QWidget()
  1646. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1647. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1648. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  1649. self.ui.tool_scroll_area = VerticalScrollArea()
  1650. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1651. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1652. # first remove all of them
  1653. self.remove_tools()
  1654. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  1655. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon(self.resource_location + '/shell16.png'),
  1656. '&Command Line\tS')
  1657. self.ui.menutoolshell.triggered.connect(self.ui.toggle_shell_ui)
  1658. # third install all of them
  1659. try:
  1660. self.install_tools()
  1661. except AttributeError:
  1662. pass
  1663. self.log.debug("Tools are initialized.")
  1664. # def parse_system_fonts(self):
  1665. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1666. # 'params': []})
  1667. def connect_tools_signals_to_toolbar(self, ui):
  1668. ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  1669. ui.cal_btn.triggered.connect(lambda: self.cal_exc_tool.run(toggle=True))
  1670. ui.align_btn.triggered.connect(lambda: self.align_objects_tool.run(toggle=True))
  1671. ui.extract_btn.triggered.connect(lambda: self.edrills_tool.run(toggle=True))
  1672. ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  1673. ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  1674. ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  1675. ui.isolation_btn.triggered.connect(lambda: self.isolation_tool.run(toggle=True))
  1676. ui.drill_btn.triggered.connect(lambda: self.drilling_tool.run(toggle=True))
  1677. ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  1678. ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  1679. ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  1680. ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  1681. ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  1682. ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  1683. ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  1684. ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  1685. ui.qrcode_btn.triggered.connect(lambda: self.qrcode_tool.run(toggle=True))
  1686. ui.copperfill_btn.triggered.connect(lambda: self.copper_thieving_tool.run(toggle=True))
  1687. ui.fiducials_btn.triggered.connect(lambda: self.fiducial_tool.run(toggle=True))
  1688. ui.punch_btn.triggered.connect(lambda: self.punch_tool.run(toggle=True))
  1689. ui.invert_btn.triggered.connect(lambda: self.invert_tool.run(toggle=True))
  1690. ui.corners_tool_btn.triggered.connect(lambda: self.corners_tool.run(toggle=True))
  1691. ui.etch_btn.triggered.connect(lambda: self.etch_tool.run(toggle=True))
  1692. def connect_toolbar_signals(self, ui):
  1693. """
  1694. Reconnect the signals to the actions in the toolbar.
  1695. This has to be done each time after the FlatCAM tools are removed/installed.
  1696. :return: None
  1697. """
  1698. # Toolbar
  1699. # File Toolbar Signals
  1700. # ui.file_new_btn.triggered.connect(self.on_file_new)
  1701. ui.file_open_btn.triggered.connect(self.on_file_openproject)
  1702. ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  1703. ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  1704. ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  1705. # View Toolbar Signals
  1706. ui.clear_plot_btn.triggered.connect(self.clear_plots)
  1707. ui.replot_btn.triggered.connect(self.plot_all)
  1708. ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  1709. ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1710. ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1711. # Edit Toolbar Signals
  1712. ui.editgeo_btn.triggered.connect(self.object2editor)
  1713. ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  1714. ui.copy_btn.triggered.connect(self.on_copy_command)
  1715. ui.delete_btn.triggered.connect(self.on_delete)
  1716. ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  1717. ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  1718. ui.origin_btn.triggered.connect(self.on_set_origin)
  1719. ui.move2origin_btn.triggered.connect(self.on_move2origin)
  1720. ui.jmp_btn.triggered.connect(self.on_jump_to)
  1721. ui.locate_btn.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  1722. # Scripting Toolbar Signals
  1723. ui.shell_btn.triggered.connect(ui.toggle_shell_ui)
  1724. ui.new_script_btn.triggered.connect(self.on_filenewscript)
  1725. ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  1726. ui.run_script_btn.triggered.connect(self.on_filerunscript)
  1727. # Tools Toolbar Signals
  1728. try:
  1729. self.connect_tools_signals_to_toolbar(ui=ui)
  1730. except Exception as err:
  1731. log.debug("App.connect_toolbar_signals() tools signals -> %s" % str(err))
  1732. def object2editor(self):
  1733. """
  1734. Send the current Geometry, Gerber, Excellon object or CNCJob (if any) into the it's editor.
  1735. :return: None
  1736. """
  1737. self.defaults.report_usage("object2editor()")
  1738. # disable the objects menu as it may interfere with the appEditors
  1739. self.ui.menuobjects.setDisabled(True)
  1740. edited_object = self.collection.get_active()
  1741. if isinstance(edited_object, GerberObject) or isinstance(edited_object, GeometryObject) or \
  1742. isinstance(edited_object, ExcellonObject) or isinstance(edited_object, CNCJobObject):
  1743. pass
  1744. else:
  1745. self.inform.emit('[WARNING_NOTCL] %s' % _("Select a Geometry, Gerber, Excellon or CNCJob Object to edit."))
  1746. return
  1747. if isinstance(edited_object, GeometryObject):
  1748. # store the Geometry Editor Toolbar visibility before entering in the Editor
  1749. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  1750. # we set the notebook to hidden
  1751. # self.ui.splitter.setSizes([0, 1])
  1752. if edited_object.multigeo is True:
  1753. sel_rows = [item.row() for item in edited_object.ui.geo_tools_table.selectedItems()]
  1754. if len(sel_rows) > 1:
  1755. self.inform.emit('[WARNING_NOTCL] %s' %
  1756. _("Simultaneous editing of tools geometry in a MultiGeo Geometry "
  1757. "is not possible.\n"
  1758. "Edit only one geometry at a time."))
  1759. if not sel_rows:
  1760. self.inform.emit('[WARNING_NOTCL] %s.' % _("No Tool Selected"))
  1761. return
  1762. # determine the tool dia of the selected tool
  1763. selected_tooldia = float(edited_object.ui.geo_tools_table.item(sel_rows[0], 1).text())
  1764. # now find the key in the edited_object.tools that has this tooldia
  1765. multi_tool = 1
  1766. for tool in edited_object.tools:
  1767. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  1768. multi_tool = tool
  1769. break
  1770. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  1771. else:
  1772. self.geo_editor.edit_fcgeometry(edited_object)
  1773. # set call source to the Editor we go into
  1774. self.call_source = 'geo_editor'
  1775. elif isinstance(edited_object, ExcellonObject):
  1776. # store the Excellon Editor Toolbar visibility before entering in the Editor
  1777. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  1778. if self.ui.splitter.sizes()[0] == 0:
  1779. self.ui.splitter.setSizes([1, 1])
  1780. self.exc_editor.edit_fcexcellon(edited_object)
  1781. # set call source to the Editor we go into
  1782. self.call_source = 'exc_editor'
  1783. elif isinstance(edited_object, GerberObject):
  1784. # store the Gerber Editor Toolbar visibility before entering in the Editor
  1785. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  1786. if self.ui.splitter.sizes()[0] == 0:
  1787. self.ui.splitter.setSizes([1, 1])
  1788. self.grb_editor.edit_fcgerber(edited_object)
  1789. # set call source to the Editor we go into
  1790. self.call_source = 'grb_editor'
  1791. # reset the following variables so the UI is built again after edit
  1792. edited_object.ui_build = False
  1793. edited_object.build_aperture_storage = False
  1794. elif isinstance(edited_object, CNCJobObject):
  1795. if self.ui.splitter.sizes()[0] == 0:
  1796. self.ui.splitter.setSizes([1, 1])
  1797. edited_object.on_edit_code_click()
  1798. return
  1799. # make sure that we can't select another object while in Editor Mode:
  1800. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1801. self.ui.project_frame.setDisabled(True)
  1802. # delete any selection shape that might be active as they are not relevant in Editor
  1803. self.delete_selection_shape()
  1804. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  1805. self.ui.plot_tab_area.protectTab(0)
  1806. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor is activated ..."))
  1807. self.should_we_save = True
  1808. def editor2object(self, cleanup=None):
  1809. """
  1810. Transfers the Geometry or Excellon from it's editor to the current object.
  1811. :return: None
  1812. """
  1813. self.defaults.report_usage("editor2object()")
  1814. # re-enable the objects menu that was disabled on entry in Editor mode
  1815. self.ui.menuobjects.setDisabled(False)
  1816. # do not update a geometry or excellon object unless it comes out of an editor
  1817. if self.call_source != 'app':
  1818. edited_obj = self.collection.get_active()
  1819. if cleanup is None:
  1820. msgbox = QtWidgets.QMessageBox()
  1821. msgbox.setText(_("Do you want to save the edited object?"))
  1822. msgbox.setWindowTitle(_("Close Editor"))
  1823. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  1824. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  1825. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  1826. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  1827. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  1828. msgbox.setDefaultButton(bt_yes)
  1829. msgbox.exec_()
  1830. response = msgbox.clickedButton()
  1831. if response == bt_yes:
  1832. # clean the Tools Tab
  1833. self.ui.tool_scroll_area.takeWidget()
  1834. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1835. self.ui.notebook.setTabText(2, "Tool")
  1836. if isinstance(edited_obj, GeometryObject):
  1837. obj_type = "Geometry"
  1838. self.geo_editor.update_fcgeometry(edited_obj)
  1839. # self.geo_editor.update_options(edited_obj)
  1840. # restore GUI to the Selected TAB
  1841. # Remove anything else in the appGUI
  1842. self.ui.tool_scroll_area.takeWidget()
  1843. # update the geo object options so it is including the bounding box values
  1844. try:
  1845. xmin, ymin, xmax, ymax = edited_obj.bounds(flatten=True)
  1846. edited_obj.options['xmin'] = xmin
  1847. edited_obj.options['ymin'] = ymin
  1848. edited_obj.options['xmax'] = xmax
  1849. edited_obj.options['ymax'] = ymax
  1850. except AttributeError as e:
  1851. self.inform.emit('[WARNING] %s' % _("Object empty after edit."))
  1852. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  1853. edited_obj.build_ui()
  1854. edited_obj.plot()
  1855. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1856. elif isinstance(edited_obj, GerberObject):
  1857. obj_type = "Gerber"
  1858. self.grb_editor.update_fcgerber()
  1859. # self.grb_editor.update_options(edited_obj)
  1860. # delete the old object (the source object) if it was an empty one
  1861. try:
  1862. if len(edited_obj.solid_geometry) == 0:
  1863. old_name = edited_obj.options['name']
  1864. self.collection.delete_by_name(old_name)
  1865. except TypeError:
  1866. # if the solid_geometry is a single Polygon the len() will not work
  1867. # in any case, falling here means that we have something in the solid_geometry, even if only
  1868. # a single Polygon, therefore we pass this
  1869. pass
  1870. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1871. # restore GUI to the Selected TAB
  1872. # Remove anything else in the GUI
  1873. self.ui.selected_scroll_area.takeWidget()
  1874. elif isinstance(edited_obj, ExcellonObject):
  1875. obj_type = "Excellon"
  1876. self.exc_editor.update_fcexcellon(edited_obj)
  1877. # self.exc_editor.update_options(edited_obj)
  1878. # restore GUI to the Selected TAB
  1879. # Remove anything else in the GUI
  1880. self.ui.tool_scroll_area.takeWidget()
  1881. # delete the old object (the source object) if it was an empty one
  1882. # find if we have drills:
  1883. has_drills = None
  1884. for tt in edited_obj.tools:
  1885. if 'drills' in edited_obj.tools[tt] and edited_obj.tools[tt]['drills']:
  1886. has_drills = True
  1887. break
  1888. # find if we have slots:
  1889. has_slots = None
  1890. for tt in edited_obj.tools:
  1891. if 'slots' in edited_obj.tools[tt] and edited_obj.tools[tt]['slots']:
  1892. has_slots = True
  1893. break
  1894. if has_drills is None and has_slots is None:
  1895. old_name = edited_obj.options['name']
  1896. self.collection.delete_by_name(name=old_name)
  1897. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1898. else:
  1899. self.inform.emit('[WARNING_NOTCL] %s' %
  1900. _("Select a Gerber, Geometry or Excellon Object to update."))
  1901. return
  1902. self.inform.emit('[selected] %s %s' % (obj_type, _("is updated, returning to App...")))
  1903. elif response == bt_no:
  1904. # clean the Tools Tab
  1905. self.ui.tool_scroll_area.takeWidget()
  1906. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1907. self.ui.notebook.setTabText(2, "Tool")
  1908. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor exited. Editor content was not saved."))
  1909. if isinstance(edited_obj, GeometryObject):
  1910. self.geo_editor.deactivate()
  1911. edited_obj.build_ui()
  1912. edited_obj.plot()
  1913. elif isinstance(edited_obj, GerberObject):
  1914. self.grb_editor.deactivate_grb_editor()
  1915. edited_obj.build_ui()
  1916. elif isinstance(edited_obj, ExcellonObject):
  1917. self.exc_editor.deactivate()
  1918. edited_obj.build_ui()
  1919. else:
  1920. self.inform.emit('[WARNING_NOTCL] %s' %
  1921. _("Select a Gerber, Geometry or Excellon Object to update."))
  1922. return
  1923. elif response == bt_cancel:
  1924. return
  1925. # edited_obj.set_ui(edited_obj.ui_type(decimals=self.decimals))
  1926. # edited_obj.build_ui()
  1927. # Switch notebook to Selected page
  1928. # self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  1929. else:
  1930. if isinstance(edited_obj, GeometryObject):
  1931. self.geo_editor.deactivate()
  1932. elif isinstance(edited_obj, GerberObject):
  1933. self.grb_editor.deactivate_grb_editor()
  1934. elif isinstance(edited_obj, ExcellonObject):
  1935. self.exc_editor.deactivate()
  1936. else:
  1937. self.inform.emit('[WARNING_NOTCL] %s' %
  1938. _("Select a Gerber, Geometry or Excellon Object to update."))
  1939. return
  1940. # if notebook is hidden we show it
  1941. if self.ui.splitter.sizes()[0] == 0:
  1942. self.ui.splitter.setSizes([1, 1])
  1943. # restore the call_source to app
  1944. self.call_source = 'app'
  1945. # edited_obj.plot()
  1946. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  1947. self.ui.plot_tab_area.protectTab(0)
  1948. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  1949. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1950. self.ui.project_frame.setDisabled(False)
  1951. def get_last_folder(self):
  1952. """
  1953. Get the folder path from where the last file was opened.
  1954. :return: String, last opened folder path
  1955. """
  1956. return self.defaults["global_last_folder"]
  1957. def get_last_save_folder(self):
  1958. """
  1959. Get the folder path from where the last file was saved.
  1960. :return: String, last saved folder path
  1961. """
  1962. loc = self.defaults["global_last_save_folder"]
  1963. if loc is None:
  1964. loc = self.defaults["global_last_folder"]
  1965. if loc is None:
  1966. loc = os.path.dirname(__file__)
  1967. return loc
  1968. @QtCore.pyqtSlot(str)
  1969. @QtCore.pyqtSlot(str, bool)
  1970. def info(self, msg, shell_echo=True):
  1971. """
  1972. Informs the user. Normally on the status bar, optionally
  1973. also on the shell.
  1974. :param msg: Text to write.
  1975. :type msg: str
  1976. :param shell_echo: Control if to display the message msg in the Shell
  1977. :type shell_echo: bool
  1978. :return: None
  1979. """
  1980. # Type of message in brackets at the beginning of the message.
  1981. match = re.search(r"\[(.*)\](.*)", msg)
  1982. if match:
  1983. level = match.group(1)
  1984. msg_ = match.group(2)
  1985. self.ui.fcinfo.set_status(str(msg_), level=level)
  1986. if shell_echo is True:
  1987. if level.lower() == "error":
  1988. self.shell_message(msg, error=True, show=True)
  1989. elif level.lower() == "warning":
  1990. self.shell_message(msg, warning=True, show=True)
  1991. elif level.lower() == "error_notcl":
  1992. self.shell_message(msg, error=True, show=False)
  1993. elif level.lower() == "warning_notcl":
  1994. self.shell_message(msg, warning=True, show=False)
  1995. elif level.lower() == "success":
  1996. self.shell_message(msg, success=True, show=False)
  1997. elif level.lower() == "selected":
  1998. self.shell_message(msg, selected=True, show=False)
  1999. else:
  2000. self.shell_message(msg, show=False)
  2001. else:
  2002. self.ui.fcinfo.set_status(str(msg), level="info")
  2003. # make sure that if the message is to clear the infobar with a space
  2004. # is not printed over and over on the shell
  2005. if msg != '' and shell_echo is True:
  2006. self.shell_message(msg)
  2007. def info_shell(self, msg):
  2008. self.shell_message(msg=msg)
  2009. def on_import_preferences(self):
  2010. """
  2011. Loads the application default settings from a saved file into
  2012. ``self.defaults`` dictionary.
  2013. :return: None
  2014. """
  2015. self.defaults.report_usage("on_import_preferences")
  2016. App.log.debug("App.on_import_preferences()")
  2017. # Show file chooser
  2018. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  2019. try:
  2020. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2021. directory=self.data_path,
  2022. filter=filter_)
  2023. except TypeError:
  2024. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2025. filter=filter_)
  2026. filename = str(filename)
  2027. if filename == "":
  2028. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2029. return
  2030. # Load in the defaults from the chosen file
  2031. self.defaults.load(filename=filename)
  2032. self.preferencesUiManager.on_preferences_edited()
  2033. self.inform.emit('[success] %s: %s' % (_("Imported Defaults from"), filename))
  2034. def on_export_preferences(self):
  2035. """
  2036. Save the defaults dictionary to a file.
  2037. :return: None
  2038. """
  2039. self.defaults.report_usage("on_export_preferences")
  2040. App.log.debug("on_export_preferences()")
  2041. # defaults_file_content = None
  2042. # Show file chooser
  2043. date = str(datetime.today()).rpartition('.')[0]
  2044. date = ''.join(c for c in date if c not in ':-')
  2045. date = date.replace(' ', '_')
  2046. filter__ = "Config File .FlatConfig (*.FlatConfig);;All Files (*.*)"
  2047. try:
  2048. filename, _f = FCFileSaveDialog.get_saved_filename(
  2049. caption=_("Export FlatCAM Preferences"),
  2050. directory=self.data_path + '/preferences_' + date,
  2051. ext_filter=filter__
  2052. )
  2053. except TypeError:
  2054. filename, _f = FCFileSaveDialog.get_saved_filename(
  2055. caption=_("Export FlatCAM Preferences"), ext_filter=filter__)
  2056. filename = str(filename)
  2057. if filename == "":
  2058. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2059. return
  2060. # Update options
  2061. self.preferencesUiManager.defaults_read_form()
  2062. self.defaults.propagate_defaults()
  2063. # Save update options
  2064. try:
  2065. self.defaults.write(filename=filename)
  2066. except Exception:
  2067. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2068. return
  2069. if self.defaults["global_open_style"] is False:
  2070. self.file_opened.emit("preferences", filename)
  2071. self.file_saved.emit("preferences", filename)
  2072. self.inform.emit('[success] %s: %s' % (_("Exported preferences to"), filename))
  2073. def save_to_file(self, content_to_save, txt_content):
  2074. """
  2075. Save something to a file.
  2076. :return: None
  2077. """
  2078. self.defaults.report_usage("save_to_file")
  2079. App.log.debug("save_to_file()")
  2080. self.date = str(datetime.today()).rpartition('.')[0]
  2081. self.date = ''.join(c for c in self.date if c not in ':-')
  2082. self.date = self.date.replace(' ', '_')
  2083. filter__ = "HTML File .html (*.html);;TXT File .txt (*.txt);;All Files (*.*)"
  2084. path_to_save = self.defaults["global_last_save_folder"] if \
  2085. self.defaults["global_last_save_folder"] is not None else self.data_path
  2086. try:
  2087. filename, _f = FCFileSaveDialog.get_saved_filename(
  2088. caption=_("Save to file"),
  2089. directory=path_to_save + '/file_' + self.date,
  2090. ext_filter=filter__
  2091. )
  2092. except TypeError:
  2093. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save to file"), ext_filter=filter__)
  2094. filename = str(filename)
  2095. if filename == "":
  2096. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2097. return
  2098. else:
  2099. try:
  2100. with open(filename, 'w') as f:
  2101. ___ = f.read()
  2102. except PermissionError:
  2103. self.inform.emit('[WARNING] %s' %
  2104. _("Permission denied, saving not possible.\n"
  2105. "Most likely another app is holding the file open and not accessible."))
  2106. return
  2107. except IOError:
  2108. App.log.debug('Creating a new file ...')
  2109. f = open(filename, 'w')
  2110. f.close()
  2111. except Exception:
  2112. e = sys.exc_info()[0]
  2113. App.log.error("Could not load the file.")
  2114. App.log.error(str(e))
  2115. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load the file."))
  2116. return
  2117. # Save content
  2118. if filename.rpartition('.')[2].lower() == 'html':
  2119. file_content = content_to_save
  2120. else:
  2121. file_content = txt_content
  2122. try:
  2123. with open(filename, "w") as f:
  2124. f.write(file_content)
  2125. except Exception:
  2126. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2127. return
  2128. self.inform.emit('[success] %s: %s' % (_("Exported file to"), filename))
  2129. def register_recent(self, kind, filename):
  2130. """
  2131. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  2132. dictionary.
  2133. :param kind: type of file that was opened
  2134. :param filename: the path and file name for the file that was opened
  2135. :return:
  2136. """
  2137. self.log.debug("register_recent()")
  2138. self.log.debug(" %s" % kind)
  2139. self.log.debug(" %s" % filename)
  2140. record = {'kind': str(kind), 'filename': str(filename)}
  2141. if record in self.recent:
  2142. return
  2143. if record in self.recent_projects:
  2144. return
  2145. if record['kind'] == 'project':
  2146. self.recent_projects.insert(0, record)
  2147. else:
  2148. self.recent.insert(0, record)
  2149. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2150. self.recent.pop()
  2151. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  2152. self.recent_projects.pop()
  2153. try:
  2154. f = open(self.data_path + '/recent.json', 'w')
  2155. except IOError:
  2156. App.log.error("Failed to open recent items file for writing.")
  2157. self.inform.emit('[ERROR_NOTCL] %s' %
  2158. _('Failed to open recent files file for writing.'))
  2159. return
  2160. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2161. f.close()
  2162. try:
  2163. fp = open(self.data_path + '/recent_projects.json', 'w')
  2164. except IOError:
  2165. App.log.error("Failed to open recent items file for writing.")
  2166. self.inform.emit('[ERROR_NOTCL] %s' %
  2167. _('Failed to open recent projects file for writing.'))
  2168. return
  2169. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  2170. fp.close()
  2171. # Re-build the recent items menu
  2172. self.setup_recent_items()
  2173. def on_about(self):
  2174. """
  2175. Displays the "about" dialog found in the Menu --> Help.
  2176. :return: None
  2177. """
  2178. self.defaults.report_usage("on_about")
  2179. version = self.version
  2180. version_date = self.version_date
  2181. beta = self.beta
  2182. class AboutDialog(QtWidgets.QDialog):
  2183. def __init__(self, app, parent=None):
  2184. QtWidgets.QDialog.__init__(self, parent)
  2185. self.app = app
  2186. # Icon and title
  2187. self.setWindowIcon(parent.app_icon)
  2188. self.setWindowTitle(_("About FlatCAM"))
  2189. self.resize(600, 200)
  2190. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  2191. # self.setStyleSheet(
  2192. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  2193. # "background-attachment: fixed"
  2194. # )
  2195. # bgimage = QtGui.QImage(self.resource_location + '/flatcam_icon256.png')
  2196. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  2197. # palette = QtGui.QPalette()
  2198. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  2199. # self.setPalette(palette)
  2200. logo = QtWidgets.QLabel()
  2201. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/flatcam_icon256.png'))
  2202. title = QtWidgets.QLabel(
  2203. "<font size=8><B>FlatCAM</B></font><BR>"
  2204. "{title}<BR>"
  2205. "<BR>"
  2206. "<BR>"
  2207. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  2208. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  2209. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  2210. "<B>{issue}</B></a><BR>".format(
  2211. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  2212. devel=_("Development"),
  2213. down=_("DOWNLOAD"),
  2214. issue=_("Issue tracker"))
  2215. )
  2216. title.setOpenExternalLinks(True)
  2217. closebtn = QtWidgets.QPushButton(_("Close"))
  2218. tab_widget = QtWidgets.QTabWidget()
  2219. description_label = QtWidgets.QLabel(
  2220. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  2221. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  2222. version=version,
  2223. beta=('BETA' if beta else ''),
  2224. date=version_date,
  2225. arch=platform.architecture()[0])
  2226. )
  2227. description_label.setOpenExternalLinks(True)
  2228. lic_lbl_header = QtWidgets.QLabel(
  2229. '%s:<br>%s<br>' % (
  2230. _('Licensed under the MIT license'),
  2231. "<a href = \"http://www.opensource.org/licenses/mit-license.php\">"
  2232. "http://www.opensource.org/licenses/mit-license.php</a>"
  2233. )
  2234. )
  2235. lic_lbl_header.setOpenExternalLinks(True)
  2236. lic_lbl_body = QtWidgets.QLabel(
  2237. _(
  2238. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  2239. 'of this software and associated documentation files (the "Software"), to deal\n'
  2240. 'in the Software without restriction, including without limitation the rights\n'
  2241. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  2242. 'copies of the Software, and to permit persons to whom the Software is\n'
  2243. 'furnished to do so, subject to the following conditions:\n\n'
  2244. 'The above copyright notice and this permission notice shall be included in\n'
  2245. 'all copies or substantial portions of the Software.\n\n'
  2246. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  2247. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  2248. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  2249. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  2250. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  2251. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  2252. 'THE SOFTWARE.'
  2253. )
  2254. )
  2255. attributions_label = QtWidgets.QLabel(
  2256. _(
  2257. 'Some of the icons used are from the following sources:<br>'
  2258. '<div>Icons by <a href="https://www.flaticon.com/authors/freepik" '
  2259. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  2260. 'title="Flaticon">www.flaticon.com</a></div>'
  2261. '<div>Icons by <a target="_blank" href="https://icons8.com">Icons8</a></div>'
  2262. 'Icons by <a href="http://www.onlinewebfonts.com">oNline Web Fonts</a>'
  2263. '<div>Icons by <a href="https://www.flaticon.com/authors/pixel-perfect" '
  2264. 'title="Pixel perfect">Pixel perfect</a> from <a href="https://www.flaticon.com/" '
  2265. 'title="Flaticon">www.flaticon.com</a></div>'
  2266. )
  2267. )
  2268. attributions_label.setOpenExternalLinks(True)
  2269. # layouts
  2270. layout1 = QtWidgets.QVBoxLayout()
  2271. layout1_1 = QtWidgets.QHBoxLayout()
  2272. layout1_2 = QtWidgets.QHBoxLayout()
  2273. layout2 = QtWidgets.QHBoxLayout()
  2274. layout3 = QtWidgets.QHBoxLayout()
  2275. self.setLayout(layout1)
  2276. layout1.addLayout(layout1_1)
  2277. layout1.addLayout(layout1_2)
  2278. layout1.addLayout(layout2)
  2279. layout1.addLayout(layout3)
  2280. layout1_1.addStretch()
  2281. layout1_1.addWidget(description_label)
  2282. layout1_2.addWidget(tab_widget)
  2283. self.splash_tab = QtWidgets.QWidget()
  2284. self.splash_tab.setObjectName("splash_about")
  2285. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  2286. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  2287. tab_widget.addTab(self.splash_tab, _("Splash"))
  2288. self.programmmers_tab = QtWidgets.QWidget()
  2289. self.programmmers_tab.setObjectName("programmers_about")
  2290. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  2291. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  2292. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  2293. self.translators_tab = QtWidgets.QWidget()
  2294. self.translators_tab.setObjectName("translators_about")
  2295. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  2296. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  2297. tab_widget.addTab(self.translators_tab, _("Translators"))
  2298. self.license_tab = QtWidgets.QWidget()
  2299. self.license_tab.setObjectName("license_about")
  2300. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  2301. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  2302. tab_widget.addTab(self.license_tab, _("License"))
  2303. self.attributions_tab = QtWidgets.QWidget()
  2304. self.attributions_tab.setObjectName("attributions_about")
  2305. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  2306. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  2307. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  2308. self.splash_tab_layout.addWidget(logo, stretch=0)
  2309. self.splash_tab_layout.addWidget(title, stretch=1)
  2310. pal = QtGui.QPalette()
  2311. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2312. self.prog_grid_lay = QtWidgets.QGridLayout()
  2313. self.prog_grid_lay.setHorizontalSpacing(20)
  2314. self.prog_grid_lay.setColumnStretch(0, 0)
  2315. self.prog_grid_lay.setColumnStretch(2, 1)
  2316. prog_widget = QtWidgets.QWidget()
  2317. prog_widget.setLayout(self.prog_grid_lay)
  2318. prog_scroll = QtWidgets.QScrollArea()
  2319. prog_scroll.setWidget(prog_widget)
  2320. prog_scroll.setWidgetResizable(True)
  2321. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2322. prog_scroll.setPalette(pal)
  2323. self.programmmers_tab_layout.addWidget(prog_scroll)
  2324. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  2325. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  2326. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  2327. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  2328. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("Program Author")), 1, 1)
  2329. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<>"), 1, 2)
  2330. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  2331. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  2332. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  2333. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("BETA Maintainer >= 2019")), 4, 1)
  2334. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 2)
  2335. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 5, 0)
  2336. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "David Robertson"), 6, 0)
  2337. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 7, 0)
  2338. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Evans"), 8, 0)
  2339. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Victor Benso"), 9, 0)
  2340. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 10, 0)
  2341. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"), 12, 0)
  2342. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lei Zheng"), 13, 0)
  2343. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Leandro Heck"), 14, 0)
  2344. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marco A Quezada"), 15, 0)
  2345. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 16, 0)
  2346. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Cedric Dussud"), 20, 0)
  2347. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Hemingway"), 22, 0)
  2348. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Damian Wrobel"), 24, 0)
  2349. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Daniel Sallin"), 28, 0)
  2350. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 32, 0)
  2351. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Bruno Vunderl"), 40, 0)
  2352. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Gonzalo Lopez"), 42, 0)
  2353. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jakob Staudt"), 45, 0)
  2354. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Smith"), 49, 0)
  2355. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 52, 0)
  2356. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Barnaby Walters"), 55, 0)
  2357. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Steve Martina"), 57, 0)
  2358. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Thomas Duffin"), 59, 0)
  2359. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 61, 0)
  2360. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 63, 0)
  2361. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Alex Lazar"), 64, 0)
  2362. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Breneman"), 65, 0)
  2363. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Eric Varsanyi"), 67, 0)
  2364. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lubos Medovarsky"), 69, 0)
  2365. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 74, 0)
  2366. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Idechix"), 100, 0)
  2367. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@SM"), 101, 0)
  2368. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@grbf"), 102, 0)
  2369. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Symonty"), 103, 0)
  2370. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@mgix"), 104, 0)
  2371. self.translator_grid_lay = QtWidgets.QGridLayout()
  2372. self.translator_grid_lay.setColumnStretch(0, 0)
  2373. self.translator_grid_lay.setColumnStretch(1, 0)
  2374. self.translator_grid_lay.setColumnStretch(2, 1)
  2375. self.translator_grid_lay.setColumnStretch(3, 0)
  2376. # trans_widget = QtWidgets.QWidget()
  2377. # trans_widget.setLayout(self.translator_grid_lay)
  2378. # self.translators_tab_layout.addWidget(trans_widget)
  2379. # self.translators_tab_layout.addStretch()
  2380. trans_widget = QtWidgets.QWidget()
  2381. trans_widget.setLayout(self.translator_grid_lay)
  2382. trans_scroll = QtWidgets.QScrollArea()
  2383. trans_scroll.setWidget(trans_widget)
  2384. trans_scroll.setWidgetResizable(True)
  2385. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2386. trans_scroll.setPalette(pal)
  2387. self.translators_tab_layout.addWidget(trans_scroll)
  2388. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  2389. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  2390. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Corrections")), 0, 2)
  2391. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 3)
  2392. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "BR - Portuguese"), 1, 0)
  2393. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  2394. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<carlos.stein@gmail.com>"), 1, 3)
  2395. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  2396. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Michel Maciejewski"), 2, 1)
  2397. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 2, 2)
  2398. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<micmac589@gmail.com>"), 2, 3)
  2399. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Hungarian"), 3, 0)
  2400. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 1)
  2401. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 2)
  2402. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 3)
  2403. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Italian"), 4, 0)
  2404. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Massimiliano Golfetto"), 4, 1)
  2405. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 4, 2)
  2406. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<golfetto.pcb@gmail.com>"), 4, 3)
  2407. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 5, 0)
  2408. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 5, 1)
  2409. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jens Karstedt, Detlef Eckardt"), 5, 2)
  2410. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 5, 3)
  2411. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 6, 0)
  2412. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 6, 1)
  2413. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 6, 3)
  2414. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 7, 0)
  2415. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 7, 1)
  2416. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 7, 3)
  2417. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 8, 0)
  2418. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 8, 1)
  2419. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 8, 2)
  2420. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 8, 3)
  2421. self.translator_grid_lay.setColumnStretch(0, 0)
  2422. self.translators_tab_layout.addStretch()
  2423. self.license_tab_layout.addWidget(lic_lbl_header)
  2424. self.license_tab_layout.addWidget(lic_lbl_body)
  2425. self.license_tab_layout.addStretch()
  2426. self.attributions_tab_layout.addWidget(attributions_label)
  2427. self.attributions_tab_layout.addStretch()
  2428. layout3.addStretch()
  2429. layout3.addWidget(closebtn)
  2430. closebtn.clicked.connect(self.accept)
  2431. AboutDialog(app=self, parent=self.ui).exec_()
  2432. def on_readme(self):
  2433. """
  2434. Displays the "about" dialog found in the Menu --> Help.
  2435. :return: None
  2436. """
  2437. class ReadmeDialog(QtWidgets.QDialog):
  2438. def __init__(self, app, parent=None):
  2439. QtWidgets.QDialog.__init__(self, parent)
  2440. self.app = app
  2441. open_source_link = "<a href = 'https://opensource.org/'<b>Open Source</b></a>"
  2442. new_features_link = "<a href = 'https://bitbucket.org/jpcgt/flatcam/pull-requests/'" \
  2443. "<b>click</b></a>"
  2444. bugs_link = "<a href = 'https://bitbucket.org/jpcgt/flatcam/issues/new'<b>click</b></a>"
  2445. # donation_link = "<a href = 'https://www.paypal.com/cgi-bin/webscr?cmd=_" \
  2446. # "donations&business=WLTJJ3Q77D98L&currency_code=USD&source=url'<b>click</b></a>"
  2447. # Icon and title
  2448. self.setWindowIcon(parent.app_icon)
  2449. self.setWindowTitle(_("Important Information's"))
  2450. self.resize(750, 375)
  2451. logo = QtWidgets.QLabel()
  2452. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/contribute256.png'))
  2453. # content = QtWidgets.QLabel(
  2454. # "%s<br>"
  2455. # "%s<br><br>"
  2456. # "%s,<br>"
  2457. # "%s<br>"
  2458. # "<ul>"
  2459. # "<li> &nbsp;%s %s</li>"
  2460. # "<li> &nbsp;%s %s</li>"
  2461. # "</ul>"
  2462. # "%s %s.<br>"
  2463. # "%s"
  2464. # "<ul>"
  2465. # "<li> &nbsp;%s &#128077;</li>"
  2466. # "<li> &nbsp;%s &#128513;</li>"
  2467. # "</ul>" %
  2468. # (
  2469. # _("This program is %s and free in a very wide meaning of the word.") % open_source_link,
  2470. # _("Yet it cannot evolve without <b>contributions</b>."),
  2471. # _("If you want to see this application grow and become better and better"),
  2472. # _("you can <b>contribute</b> to the development yourself by:"),
  2473. # _("Pull Requests on the Bitbucket repository, if you are a developer"),
  2474. # new_features_link,
  2475. # _("Bug Reports by providing the steps required to reproduce the bug"),
  2476. # bugs_link,
  2477. # _("If you like or use this program you can make a donation"),
  2478. # donation_link,
  2479. # _("You don't have to make a donation %s, and it is totally optional but:") % donation_link,
  2480. # _("it will be welcomed with joy"),
  2481. # _("it will give me a reason to continue")
  2482. # )
  2483. # )
  2484. content = QtWidgets.QLabel(
  2485. "%s<br>"
  2486. "%s<br><br>"
  2487. "%s,<br>"
  2488. "%s<br>"
  2489. "<ul>"
  2490. "<li> &nbsp;%s %s</li>"
  2491. "<li> &nbsp;%s %s</li>"
  2492. "</ul>" %
  2493. (
  2494. _("This program is %s and free in a very wide meaning of the word.") % open_source_link,
  2495. _("Yet it cannot evolve without <b>contributions</b>."),
  2496. _("If you want to see this application grow and become better and better"),
  2497. _("you can <b>contribute</b> to the development yourself by:"),
  2498. _("Pull Requests on the Bitbucket repository, if you are a developer"),
  2499. new_features_link,
  2500. _("Bug Reports by providing the steps required to reproduce the bug"),
  2501. bugs_link
  2502. )
  2503. )
  2504. content.setOpenExternalLinks(True)
  2505. # palette
  2506. pal = QtGui.QPalette()
  2507. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2508. # layouts
  2509. main_layout = QtWidgets.QVBoxLayout()
  2510. self.setLayout(main_layout)
  2511. tab_layout = QtWidgets.QHBoxLayout()
  2512. buttons_hlay = QtWidgets.QHBoxLayout()
  2513. main_layout.addLayout(tab_layout)
  2514. main_layout.addLayout(buttons_hlay)
  2515. tab_widget = QtWidgets.QTabWidget()
  2516. tab_layout.addWidget(tab_widget)
  2517. closebtn = QtWidgets.QPushButton(_("Close"))
  2518. buttons_hlay.addStretch()
  2519. buttons_hlay.addWidget(closebtn)
  2520. # CONTRIBUTE section
  2521. self.intro_tab = QtWidgets.QWidget()
  2522. self.intro_tab_layout = QtWidgets.QHBoxLayout(self.intro_tab)
  2523. self.intro_tab_layout.setContentsMargins(2, 2, 2, 2)
  2524. tab_widget.addTab(self.intro_tab, _("Contribute"))
  2525. self.grid_lay = QtWidgets.QGridLayout()
  2526. self.grid_lay.setHorizontalSpacing(20)
  2527. self.grid_lay.setColumnStretch(0, 0)
  2528. self.grid_lay.setColumnStretch(1, 1)
  2529. intro_wdg = QtWidgets.QWidget()
  2530. intro_wdg.setLayout(self.grid_lay)
  2531. intro_scroll_area = QtWidgets.QScrollArea()
  2532. intro_scroll_area.setWidget(intro_wdg)
  2533. intro_scroll_area.setWidgetResizable(True)
  2534. intro_scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2535. intro_scroll_area.setPalette(pal)
  2536. self.grid_lay.addWidget(logo, 0, 0)
  2537. self.grid_lay.addWidget(content, 0, 1)
  2538. self.intro_tab_layout.addWidget(intro_scroll_area)
  2539. # LINKS EXCHANGE section
  2540. self.links_tab = QtWidgets.QWidget()
  2541. self.links_tab_layout = QtWidgets.QVBoxLayout(self.links_tab)
  2542. self.links_tab_layout.setContentsMargins(2, 2, 2, 2)
  2543. tab_widget.addTab(self.links_tab, _("Links Exchange"))
  2544. self.links_lay = QtWidgets.QHBoxLayout()
  2545. links_wdg = QtWidgets.QWidget()
  2546. links_wdg.setLayout(self.links_lay)
  2547. links_scroll_area = QtWidgets.QScrollArea()
  2548. links_scroll_area.setWidget(links_wdg)
  2549. links_scroll_area.setWidgetResizable(True)
  2550. links_scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2551. links_scroll_area.setPalette(pal)
  2552. self.links_lay.addWidget(QtWidgets.QLabel('%s' % _("Soon ...")), alignment=QtCore.Qt.AlignCenter)
  2553. self.links_tab_layout.addWidget(links_scroll_area)
  2554. # HOW TO section
  2555. self.howto_tab = QtWidgets.QWidget()
  2556. self.howto_tab_layout = QtWidgets.QVBoxLayout(self.howto_tab)
  2557. self.howto_tab_layout.setContentsMargins(2, 2, 2, 2)
  2558. tab_widget.addTab(self.howto_tab, _("How To's"))
  2559. self.howto_lay = QtWidgets.QHBoxLayout()
  2560. howto_wdg = QtWidgets.QWidget()
  2561. howto_wdg.setLayout(self.howto_lay)
  2562. howto_scroll_area = QtWidgets.QScrollArea()
  2563. howto_scroll_area.setWidget(howto_wdg)
  2564. howto_scroll_area.setWidgetResizable(True)
  2565. howto_scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2566. howto_scroll_area.setPalette(pal)
  2567. self.howto_lay.addWidget(QtWidgets.QLabel('%s' % _("Soon ...")), alignment=QtCore.Qt.AlignCenter)
  2568. self.howto_tab_layout.addWidget(howto_scroll_area)
  2569. # BUTTONS section
  2570. closebtn.clicked.connect(self.accept)
  2571. ReadmeDialog(app=self, parent=self.ui).exec_()
  2572. def install_bookmarks(self, book_dict=None):
  2573. """
  2574. Install the bookmarks actions in the Help menu -> Bookmarks
  2575. :param book_dict: a dict having the actions text as keys and the weblinks as the values
  2576. :return: None
  2577. """
  2578. if book_dict is None:
  2579. self.defaults["global_bookmarks"].update(
  2580. {
  2581. '1': ['FlatCAM', "http://flatcam.org"],
  2582. '2': ['Backup Site', ""]
  2583. }
  2584. )
  2585. else:
  2586. self.defaults["global_bookmarks"].clear()
  2587. self.defaults["global_bookmarks"].update(book_dict)
  2588. # first try to disconnect if somehow they get connected from elsewhere
  2589. for act in self.ui.menuhelp_bookmarks.actions():
  2590. try:
  2591. act.triggered.disconnect()
  2592. except TypeError:
  2593. pass
  2594. # clear all actions except the last one who is the Bookmark manager
  2595. if act is self.ui.menuhelp_bookmarks.actions()[-1]:
  2596. pass
  2597. else:
  2598. self.ui.menuhelp_bookmarks.removeAction(act)
  2599. bm_limit = int(self.defaults["global_bookmarks_limit"])
  2600. if self.defaults["global_bookmarks"]:
  2601. # order the self.defaults["global_bookmarks"] dict keys by the value as integer
  2602. # the whole convoluted things is because when serializing the self.defaults (on app close or save)
  2603. # the JSON is first making the keys as strings (therefore I have to use strings too
  2604. # or do the conversion :(
  2605. # )
  2606. # and it is ordering them (actually I want that to make the defaults easy to search within) but making
  2607. # the '10' entry jsut after '1' therefore ordering as strings
  2608. sorted_bookmarks = sorted(list(self.defaults["global_bookmarks"].items())[:bm_limit],
  2609. key=lambda x: int(x[0]))
  2610. for entry, bookmark in sorted_bookmarks:
  2611. title = bookmark[0]
  2612. weblink = bookmark[1]
  2613. act = QtWidgets.QAction(parent=self.ui.menuhelp_bookmarks)
  2614. act.setText(title)
  2615. act.setIcon(QtGui.QIcon(self.resource_location + '/link16.png'))
  2616. # from here: https://stackoverflow.com/questions/20390323/pyqt-dynamic-generate-qmenu-action-and-connect
  2617. if title == 'Backup Site' and weblink == "":
  2618. act.triggered.connect(self.on_backup_site)
  2619. else:
  2620. act.triggered.connect(lambda sig, link=weblink: webbrowser.open(link))
  2621. self.ui.menuhelp_bookmarks.insertAction(self.ui.menuhelp_bookmarks_manager, act)
  2622. self.ui.menuhelp_bookmarks_manager.triggered.connect(self.on_bookmarks_manager)
  2623. def on_bookmarks_manager(self):
  2624. """
  2625. Adds the bookmark manager in a Tab in Plot Area
  2626. :return:
  2627. """
  2628. for idx in range(self.ui.plot_tab_area.count()):
  2629. if self.ui.plot_tab_area.tabText(idx) == _("Bookmarks Manager"):
  2630. # there can be only one instance of Bookmark Manager at one time
  2631. return
  2632. # BookDialog(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui).exec_()
  2633. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui)
  2634. self.book_dialog_tab.setObjectName("bookmarks_tab")
  2635. # add the tab if it was closed
  2636. self.ui.plot_tab_area.addTab(self.book_dialog_tab, _("Bookmarks Manager"))
  2637. # delete the absolute and relative position and messages in the infobar
  2638. # self.ui.position_label.setText("")
  2639. # self.ui.rel_position_label.setText("")
  2640. # hide coordinates toolbars in the infobar while in DB
  2641. self.ui.coords_toolbar.hide()
  2642. self.ui.delta_coords_toolbar.hide()
  2643. # Switch plot_area to preferences page
  2644. self.ui.plot_tab_area.setCurrentWidget(self.book_dialog_tab)
  2645. def on_backup_site(self):
  2646. msgbox = QtWidgets.QMessageBox()
  2647. msgbox.setText(_("This entry will resolve to another website if:\n\n"
  2648. "1. FlatCAM.org website is down\n"
  2649. "2. Someone forked FlatCAM project and wants to point\n"
  2650. "to his own website\n\n"
  2651. "If you can't get any informations about FlatCAM beta\n"
  2652. "use the YouTube channel link from the Help menu."))
  2653. msgbox.setWindowTitle(_("Alternative website"))
  2654. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/globe16.png'))
  2655. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  2656. bt_yes = msgbox.addButton(_('Close'), QtWidgets.QMessageBox.YesRole)
  2657. msgbox.setDefaultButton(bt_yes)
  2658. msgbox.exec_()
  2659. # response = msgbox.clickedButton()
  2660. def on_file_savedefaults(self):
  2661. """
  2662. Callback for menu item File->Save Defaults. Saves application default options
  2663. ``self.defaults`` to current_defaults.FlatConfig.
  2664. :return: None
  2665. """
  2666. self.preferencesUiManager.save_defaults()
  2667. def final_save(self):
  2668. """
  2669. Callback for doing a preferences save to file whenever the application is about to quit.
  2670. If the project has changes, it will ask the user to save the project.
  2671. :return: None
  2672. """
  2673. if self.save_in_progress:
  2674. self.inform.emit('[WARNING_NOTCL] %s' % _("Application is saving the project. Please wait ..."))
  2675. return
  2676. if self.should_we_save and self.collection.get_list():
  2677. msgbox = QtWidgets.QMessageBox()
  2678. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  2679. "\n"
  2680. "Do you want to Save the project?"))
  2681. msgbox.setWindowTitle(_("Save changes"))
  2682. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  2683. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  2684. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2685. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2686. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2687. msgbox.setDefaultButton(bt_yes)
  2688. msgbox.exec_()
  2689. response = msgbox.clickedButton()
  2690. if response == bt_yes:
  2691. try:
  2692. self.trayIcon.hide()
  2693. except Exception:
  2694. pass
  2695. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  2696. elif response == bt_no:
  2697. try:
  2698. self.trayIcon.hide()
  2699. except Exception:
  2700. pass
  2701. self.quit_application()
  2702. elif response == bt_cancel:
  2703. return
  2704. else:
  2705. try:
  2706. self.trayIcon.hide()
  2707. except Exception:
  2708. pass
  2709. self.quit_application()
  2710. def quit_application(self):
  2711. """
  2712. Called (as a pyslot or not) when the application is quit.
  2713. :return: None
  2714. """
  2715. # close editors before quiting the app, if they are open
  2716. if self.geo_editor.editor_active is True:
  2717. self.geo_editor.deactivate()
  2718. try:
  2719. self.geo_editor.disconnect()
  2720. except TypeError:
  2721. pass
  2722. log.debug("App.quit_application() --> Geo Editor deactivated.")
  2723. if self.exc_editor.editor_active is True:
  2724. self.exc_editor.deactivate()
  2725. try:
  2726. self.grb_editor.disconnect()
  2727. except TypeError:
  2728. pass
  2729. log.debug("App.quit_application() --> Excellon Editor deactivated.")
  2730. if self.grb_editor.editor_active is True:
  2731. self.grb_editor.deactivate_grb_editor()
  2732. try:
  2733. self.exc_editor.disconnect()
  2734. except TypeError:
  2735. pass
  2736. log.debug("App.quit_application() --> Gerber Editor deactivated.")
  2737. # disconnect the mouse events
  2738. if self.is_legacy:
  2739. self.plotcanvas.graph_event_disconnect(self.mm)
  2740. self.plotcanvas.graph_event_disconnect(self.mp)
  2741. self.plotcanvas.graph_event_disconnect(self.mr)
  2742. self.plotcanvas.graph_event_disconnect(self.mdc)
  2743. self.plotcanvas.graph_event_disconnect(self.kp)
  2744. else:
  2745. self.mm = self.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move_over_plot)
  2746. self.mp = self.plotcanvas.graph_event_disconnect('mouse_press', self.on_mouse_click_over_plot)
  2747. self.mr = self.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_click_release_over_plot)
  2748. self.mdc = self.plotcanvas.graph_event_disconnect('mouse_double_click',
  2749. self.on_mouse_double_click_over_plot)
  2750. self.kp = self.plotcanvas.graph_event_disconnect('key_press', self.ui.keyPressEvent)
  2751. self.preferencesUiManager.save_defaults(silent=True)
  2752. log.debug("App.quit_application() --> App Defaults saved.")
  2753. if self.cmd_line_headless != 1:
  2754. # save app state to file
  2755. stgs = QSettings("Open Source", "FlatCAM")
  2756. stgs.setValue('saved_gui_state', self.ui.saveState())
  2757. stgs.setValue('maximized_gui', self.ui.isMaximized())
  2758. stgs.setValue(
  2759. 'language',
  2760. self.ui.general_defaults_form.general_app_group.language_cb.get_value()
  2761. )
  2762. stgs.setValue(
  2763. 'notebook_font_size',
  2764. self.ui.general_defaults_form.general_app_set_group.notebook_font_size_spinner.get_value()
  2765. )
  2766. stgs.setValue(
  2767. 'axis_font_size',
  2768. self.ui.general_defaults_form.general_app_set_group.axis_font_size_spinner.get_value()
  2769. )
  2770. stgs.setValue(
  2771. 'textbox_font_size',
  2772. self.ui.general_defaults_form.general_app_set_group.textbox_font_size_spinner.get_value()
  2773. )
  2774. stgs.setValue(
  2775. 'hud_font_size',
  2776. self.ui.general_defaults_form.general_app_set_group.hud_font_size_spinner.get_value()
  2777. )
  2778. stgs.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  2779. stgs.setValue(
  2780. 'machinist',
  2781. 1 if self.ui.general_defaults_form.general_app_set_group.machinist_cb.get_value() else 0
  2782. )
  2783. # This will write the setting to the platform specific storage.
  2784. del stgs
  2785. log.debug("App.quit_application() --> App UI state saved.")
  2786. # try to quit the Socket opened by ArgsThread class
  2787. try:
  2788. # self.new_launch.thread_exit = True
  2789. # self.new_launch.listener.close()
  2790. self.new_launch.stop.emit()
  2791. except Exception as err:
  2792. log.debug("App.quit_application() --> %s" % str(err))
  2793. # try to quit the QThread that run ArgsThread class
  2794. try:
  2795. # del self.new_launch
  2796. self.listen_th.quit()
  2797. except Exception as e:
  2798. log.debug("App.quit_application() --> %s" % str(e))
  2799. # terminate workers
  2800. # self.workers.__del__()
  2801. self.clear_pool()
  2802. # quit app by signalling for self.kill_app() method
  2803. # self.close_app_signal.emit()
  2804. QtWidgets.qApp.quit()
  2805. sys.exit(0)
  2806. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2807. # we use the following command
  2808. # minor_v = sys.version_info.minor
  2809. # if minor_v < 8:
  2810. # # make sure that the app closes
  2811. # sys.exit(0)
  2812. # else:
  2813. # os._exit(0) # fix to work with Python 3.8
  2814. @staticmethod
  2815. def kill_app():
  2816. QtWidgets.qApp.quit()
  2817. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2818. # we use the following command
  2819. sys.exit(0)
  2820. def on_portable_checked(self, state):
  2821. """
  2822. Callback called when the checkbox in Preferences GUI is checked.
  2823. It will set the application as portable by creating the preferences and recent files in the
  2824. 'config' folder found in the FlatCAM installation folder.
  2825. :param state: boolean, the state of the checkbox when clicked/checked
  2826. :return:
  2827. """
  2828. line_no = 0
  2829. data = None
  2830. if sys.platform != 'win32':
  2831. # this won't work in Linux or MacOS
  2832. return
  2833. # test if the app was frozen and choose the path for the configuration file
  2834. if getattr(sys, "frozen", False) is True:
  2835. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  2836. else:
  2837. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  2838. config_file = current_data_path + '\\configuration.txt'
  2839. try:
  2840. with open(config_file, 'r') as f:
  2841. try:
  2842. data = f.readlines()
  2843. except Exception as e:
  2844. log.debug('App.__init__() -->%s' % str(e))
  2845. return
  2846. except FileNotFoundError:
  2847. pass
  2848. for line in data:
  2849. line = line.strip('\n')
  2850. param = str(line).rpartition('=')
  2851. if param[0] == 'portable':
  2852. break
  2853. line_no += 1
  2854. if state:
  2855. data[line_no] = 'portable=True\n'
  2856. # create the new defauults files
  2857. # create current_defaults.FlatConfig file if there is none
  2858. try:
  2859. f = open(current_data_path + '/current_defaults.FlatConfig')
  2860. f.close()
  2861. except IOError:
  2862. App.log.debug('Creating empty current_defaults.FlatConfig')
  2863. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  2864. json.dump({}, f)
  2865. f.close()
  2866. # create factory_defaults.FlatConfig file if there is none
  2867. try:
  2868. f = open(current_data_path + '/factory_defaults.FlatConfig')
  2869. f.close()
  2870. except IOError:
  2871. App.log.debug('Creating empty factory_defaults.FlatConfig')
  2872. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  2873. json.dump({}, f)
  2874. f.close()
  2875. try:
  2876. f = open(current_data_path + '/recent.json')
  2877. f.close()
  2878. except IOError:
  2879. App.log.debug('Creating empty recent.json')
  2880. f = open(current_data_path + '/recent.json', 'w')
  2881. json.dump([], f)
  2882. f.close()
  2883. try:
  2884. fp = open(current_data_path + '/recent_projects.json')
  2885. fp.close()
  2886. except IOError:
  2887. App.log.debug('Creating empty recent_projects.json')
  2888. fp = open(current_data_path + '/recent_projects.json', 'w')
  2889. json.dump([], fp)
  2890. fp.close()
  2891. # save the current defaults to the new defaults file
  2892. self.preferencesUiManager.save_defaults(silent=True, data_path=current_data_path)
  2893. else:
  2894. data[line_no] = 'portable=False\n'
  2895. with open(config_file, 'w') as f:
  2896. f.writelines(data)
  2897. def on_register_files(self, obj_type=None):
  2898. """
  2899. Called whenever there is a need to register file extensions with FlatCAM.
  2900. Works only in Windows and should be called only when FlatCAM is run in Windows.
  2901. :param obj_type: the type of object to be register for.
  2902. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  2903. :return: None
  2904. """
  2905. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  2906. new_reg_path = 'Software\\Classes\\'
  2907. # find if the current user is admin
  2908. try:
  2909. is_admin = os.getuid() == 0
  2910. except AttributeError:
  2911. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  2912. if is_admin is True:
  2913. root_path = winreg.HKEY_LOCAL_MACHINE
  2914. else:
  2915. root_path = winreg.HKEY_CURRENT_USER
  2916. # create the keys
  2917. def set_reg(name, root_pth, new_reg_path, value):
  2918. try:
  2919. winreg.CreateKey(root_pth, new_reg_path)
  2920. with winreg.OpenKey(root_pth, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  2921. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  2922. return True
  2923. except WindowsError:
  2924. return False
  2925. # delete key in registry
  2926. def delete_reg(root_pth, reg_path, key_to_del):
  2927. key_to_del_path = reg_path + key_to_del
  2928. try:
  2929. winreg.DeleteKey(root_pth, key_to_del_path)
  2930. return True
  2931. except WindowsError:
  2932. return False
  2933. if obj_type is None or obj_type == 'excellon':
  2934. exc_list = \
  2935. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  2936. exc_list = [x for x in exc_list if x != '']
  2937. # register all keys in the Preferences window
  2938. for ext in exc_list:
  2939. new_k = new_reg_path + '.%s' % ext
  2940. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2941. # and unregister those that are no longer in the Preferences windows but are in the file
  2942. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  2943. if ext not in exc_list:
  2944. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2945. # now write the updated extensions to the self.defaults
  2946. # new_ext = ''
  2947. # for ext in exc_list:
  2948. # new_ext = new_ext + ext + ', '
  2949. # self.defaults["fa_excellon"] = new_ext
  2950. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  2951. if obj_type is None or obj_type == 'gcode':
  2952. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  2953. gco_list = [x for x in gco_list if x != '']
  2954. # register all keys in the Preferences window
  2955. for ext in gco_list:
  2956. new_k = new_reg_path + '.%s' % ext
  2957. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2958. # and unregister those that are no longer in the Preferences windows but are in the file
  2959. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  2960. if ext not in gco_list:
  2961. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2962. # now write the updated extensions to the self.defaults
  2963. # new_ext = ''
  2964. # for ext in gco_list:
  2965. # new_ext = new_ext + ext + ', '
  2966. # self.defaults["fa_gcode"] = new_ext
  2967. self.inform.emit('[success] %s' %
  2968. _("Selected GCode file extensions registered with FlatCAM."))
  2969. if obj_type is None or obj_type == 'gerber':
  2970. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  2971. grb_list = [x for x in grb_list if x != '']
  2972. # register all keys in the Preferences window
  2973. for ext in grb_list:
  2974. new_k = new_reg_path + '.%s' % ext
  2975. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2976. # and unregister those that are no longer in the Preferences windows but are in the file
  2977. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  2978. if ext not in grb_list:
  2979. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2980. # now write the updated extensions to the self.defaults
  2981. # new_ext = ''
  2982. # for ext in grb_list:
  2983. # new_ext = new_ext + ext + ', '
  2984. # self.defaults["fa_gerber"] = new_ext
  2985. self.inform.emit('[success] %s' %
  2986. _("Selected Gerber file extensions registered with FlatCAM."))
  2987. def add_extension(self, ext_type):
  2988. """
  2989. Add a file extension to the list for a specific object
  2990. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  2991. :return:
  2992. """
  2993. if ext_type == 'excellon':
  2994. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  2995. if new_ext == '':
  2996. return
  2997. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  2998. if new_ext in old_val:
  2999. return
  3000. old_val.append(new_ext)
  3001. old_val.sort()
  3002. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3003. if ext_type == 'gcode':
  3004. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3005. if new_ext == '':
  3006. return
  3007. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3008. if new_ext in old_val:
  3009. return
  3010. old_val.append(new_ext)
  3011. old_val.sort()
  3012. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3013. if ext_type == 'gerber':
  3014. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3015. if new_ext == '':
  3016. return
  3017. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3018. if new_ext in old_val:
  3019. return
  3020. old_val.append(new_ext)
  3021. old_val.sort()
  3022. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3023. if ext_type == 'keyword':
  3024. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3025. if new_kw == '':
  3026. return
  3027. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3028. if new_kw in old_val:
  3029. return
  3030. old_val.append(new_kw)
  3031. old_val.sort()
  3032. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3033. # update the self.myKeywords so the model is updated
  3034. self.autocomplete_kw_list = \
  3035. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3036. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3037. self.shell._edit.set_model_data(self.myKeywords)
  3038. def del_extension(self, ext_type):
  3039. """
  3040. Remove a file extension from the list for a specific object
  3041. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3042. :return:
  3043. """
  3044. if ext_type == 'excellon':
  3045. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3046. if new_ext == '':
  3047. return
  3048. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3049. if new_ext not in old_val:
  3050. return
  3051. old_val.remove(new_ext)
  3052. old_val.sort()
  3053. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3054. if ext_type == 'gcode':
  3055. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3056. if new_ext == '':
  3057. return
  3058. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3059. if new_ext not in old_val:
  3060. return
  3061. old_val.remove(new_ext)
  3062. old_val.sort()
  3063. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3064. if ext_type == 'gerber':
  3065. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3066. if new_ext == '':
  3067. return
  3068. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3069. if new_ext not in old_val:
  3070. return
  3071. old_val.remove(new_ext)
  3072. old_val.sort()
  3073. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3074. if ext_type == 'keyword':
  3075. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3076. if new_kw == '':
  3077. return
  3078. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3079. if new_kw not in old_val:
  3080. return
  3081. old_val.remove(new_kw)
  3082. old_val.sort()
  3083. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3084. # update the self.myKeywords so the model is updated
  3085. self.autocomplete_kw_list = \
  3086. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3087. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3088. self.shell._edit.set_model_data(self.myKeywords)
  3089. def restore_extensions(self, ext_type):
  3090. """
  3091. Restore all file extensions associations with FlatCAM, for a specific object
  3092. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3093. :return:
  3094. """
  3095. if ext_type == 'excellon':
  3096. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  3097. # for the ability to open Excellon files with .txt extension
  3098. new_exc_list = deepcopy(self.exc_list)
  3099. try:
  3100. new_exc_list.remove('txt')
  3101. except ValueError:
  3102. pass
  3103. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  3104. if ext_type == 'gcode':
  3105. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  3106. if ext_type == 'gerber':
  3107. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  3108. if ext_type == 'keyword':
  3109. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  3110. # update the self.myKeywords so the model is updated
  3111. self.autocomplete_kw_list = self.default_keywords
  3112. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3113. self.shell._edit.set_model_data(self.myKeywords)
  3114. def delete_all_extensions(self, ext_type):
  3115. """
  3116. Delete all file extensions associations with FlatCAM, for a specific object
  3117. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3118. :return:
  3119. """
  3120. if ext_type == 'excellon':
  3121. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  3122. if ext_type == 'gcode':
  3123. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  3124. if ext_type == 'gerber':
  3125. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  3126. if ext_type == 'keyword':
  3127. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  3128. # update the self.myKeywords so the model is updated
  3129. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  3130. self.shell._edit.set_model_data(self.myKeywords)
  3131. def on_edit_join(self, name=None):
  3132. """
  3133. Callback for Edit->Join. Joins the selected geometry objects into
  3134. a new one.
  3135. :return: None
  3136. """
  3137. self.defaults.report_usage("on_edit_join()")
  3138. obj_name_single = str(name) if name else "Combo_SingleGeo"
  3139. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  3140. geo_type_set = set()
  3141. objs = self.collection.get_selected()
  3142. if len(objs) < 2:
  3143. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3144. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3145. return 'fail'
  3146. for obj in objs:
  3147. geo_type_set.add(obj.multigeo)
  3148. # if len(geo_type_list) == 1 means that all list elements are the same
  3149. if len(geo_type_set) != 1:
  3150. self.inform.emit('[ERROR] %s' %
  3151. _("Failed join. The Geometry objects are of different types.\n"
  3152. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  3153. "convert from one to another and retry joining \n"
  3154. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  3155. "the result may not be what was expected. \n"
  3156. "Check the generated GCODE."))
  3157. return
  3158. fuse_tools = self.defaults["geometry_merge_fuse_tools"]
  3159. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  3160. if True in geo_type_set:
  3161. def initialize(geo_obj, app):
  3162. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=True, fuse_tools=fuse_tools)
  3163. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3164. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3165. for v in geo_obj.tools.values():
  3166. v['data']['name'] = obj_name_multi
  3167. self.app_obj.new_object("geometry", obj_name_multi, initialize)
  3168. else:
  3169. def initialize(geo_obj, app):
  3170. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=False, fuse_tools=fuse_tools)
  3171. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3172. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3173. for v in geo_obj.tools.values():
  3174. v['data']['name'] = obj_name_single
  3175. self.app_obj.new_object("geometry", obj_name_single, initialize)
  3176. self.should_we_save = True
  3177. def on_edit_join_exc(self):
  3178. """
  3179. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  3180. a new Excellon.
  3181. :return: None
  3182. """
  3183. self.defaults.report_usage("on_edit_join_exc()")
  3184. objs = self.collection.get_selected()
  3185. for obj in objs:
  3186. if not isinstance(obj, ExcellonObject):
  3187. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Excellon joining works only on Excellon objects."))
  3188. return
  3189. if len(objs) < 2:
  3190. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3191. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3192. return 'fail'
  3193. fuse_tools = self.defaults["excellon_merge_fuse_tools"]
  3194. def initialize(exc_obj, app):
  3195. ExcellonObject.merge(exc_list=objs, exc_final=exc_obj, decimals=self.decimals, fuse_tools=fuse_tools)
  3196. app.inform.emit('[success] %s.' % _("Excellon merging finished"))
  3197. self.app_obj.new_object("excellon", 'Combo_Excellon', initialize)
  3198. self.should_we_save = True
  3199. def on_edit_join_grb(self):
  3200. """
  3201. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  3202. a new Gerber object.
  3203. :return: None
  3204. """
  3205. self.defaults.report_usage("on_edit_join_grb()")
  3206. objs = self.collection.get_selected()
  3207. for obj in objs:
  3208. if not isinstance(obj, GerberObject):
  3209. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Gerber joining works only on Gerber objects."))
  3210. return
  3211. if len(objs) < 2:
  3212. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3213. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3214. return 'fail'
  3215. def initialize(grb_obj, app):
  3216. GerberObject.merge(grb_list=objs, grb_final=grb_obj)
  3217. app.inform.emit('[success] %s.' % _("Gerber merging finished"))
  3218. self.app_obj.new_object("gerber", 'Combo_Gerber', initialize)
  3219. self.should_we_save = True
  3220. def on_convert_singlegeo_to_multigeo(self):
  3221. """
  3222. Called for converting a Geometry object from single-geo to multi-geo.
  3223. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3224. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3225. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3226. the solid-geometry of that tool.
  3227. :return: None
  3228. """
  3229. self.defaults.report_usage("on_convert_singlegeo_to_multigeo()")
  3230. obj = self.collection.get_active()
  3231. if obj is None:
  3232. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Select a Geometry Object and try again."))
  3233. return
  3234. if not isinstance(obj, GeometryObject):
  3235. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Expected a GeometryObject, got"), type(obj)))
  3236. return
  3237. obj.multigeo = True
  3238. for tooluid, dict_value in obj.tools.items():
  3239. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  3240. if not isinstance(obj.solid_geometry, list):
  3241. obj.solid_geometry = [obj.solid_geometry]
  3242. # obj.solid_geometry[:] = []
  3243. obj.plot()
  3244. self.should_we_save = True
  3245. self.inform.emit('[success] %s' % _("A Geometry object was converted to MultiGeo type."))
  3246. def on_convert_multigeo_to_singlegeo(self):
  3247. """
  3248. Called for converting a Geometry object from multi-geo to single-geo.
  3249. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3250. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3251. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3252. the solid-geometry of that tool.
  3253. :return: None
  3254. """
  3255. self.defaults.report_usage("on_convert_multigeo_to_singlegeo()")
  3256. obj = self.collection.get_active()
  3257. if obj is None:
  3258. self.inform.emit('[ERROR_NOTCL] %s' %
  3259. _("Failed. Select a Geometry Object and try again."))
  3260. return
  3261. if not isinstance(obj, GeometryObject):
  3262. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  3263. (_("Expected a GeometryObject, got"), type(obj)))
  3264. return
  3265. obj.multigeo = False
  3266. total_solid_geometry = []
  3267. for tooluid, dict_value in obj.tools.items():
  3268. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  3269. # clear the original geometry
  3270. dict_value['solid_geometry'][:] = []
  3271. obj.solid_geometry = deepcopy(total_solid_geometry)
  3272. obj.plot()
  3273. self.should_we_save = True
  3274. self.inform.emit('[success] %s' %
  3275. _("A Geometry object was converted to SingleGeo type."))
  3276. def on_defaults_dict_change(self, field):
  3277. """
  3278. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  3279. Edit -> Preferences tab window.
  3280. :param field: the key of the self.defaults dictionary that was changed.
  3281. :return: None
  3282. """
  3283. self.preferencesUiManager.defaults_write_form_field(field=field)
  3284. if field == "units":
  3285. self.set_screen_units(self.defaults['units'])
  3286. def set_screen_units(self, units):
  3287. """
  3288. Set the FlatCAM units on the status bar.
  3289. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  3290. :return: None
  3291. """
  3292. self.ui.units_label.setText("[" + units.lower() + "]")
  3293. def on_toggle_units_click(self):
  3294. try:
  3295. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  3296. except (TypeError, AttributeError):
  3297. pass
  3298. if self.defaults["units"] == 'MM':
  3299. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  3300. else:
  3301. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  3302. self.on_toggle_units(no_pref=True)
  3303. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  3304. lambda: self.on_toggle_units(no_pref=False))
  3305. def on_toggle_units(self, no_pref=False):
  3306. """
  3307. Callback for the Units radio-button change in the Preferences tab.
  3308. Changes the application's default units adn for the project too.
  3309. If changing the project's units, the change propagates to all of
  3310. the objects in the project.
  3311. :return: None
  3312. """
  3313. self.defaults.report_usage("on_toggle_units")
  3314. if self.toggle_units_ignore:
  3315. return
  3316. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3317. # If option is the same, then ignore
  3318. if new_units == self.defaults["units"].upper():
  3319. self.log.debug("on_toggle_units(): Same as previous, ignoring.")
  3320. return
  3321. # Keys in self.defaults for which to scale their values
  3322. dimensions = ['tools_iso_tooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin',
  3323. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f",
  3324. "tools_iso_tool_vtipdia",
  3325. "tools_iso_tool_cutz", "gerber_editor_newdim", "gerber_editor_ma_low",
  3326. "gerber_editor_ma_high",
  3327. 'excellon_cutz', 'excellon_travelz', "excellon_toolchangexy", 'excellon_offset',
  3328. 'excellon_feedrate_z', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  3329. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', 'excellon_endxy',
  3330. "excellon_feedrate_probe", "excellon_milling_dia",
  3331. "excellon_z_pdepth", "excellon_editor_newdia", "excellon_editor_lin_pitch",
  3332. "excellon_editor_slot_lin_pitch", "excellon_editor_slot_length",
  3333. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  3334. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  3335. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', 'geometry_endxy',
  3336. "geometry_extracut_length", "geometry_z_pdepth",
  3337. "geometry_feedrate_probe", "geometry_startz", "geometry_segx", "geometry_segy",
  3338. 'cncjob_tooldia',
  3339. 'tools_paintoffset', 'tools_painttooldia', "tools_paintcutz", "tools_painttipdia",
  3340. "tools_paintnewdia",
  3341. "tools_ncctools", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia",
  3342. "tools_nccnewdia", "tools_ncc_offset_value",
  3343. "tools_2sided_drilldia",
  3344. "tools_film_boundary", "tools_film_scale_stroke",
  3345. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize', "tools_cutout_z",
  3346. "tools_cutout_depthperpass",
  3347. "tools_panelize_constrainx", "tools_panelize_constrainy", "tools_panelize_spacing_columns",
  3348. "tools_panelize_spacing_rows",
  3349. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  3350. "tools_transform_offset_x", "tools_transform_offset_y", "tools_transform_mirror_point",
  3351. "tools_transform_buffer_dis",
  3352. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  3353. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  3354. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  3355. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  3356. "tools_cr_trace_size_val", "tools_cr_c2c_val", "tools_cr_c2o_val", "tools_cr_s2s_val",
  3357. "tools_cr_s2sm_val", "tools_cr_s2o_val", "tools_cr_sm2sm_val", "tools_cr_ri_val",
  3358. "tools_cr_h2h_val", "tools_cr_dh_val",
  3359. "tools_fiducials_dia", "tools_fiducials_margin", "tools_fiducials_line_thickness",
  3360. "tools_copper_thieving_clearance", "tools_copper_thieving_margin",
  3361. "tools_copper_thieving_dots_dia", "tools_copper_thieving_dots_spacing",
  3362. "tools_copper_thieving_squares_size", "tools_copper_thieving_squares_spacing",
  3363. "tools_copper_thieving_lines_size", "tools_copper_thieving_lines_spacing",
  3364. "tools_copper_thieving_rb_margin", "tools_copper_thieving_rb_thickness",
  3365. "tools_copper_thieving_mask_clearance",
  3366. "tools_cal_travelz", "tools_cal_verz", "tools_cal_toolchangez", "tools_cal_toolchange_xy",
  3367. "tools_edrills_hole_fixed_dia", "tools_edrills_circular_ring", "tools_edrills_oblong_ring",
  3368. "tools_edrills_square_ring", "tools_edrills_rectangular_ring", "tools_edrills_others_ring",
  3369. "tools_punch_hole_fixed_dia", "tools_punch_circular_ring", "tools_punch_oblong_ring",
  3370. "tools_punch_square_ring", "tools_punch_rectangular_ring", "tools_punch_others_ring",
  3371. "tools_invert_margin",
  3372. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance",
  3373. 'global_tpdf_bmargin', 'global_tpdf_tmargin', 'global_tpdf_rmargin', 'global_tpdf_lmargin']
  3374. def scale_defaults(sfactor):
  3375. for dim in dimensions:
  3376. if dim in [
  3377. 'gerber_editor_newdim', 'excellon_toolchangexy', 'geometry_toolchangexy', 'excellon_endxy',
  3378. 'geometry_endxy', 'tools_solderpaste_xy_toolchange', 'tools_cal_toolchange_xy',
  3379. 'tools_transform_mirror_point'
  3380. ]:
  3381. if self.defaults[dim] is None or self.defaults[dim] == '':
  3382. continue
  3383. try:
  3384. coordinates = self.defaults[dim].split(",")
  3385. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3386. coords_xy[0] *= sfactor
  3387. coords_xy[1] *= sfactor
  3388. self.defaults[dim] = "%.*f, %.*f" % (
  3389. self.decimals, coords_xy[0], self.decimals, coords_xy[1])
  3390. except Exception as e:
  3391. log.debug("App.on_toggle_units.scale_defaults() --> 'string tuples': %s" % str(e))
  3392. elif dim in [
  3393. 'geometry_cnctooldia', 'tools_ncctools', 'tools_solderpaste_tools'
  3394. ]:
  3395. if self.defaults[dim] is None or self.defaults[dim] == '':
  3396. continue
  3397. try:
  3398. self.defaults[dim] = float(self.defaults[dim])
  3399. tools_diameters = [self.defaults[dim]]
  3400. except ValueError:
  3401. try:
  3402. tools_string = self.defaults[dim].split(",")
  3403. tools_diameters = [eval(a) for a in tools_string if a != '']
  3404. except Exception as e:
  3405. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3406. continue
  3407. self.defaults[dim] = ''
  3408. td_len = len(tools_diameters)
  3409. if td_len > 1:
  3410. for t in range(td_len):
  3411. tools_diameters[t] *= sfactor
  3412. self.defaults[dim] += "%.*f," % (self.decimals, tools_diameters[t])
  3413. else:
  3414. tools_diameters[0] *= sfactor
  3415. self.defaults[dim] += "%.*f" % (self.decimals, tools_diameters[0])
  3416. elif dim in ['global_gridx', 'global_gridy']:
  3417. # format the number of decimals to the one specified in self.decimals
  3418. try:
  3419. val = float(self.defaults[dim]) * sfactor
  3420. except Exception as e:
  3421. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3422. continue
  3423. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  3424. else:
  3425. # the number of decimals for the rest is kept unchanged
  3426. if self.defaults[dim]:
  3427. try:
  3428. val = float(self.defaults[dim]) * sfactor
  3429. except Exception as e:
  3430. log.debug('App.on_toggle_units().scale_defaults() --> Value: %s %s' % (str(dim), str(e)))
  3431. continue
  3432. self.defaults[dim] = val
  3433. # The scaling factor depending on choice of units.
  3434. factor = 25.4 if new_units == 'MM' else 1 / 25.4
  3435. # Changing project units. Warn user.
  3436. msgbox = QtWidgets.QMessageBox()
  3437. msgbox.setWindowTitle(_("Toggle Units"))
  3438. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/toggle_units32.png'))
  3439. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  3440. msgbox.setText(_("Changing the units of the project\n"
  3441. "will scale all objects.\n\n"
  3442. "Do you want to continue?"))
  3443. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3444. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3445. msgbox.setDefaultButton(bt_ok)
  3446. msgbox.exec_()
  3447. response = msgbox.clickedButton()
  3448. if response == bt_ok:
  3449. if no_pref is False:
  3450. self.preferencesUiManager.defaults_read_form()
  3451. scale_defaults(factor)
  3452. self.preferencesUiManager.defaults_write_form(fl_units=new_units)
  3453. self.defaults["units"] = new_units
  3454. # update the defaults from form, some may assume that the conversion is enough and it's not
  3455. self.on_options_app2project()
  3456. # update the objects
  3457. for obj in self.collection.get_list():
  3458. obj.convert_units(new_units)
  3459. # make that the properties stored in the object are also updated
  3460. self.app_obj.object_changed.emit(obj)
  3461. # rebuild the object UI
  3462. obj.build_ui()
  3463. # change this only if the workspace is active
  3464. if self.defaults['global_workspace'] is True:
  3465. self.plotcanvas.draw_workspace(pagesize=self.defaults['global_workspaceT'])
  3466. # adjust the grid values on the main toolbar
  3467. val_x = float(self.defaults['global_gridx']) * factor
  3468. val_y = val_x if self.ui.grid_gap_link_cb.isChecked() else float(self.defaults['global_gridx']) * factor
  3469. current = self.collection.get_active()
  3470. if current is not None:
  3471. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  3472. if not isinstance(current, GeometryObject):
  3473. current.to_form()
  3474. # replot all objects
  3475. self.plot_all()
  3476. # set the status labels to reflect the current FlatCAM units
  3477. self.set_screen_units(new_units)
  3478. # signal to the app that we changed the object properties and it should save the project
  3479. self.should_we_save = True
  3480. self.inform.emit('[success] %s: %s' % (_("Converted units to"), new_units))
  3481. else:
  3482. # Undo toggling
  3483. self.toggle_units_ignore = True
  3484. if self.defaults['units'].upper() == 'MM':
  3485. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  3486. else:
  3487. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  3488. self.toggle_units_ignore = False
  3489. # store the grid values so they are not changed in the next step
  3490. val_x = float(self.defaults['global_gridx'])
  3491. val_y = float(self.defaults['global_gridy'])
  3492. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  3493. self.preferencesUiManager.defaults_read_form()
  3494. # the self.preferencesUiManager.defaults_read_form() will update all defaults values
  3495. # in self.defaults from the GUI elements but
  3496. # I don't want it for the grid values, so I update them here
  3497. self.defaults['global_gridx'] = val_x
  3498. self.defaults['global_gridy'] = val_y
  3499. self.ui.grid_gap_x_entry.set_value(val_x, decimals=self.decimals)
  3500. self.ui.grid_gap_y_entry.set_value(val_y, decimals=self.decimals)
  3501. def on_deselect_all(self):
  3502. self.collection.set_all_inactive()
  3503. self.delete_selection_shape()
  3504. def on_workspace_modified(self):
  3505. # self.save_defaults(silent=True)
  3506. self.plotcanvas.delete_workspace()
  3507. self.preferencesUiManager.defaults_read_form()
  3508. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3509. def on_workspace(self):
  3510. if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value():
  3511. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3512. self.inform[str, bool].emit(_("Workspace enabled."), False)
  3513. else:
  3514. self.plotcanvas.delete_workspace()
  3515. self.inform[str, bool].emit(_("Workspace disabled."), False)
  3516. self.preferencesUiManager.defaults_read_form()
  3517. # self.save_defaults(silent=True)
  3518. def on_workspace_toggle(self):
  3519. state = False if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value() else True
  3520. try:
  3521. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.disconnect(self.on_workspace)
  3522. except TypeError:
  3523. pass
  3524. self.ui.general_defaults_form.general_app_set_group.workspace_cb.set_value(state)
  3525. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  3526. self.on_workspace()
  3527. def on_cursor_type(self, val):
  3528. """
  3529. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  3530. :return: None
  3531. """
  3532. self.app_cursor.enabled = False
  3533. if val == 'small':
  3534. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(False)
  3535. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(False)
  3536. self.app_cursor = self.plotcanvas.new_cursor()
  3537. else:
  3538. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(True)
  3539. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(True)
  3540. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  3541. if self.ui.grid_snap_btn.isChecked():
  3542. self.app_cursor.enabled = True
  3543. else:
  3544. self.app_cursor.enabled = False
  3545. def on_tool_add_keypress(self):
  3546. # ## Current application units in Upper Case
  3547. self.units = self.defaults['units'].upper()
  3548. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3549. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3550. if notebook_widget_name == 'selected_tab':
  3551. if self.collection.get_active().kind == 'geometry':
  3552. # Tool add works for Geometry only if Advanced is True in Preferences
  3553. if self.defaults["global_app_level"] == 'a':
  3554. tool_add_popup = FCInputDialog(title="New Tool ...",
  3555. text='Enter a Tool Diameter:',
  3556. min=0.0000, max=99.9999, decimals=4)
  3557. tool_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/letter_t_32.png'))
  3558. val, ok = tool_add_popup.get_value()
  3559. if ok:
  3560. if float(val) == 0:
  3561. self.inform.emit('[WARNING_NOTCL] %s' %
  3562. _("Please enter a tool diameter with non-zero value, in Float format."))
  3563. return
  3564. self.collection.get_active().on_tool_add(dia=float(val))
  3565. else:
  3566. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  3567. else:
  3568. msgbox = QtWidgets.QMessageBox()
  3569. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  3570. "Go to Preferences -> General - Show Advanced Options."))
  3571. msgbox.setWindowTitle("Tool adding ...")
  3572. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/warning.png'))
  3573. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  3574. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3575. msgbox.setDefaultButton(bt_ok)
  3576. msgbox.exec_()
  3577. # work only if the notebook tab on focus is the Tools_Tab
  3578. if notebook_widget_name == 'tool_tab':
  3579. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3580. # and only if the tool is NCC Tool
  3581. if tool_widget == self.ncclear_tool.toolName:
  3582. self.ncclear_tool.on_add_tool_by_key()
  3583. # and only if the tool is Paint Area Tool
  3584. elif tool_widget == self.paint_tool.toolName:
  3585. self.paint_tool.on_add_tool_by_key()
  3586. # and only if the tool is Solder Paste Dispensing Tool
  3587. elif tool_widget == self.paste_tool.toolName:
  3588. self.paste_tool.on_add_tool_by_key()
  3589. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  3590. # See description below.
  3591. def on_delete_keypress(self):
  3592. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3593. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3594. if notebook_widget_name == 'selected_tab':
  3595. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.GeometryObject'>":
  3596. self.collection.get_active().on_tool_delete()
  3597. # work only if the notebook tab on focus is the Tools_Tab
  3598. elif notebook_widget_name == 'tool_tab':
  3599. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3600. # and only if the tool is NCC Tool
  3601. if tool_widget == self.ncclear_tool.toolName:
  3602. self.ncclear_tool.on_tool_delete()
  3603. # and only if the tool is Paint Tool
  3604. elif tool_widget == self.paint_tool.toolName:
  3605. self.paint_tool.on_tool_delete()
  3606. # and only if the tool is Solder Paste Dispensing Tool
  3607. elif tool_widget == self.paste_tool.toolName:
  3608. self.paste_tool.on_tool_delete()
  3609. # and only if the tool is Isolation Tool
  3610. elif tool_widget == self.isolation_tool.toolName:
  3611. self.isolation_tool.on_tool_delete()
  3612. else:
  3613. self.on_delete()
  3614. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  3615. # some screens you have to be careful where you hover with your mouse.
  3616. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  3617. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  3618. # Complicated, I know :)
  3619. def on_delete(self, force_deletion=False):
  3620. """
  3621. Delete the currently selected FlatCAMObjs.
  3622. :param force_deletion: used by Tcl command
  3623. :return: None
  3624. """
  3625. self.defaults.report_usage("on_delete()")
  3626. response = None
  3627. bt_ok = None
  3628. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  3629. # a geometry object before we update it.
  3630. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  3631. and self.grb_editor.editor_active is False:
  3632. if self.defaults["global_delete_confirmation"] is True and force_deletion is False:
  3633. msgbox = QtWidgets.QMessageBox()
  3634. msgbox.setWindowTitle(_("Delete objects"))
  3635. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/deleteshape32.png'))
  3636. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  3637. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  3638. msgbox.setText(_("Are you sure you want to permanently delete\n"
  3639. "the selected objects?"))
  3640. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3641. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3642. msgbox.setDefaultButton(bt_ok)
  3643. msgbox.exec_()
  3644. response = msgbox.clickedButton()
  3645. if self.defaults["global_delete_confirmation"] is False or force_deletion is True:
  3646. response = bt_ok
  3647. if response == bt_ok:
  3648. if self.collection.get_active():
  3649. self.log.debug("App.on_delete()")
  3650. for obj_active in self.collection.get_selected():
  3651. # if the deleted object is GerberObject then make sure to delete the possible mark shapes
  3652. if obj_active.kind == 'gerber':
  3653. for el in obj_active.mark_shapes:
  3654. obj_active.mark_shapes[el].clear(update=True)
  3655. obj_active.mark_shapes[el].enabled = False
  3656. # obj_active.mark_shapes[el] = None
  3657. del el
  3658. elif obj_active.kind == 'cncjob':
  3659. try:
  3660. obj_active.text_col.enabled = False
  3661. del obj_active.text_col
  3662. obj_active.annotation.clear(update=True)
  3663. del obj_active.annotation
  3664. except AttributeError as e:
  3665. log.debug(
  3666. "App.on_delete() --> delete annotations on a FlatCAMCNCJob object. %s" % str(e)
  3667. )
  3668. while self.collection.get_selected():
  3669. self.delete_first_selected()
  3670. # make sure that the selection shape is deleted, too
  3671. self.delete_selection_shape()
  3672. # if there are no longer objects delete also the exclusion areas shapes
  3673. if not self.collection.get_list():
  3674. self.exc_areas.clear_shapes()
  3675. self.inform.emit('%s...' % _("Object(s) deleted"))
  3676. else:
  3677. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  3678. else:
  3679. self.inform.emit(_("Save the work in Editor and try again ..."))
  3680. def delete_first_selected(self):
  3681. # Keep this for later
  3682. try:
  3683. sel_obj = self.collection.get_active()
  3684. name = sel_obj.options["name"]
  3685. isPlotted = sel_obj.options["plot"]
  3686. except AttributeError:
  3687. self.log.debug("Nothing selected for deletion")
  3688. return
  3689. if self.is_legacy is True:
  3690. # Remove plot only if the object was plotted otherwise delaxes will fail
  3691. if isPlotted:
  3692. try:
  3693. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  3694. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  3695. except Exception as e:
  3696. log.debug("App.delete_first_selected() --> %s" % str(e))
  3697. self.plotcanvas.auto_adjust_axes()
  3698. # Remove from dictionary
  3699. self.collection.delete_active()
  3700. # Clear form
  3701. self.setup_component_editor()
  3702. self.inform.emit('%s: %s' % (_("Object deleted"), name))
  3703. def on_set_origin(self):
  3704. """
  3705. Set the origin to the left mouse click position
  3706. :return: None
  3707. """
  3708. # display the message for the user
  3709. # and ask him to click on the desired position
  3710. self.defaults.report_usage("on_set_origin()")
  3711. def origin_replot():
  3712. def worker_task():
  3713. with self.proc_container.new('%s...' % _("Plotting")):
  3714. for obj in self.collection.get_list():
  3715. obj.plot()
  3716. self.plotcanvas.fit_view()
  3717. if self.is_legacy:
  3718. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  3719. else:
  3720. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  3721. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3722. self.inform.emit(_('Click to set the origin ...'))
  3723. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  3724. # first disconnect it as it may have been used by something else
  3725. try:
  3726. self.replot_signal.disconnect()
  3727. except TypeError:
  3728. pass
  3729. self.replot_signal[list].connect(origin_replot)
  3730. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  3731. """
  3732. :param event:
  3733. :param location:
  3734. :param noplot:
  3735. :param use_thread:
  3736. :return:
  3737. """
  3738. noplot_sig = noplot
  3739. def worker_task():
  3740. with self.proc_container.new(_("Setting Origin...")):
  3741. obj_list = self.collection.get_list()
  3742. for obj in obj_list:
  3743. obj.offset((x, y))
  3744. self.app_obj.object_changed.emit(obj)
  3745. # Update the object bounding box options
  3746. a, b, c, d = obj.bounds()
  3747. obj.options['xmin'] = a
  3748. obj.options['ymin'] = b
  3749. obj.options['xmax'] = c
  3750. obj.options['ymax'] = d
  3751. self.inform.emit('[success] %s...' % _('Origin set'))
  3752. for obj in obj_list:
  3753. out_name = obj.options["name"]
  3754. if obj.kind == 'gerber':
  3755. obj.source_file = self.export_gerber(
  3756. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3757. elif obj.kind == 'excellon':
  3758. obj.source_file = self.export_excellon(
  3759. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3760. if noplot_sig is False:
  3761. self.replot_signal.emit([])
  3762. if location is not None:
  3763. if len(location) != 2:
  3764. self.inform.emit('[ERROR_NOTCL] %s...' % _("Origin coordinates specified but incomplete."))
  3765. return 'fail'
  3766. x, y = location
  3767. if use_thread is True:
  3768. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3769. else:
  3770. worker_task()
  3771. self.should_we_save = True
  3772. return
  3773. if event is not None and event.button == 1:
  3774. if self.is_legacy is False:
  3775. event_pos = event.pos
  3776. else:
  3777. event_pos = (event.xdata, event.ydata)
  3778. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  3779. if self.grid_status():
  3780. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3781. else:
  3782. pos = pos_canvas
  3783. x = 0 - pos[0]
  3784. y = 0 - pos[1]
  3785. if use_thread is True:
  3786. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3787. else:
  3788. worker_task()
  3789. self.should_we_save = True
  3790. def on_move2origin(self, use_thread=True):
  3791. """
  3792. Move selected objects to origin.
  3793. :param use_thread: Control if to use threaded operation. Boolean.
  3794. :return:
  3795. """
  3796. def worker_task():
  3797. with self.proc_container.new(_("Moving to Origin...")):
  3798. obj_list = self.collection.get_selected()
  3799. if not obj_list:
  3800. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  3801. return
  3802. xminlist = []
  3803. yminlist = []
  3804. # first get a bounding box to fit all
  3805. for obj in obj_list:
  3806. xmin, ymin, xmax, ymax = obj.bounds()
  3807. xminlist.append(xmin)
  3808. yminlist.append(ymin)
  3809. # get the minimum x,y for all objects selected
  3810. x = min(xminlist)
  3811. y = min(yminlist)
  3812. for obj in obj_list:
  3813. obj.offset((-x, -y))
  3814. self.app_obj.object_changed.emit(obj)
  3815. # Update the object bounding box options
  3816. a, b, c, d = obj.bounds()
  3817. obj.options['xmin'] = a
  3818. obj.options['ymin'] = b
  3819. obj.options['xmax'] = c
  3820. obj.options['ymax'] = d
  3821. for obj in obj_list:
  3822. obj.plot()
  3823. for obj in obj_list:
  3824. out_name = obj.options["name"]
  3825. if obj.kind == 'gerber':
  3826. obj.source_file = self.export_gerber(
  3827. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3828. elif obj.kind == 'excellon':
  3829. obj.source_file = self.export_excellon(
  3830. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3831. self.inform.emit('[success] %s...' % _('Origin set'))
  3832. if use_thread is True:
  3833. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3834. else:
  3835. worker_task()
  3836. self.should_we_save = True
  3837. def on_jump_to(self, custom_location=None, fit_center=True):
  3838. """
  3839. Jump to a location by setting the mouse cursor location.
  3840. :param custom_location: Jump to a specified point. (x, y) tuple.
  3841. :param fit_center: If to fit view. Boolean.
  3842. :return:
  3843. """
  3844. self.defaults.report_usage("on_jump_to()")
  3845. if not custom_location:
  3846. dia_box_location = None
  3847. try:
  3848. dia_box_location = eval(self.clipboard.text())
  3849. except Exception:
  3850. pass
  3851. if type(dia_box_location) == tuple:
  3852. dia_box_location = str(dia_box_location)
  3853. else:
  3854. dia_box_location = None
  3855. # dia_box = Dialog_box(title=_("Jump to ..."),
  3856. # label=_("Enter the coordinates in format X,Y:"),
  3857. # icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  3858. # initial_text=dia_box_location)
  3859. dia_box = DialogBoxRadio(title=_("Jump to ..."),
  3860. label=_("Enter the coordinates in format X,Y:"),
  3861. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  3862. initial_text=dia_box_location,
  3863. reference=self.defaults['global_jump_ref'])
  3864. if dia_box.ok is True:
  3865. try:
  3866. location = eval(dia_box.location)
  3867. if not isinstance(location, tuple):
  3868. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  3869. return
  3870. if dia_box.reference == 'rel':
  3871. rel_x = self.mouse[0] + location[0]
  3872. rel_y = self.mouse[1] + location[1]
  3873. location = (rel_x, rel_y)
  3874. self.defaults['global_jump_ref'] = dia_box.reference
  3875. except Exception:
  3876. return
  3877. else:
  3878. return
  3879. else:
  3880. location = custom_location
  3881. self.jump_signal.emit(location)
  3882. if fit_center:
  3883. self.plotcanvas.fit_center(loc=location)
  3884. cursor = QtGui.QCursor()
  3885. if self.is_legacy is False:
  3886. # I don't know where those differences come from but they are constant for the current
  3887. # execution of the application and they are multiples of a value around 0.0263mm.
  3888. # In a random way sometimes they are more sometimes they are less
  3889. # if units == 'MM':
  3890. # cal_factor = 0.0263
  3891. # else:
  3892. # cal_factor = 0.0263 / 25.4
  3893. cal_location = (location[0], location[1])
  3894. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3895. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  3896. j_pos = (
  3897. int(canvas_origin.x() + round(jump_loc[0])),
  3898. int(canvas_origin.y() + round(jump_loc[1]))
  3899. )
  3900. cursor.setPos(j_pos[0], j_pos[1])
  3901. else:
  3902. # find the canvas origin which is in the top left corner
  3903. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3904. # determine the coordinates for the lowest left point of the canvas
  3905. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  3906. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  3907. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  3908. # canvas) and the point (width, height) is in the top-right location
  3909. loc = self.plotcanvas.axes.transData.transform_point(location)
  3910. j_pos = (
  3911. int(x0 + loc[0]),
  3912. int(y0 - loc[1])
  3913. )
  3914. cursor.setPos(j_pos[0], j_pos[1])
  3915. self.plotcanvas.mouse = [location[0], location[1]]
  3916. if self.defaults["global_cursor_color_enabled"] is True:
  3917. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  3918. else:
  3919. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  3920. if self.grid_status():
  3921. # Update cursor
  3922. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  3923. symbol='++', edge_color=self.cursor_color_3D,
  3924. edge_width=self.defaults["global_cursor_width"],
  3925. size=self.defaults["global_cursor_size"])
  3926. # Set the relative position label
  3927. dx = location[0] - float(self.rel_point1[0])
  3928. dy = location[1] - float(self.rel_point1[1])
  3929. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  3930. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  3931. # Set the position label
  3932. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3933. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  3934. units = self.defaults["units"].lower()
  3935. self.plotcanvas.text_hud.text = \
  3936. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  3937. dx, units, dy, units, location[0], units, location[1], units)
  3938. self.inform.emit('[success] %s' % _("Done."))
  3939. return location
  3940. def on_locate(self, obj, fit_center=True):
  3941. """
  3942. Jump to one of the corners (or center) of an object by setting the mouse cursor location
  3943. :param obj: The object on which to locate certain points
  3944. :param fit_center: If to fit view. Boolean.
  3945. :return: A point location. (x, y) tuple.
  3946. """
  3947. self.defaults.report_usage("on_locate()")
  3948. if obj is None:
  3949. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  3950. return 'fail'
  3951. class DialogBoxChoice(QtWidgets.QDialog):
  3952. def __init__(self, title=None, icon=None, choice='bl'):
  3953. """
  3954. :param title: string with the window title
  3955. """
  3956. super(DialogBoxChoice, self).__init__()
  3957. self.ok = False
  3958. self.setWindowIcon(icon)
  3959. self.setWindowTitle(str(title))
  3960. self.form = QtWidgets.QFormLayout(self)
  3961. self.ref_radio = RadioSet([
  3962. {"label": _("Bottom-Left"), "value": "bl"},
  3963. {"label": _("Top-Left"), "value": "tl"},
  3964. {"label": _("Bottom-Right"), "value": "br"},
  3965. {"label": _("Top-Right"), "value": "tr"},
  3966. {"label": _("Center"), "value": "c"}
  3967. ], orientation='vertical', stretch=False)
  3968. self.ref_radio.set_value(choice)
  3969. self.form.addRow(self.ref_radio)
  3970. self.button_box = QtWidgets.QDialogButtonBox(
  3971. QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,
  3972. Qt.Horizontal, parent=self)
  3973. self.form.addRow(self.button_box)
  3974. self.button_box.accepted.connect(self.accept)
  3975. self.button_box.rejected.connect(self.reject)
  3976. if self.exec_() == QtWidgets.QDialog.Accepted:
  3977. self.ok = True
  3978. self.location_point = self.ref_radio.get_value()
  3979. else:
  3980. self.ok = False
  3981. self.location_point = None
  3982. dia_box = DialogBoxChoice(title=_("Locate ..."),
  3983. icon=QtGui.QIcon(self.resource_location + '/locate16.png'),
  3984. choice=self.defaults['global_locate_pt'])
  3985. if dia_box.ok is True:
  3986. try:
  3987. location_point = dia_box.location_point
  3988. self.defaults['global_locate_pt'] = dia_box.location_point
  3989. except Exception:
  3990. return
  3991. else:
  3992. return
  3993. loc_b = obj.bounds()
  3994. if location_point == 'bl':
  3995. location = (loc_b[0], loc_b[1])
  3996. elif location_point == 'tl':
  3997. location = (loc_b[0], loc_b[3])
  3998. elif location_point == 'br':
  3999. location = (loc_b[2], loc_b[1])
  4000. elif location_point == 'tr':
  4001. location = (loc_b[2], loc_b[3])
  4002. else:
  4003. # center
  4004. cx = loc_b[0] + ((loc_b[2] - loc_b[0]) / 2)
  4005. cy = loc_b[1] + ((loc_b[3] - loc_b[1]) / 2)
  4006. location = (cx, cy)
  4007. self.locate_signal.emit(location, location_point)
  4008. if fit_center:
  4009. self.plotcanvas.fit_center(loc=location)
  4010. cursor = QtGui.QCursor()
  4011. if self.is_legacy is False:
  4012. # I don't know where those differences come from but they are constant for the current
  4013. # execution of the application and they are multiples of a value around 0.0263mm.
  4014. # In a random way sometimes they are more sometimes they are less
  4015. # if units == 'MM':
  4016. # cal_factor = 0.0263
  4017. # else:
  4018. # cal_factor = 0.0263 / 25.4
  4019. cal_location = (location[0], location[1])
  4020. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4021. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  4022. j_pos = (
  4023. int(canvas_origin.x() + round(jump_loc[0])),
  4024. int(canvas_origin.y() + round(jump_loc[1]))
  4025. )
  4026. cursor.setPos(j_pos[0], j_pos[1])
  4027. else:
  4028. # find the canvas origin which is in the top left corner
  4029. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4030. # determine the coordinates for the lowest left point of the canvas
  4031. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  4032. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  4033. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  4034. # canvas) and the point (width, height) is in the top-right location
  4035. loc = self.plotcanvas.axes.transData.transform_point(location)
  4036. j_pos = (
  4037. int(x0 + loc[0]),
  4038. int(y0 - loc[1])
  4039. )
  4040. cursor.setPos(j_pos[0], j_pos[1])
  4041. self.plotcanvas.mouse = [location[0], location[1]]
  4042. if self.defaults["global_cursor_color_enabled"] is True:
  4043. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  4044. else:
  4045. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  4046. if self.grid_status():
  4047. # Update cursor
  4048. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  4049. symbol='++', edge_color=self.cursor_color_3D,
  4050. edge_width=self.defaults["global_cursor_width"],
  4051. size=self.defaults["global_cursor_size"])
  4052. # Set the relative position label
  4053. self.dx = location[0] - float(self.rel_point1[0])
  4054. self.dy = location[1] - float(self.rel_point1[1])
  4055. # Set the position label
  4056. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4057. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  4058. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4059. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  4060. units = self.defaults["units"].lower()
  4061. self.plotcanvas.text_hud.text = \
  4062. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  4063. self.dx, units, self.dy, units, location[0], units, location[1], units)
  4064. self.inform.emit('[success] %s' % _("Done."))
  4065. return location
  4066. def on_copy_command(self):
  4067. """
  4068. Will copy a selection of objects, creating new objects.
  4069. :return:
  4070. """
  4071. self.defaults.report_usage("on_copy_command()")
  4072. def initialize(obj_init, app):
  4073. """
  4074. :param obj_init: the new object
  4075. :type obj_init: class
  4076. :param app: An instance of the App class
  4077. :type app: App
  4078. :return: None
  4079. :rtype:
  4080. """
  4081. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4082. try:
  4083. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4084. except AttributeError:
  4085. pass
  4086. try:
  4087. obj_init.apertures = deepcopy(obj.apertures)
  4088. except AttributeError:
  4089. pass
  4090. try:
  4091. if obj.tools:
  4092. obj_init.tools = deepcopy(obj.tools)
  4093. except Exception as err:
  4094. log.debug("App.on_copy_command() --> %s" % str(err))
  4095. try:
  4096. obj_init.source_file = deepcopy(obj.source_file)
  4097. except (AttributeError, TypeError):
  4098. pass
  4099. def initialize_excellon(obj_init, app):
  4100. obj_init.source_file = deepcopy(obj.source_file)
  4101. obj_init.tools = deepcopy(obj.tools)
  4102. # drills are offset, so they need to be deep copied
  4103. obj_init.drills = deepcopy(obj.drills)
  4104. # slots are offset, so they need to be deep copied
  4105. obj_init.slots = deepcopy(obj.slots)
  4106. obj_init.create_geometry()
  4107. def initialize_script(obj_init, app_obj):
  4108. obj_init.source_file = deepcopy(obj.source_file)
  4109. def initialize_document(obj_init, app_obj):
  4110. obj_init.source_file = deepcopy(obj.source_file)
  4111. for obj in self.collection.get_selected():
  4112. obj_name = obj.options["name"]
  4113. try:
  4114. if isinstance(obj, ExcellonObject):
  4115. self.app_obj.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  4116. elif isinstance(obj, GerberObject):
  4117. self.app_obj.new_object("gerber", str(obj_name) + "_copy", initialize)
  4118. elif isinstance(obj, GeometryObject):
  4119. self.app_obj.new_object("geometry", str(obj_name) + "_copy", initialize)
  4120. elif isinstance(obj, ScriptObject):
  4121. self.app_obj.new_object("script", str(obj_name) + "_copy", initialize_script)
  4122. elif isinstance(obj, DocumentObject):
  4123. self.app_obj.new_object("document", str(obj_name) + "_copy", initialize_document)
  4124. except Exception as e:
  4125. return "Operation failed: %s" % str(e)
  4126. def on_copy_object2(self, custom_name):
  4127. def initialize_geometry(obj_init, app):
  4128. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4129. try:
  4130. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4131. except AttributeError:
  4132. pass
  4133. try:
  4134. obj_init.apertures = deepcopy(obj.apertures)
  4135. except AttributeError:
  4136. pass
  4137. try:
  4138. if obj.tools:
  4139. obj_init.tools = deepcopy(obj.tools)
  4140. except Exception as ee:
  4141. log.debug("on_copy_object2() --> %s" % str(ee))
  4142. def initialize_gerber(obj_init, app):
  4143. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4144. obj_init.apertures = deepcopy(obj.apertures)
  4145. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  4146. def initialize_excellon(obj_init, app):
  4147. obj_init.tools = deepcopy(obj.tools)
  4148. # drills are offset, so they need to be deep copied
  4149. obj_init.drills = deepcopy(obj.drills)
  4150. # slots are offset, so they need to be deep copied
  4151. obj_init.slots = deepcopy(obj.slots)
  4152. obj_init.create_geometry()
  4153. for obj in self.collection.get_selected():
  4154. obj_name = obj.options["name"]
  4155. try:
  4156. if isinstance(obj, ExcellonObject):
  4157. self.app_obj.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  4158. elif isinstance(obj, GerberObject):
  4159. self.app_obj.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  4160. elif isinstance(obj, GeometryObject):
  4161. self.app_obj.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  4162. except Exception as er:
  4163. return "Operation failed: %s" % str(er)
  4164. def on_rename_object(self, text):
  4165. """
  4166. Will rename an object.
  4167. :param text: New name for the object.
  4168. :return:
  4169. """
  4170. self.defaults.report_usage("on_rename_object()")
  4171. named_obj = self.collection.get_active()
  4172. for obj in named_obj:
  4173. if obj is list:
  4174. self.on_rename_object(text)
  4175. else:
  4176. try:
  4177. obj.options['name'] = text
  4178. except Exception as e:
  4179. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  4180. def convert_any2geo(self):
  4181. """
  4182. Will convert any object out of Gerber, Excellon, Geometry to Geometry object.
  4183. :return:
  4184. """
  4185. self.defaults.report_usage("convert_any2geo()")
  4186. def initialize(obj_init, app):
  4187. obj_init.solid_geometry = obj.solid_geometry
  4188. try:
  4189. obj_init.follow_geometry = obj.follow_geometry
  4190. except AttributeError:
  4191. pass
  4192. try:
  4193. obj_init.apertures = obj.apertures
  4194. except AttributeError:
  4195. pass
  4196. try:
  4197. if obj.tools:
  4198. obj_init.tools = obj.tools
  4199. except AttributeError:
  4200. pass
  4201. def initialize_excellon(obj_init, app):
  4202. # objs = self.collection.get_selected()
  4203. # GeometryObject.merge(objs, obj)
  4204. solid_geo = []
  4205. for tool in obj.tools:
  4206. for geo in obj.tools[tool]['solid_geometry']:
  4207. solid_geo.append(geo)
  4208. obj_init.solid_geometry = deepcopy(solid_geo)
  4209. if not self.collection.get_selected():
  4210. log.warning("App.convert_any2geo --> No object selected")
  4211. self.inform.emit('[WARNING_NOTCL] %s' %
  4212. _("No object is selected. Select an object and try again."))
  4213. return
  4214. for obj in self.collection.get_selected():
  4215. obj_name = obj.options["name"]
  4216. try:
  4217. if isinstance(obj, ExcellonObject):
  4218. self.app_obj.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  4219. else:
  4220. self.app_obj.new_object("geometry", str(obj_name) + "_conv", initialize)
  4221. except Exception as e:
  4222. return "Operation failed: %s" % str(e)
  4223. def convert_any2gerber(self):
  4224. """
  4225. Will convert any object out of Gerber, Excellon, Geometry to Gerber object.
  4226. :return:
  4227. """
  4228. self.defaults.report_usage("convert_any2gerber()")
  4229. def initialize_geometry(obj_init, app):
  4230. apertures = {}
  4231. apid = 0
  4232. apertures[str(apid)] = {}
  4233. apertures[str(apid)]['geometry'] = []
  4234. for obj_orig in obj.solid_geometry:
  4235. new_elem = {}
  4236. new_elem['solid'] = obj_orig
  4237. try:
  4238. new_elem['follow'] = obj_orig.exterior
  4239. except AttributeError:
  4240. pass
  4241. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  4242. apertures[str(apid)]['size'] = 0.0
  4243. apertures[str(apid)]['type'] = 'C'
  4244. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4245. obj_init.apertures = deepcopy(apertures)
  4246. def initialize_excellon(obj_init, app):
  4247. apertures = {}
  4248. apid = 10
  4249. for tool in obj.tools:
  4250. apertures[str(apid)] = {}
  4251. apertures[str(apid)]['geometry'] = []
  4252. for geo in obj.tools[tool]['solid_geometry']:
  4253. new_el = {}
  4254. new_el['solid'] = geo
  4255. new_el['follow'] = geo.exterior
  4256. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  4257. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  4258. apertures[str(apid)]['type'] = 'C'
  4259. apid += 1
  4260. # create solid_geometry
  4261. solid_geometry = []
  4262. for apid in apertures:
  4263. for geo_el in apertures[apid]['geometry']:
  4264. solid_geometry.append(geo_el['solid'])
  4265. solid_geometry = MultiPolygon(solid_geometry)
  4266. solid_geometry = solid_geometry.buffer(0.0000001)
  4267. obj_init.solid_geometry = deepcopy(solid_geometry)
  4268. obj_init.apertures = deepcopy(apertures)
  4269. # clear the working objects (perhaps not necessary due of Python GC)
  4270. apertures.clear()
  4271. if not self.collection.get_selected():
  4272. log.warning("App.convert_any2gerber --> No object selected")
  4273. self.inform.emit('[WARNING_NOTCL] %s' %
  4274. _("No object is selected. Select an object and try again."))
  4275. return
  4276. for obj in self.collection.get_selected():
  4277. obj_name = obj.options["name"]
  4278. try:
  4279. if isinstance(obj, ExcellonObject):
  4280. self.app_obj.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  4281. elif isinstance(obj, GeometryObject):
  4282. self.app_obj.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  4283. else:
  4284. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  4285. except Exception as e:
  4286. return "Operation failed: %s" % str(e)
  4287. def abort_all_tasks(self):
  4288. """
  4289. Executed when a certain key combo is pressed (Ctrl+Alt+X). Will abort current task
  4290. on the first possible occasion.
  4291. :return:
  4292. """
  4293. if self.abort_flag is False:
  4294. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  4295. self.abort_flag = True
  4296. self.cleanup.emit()
  4297. def app_is_idle(self):
  4298. if self.abort_flag:
  4299. self.inform.emit('[WARNING_NOTCL] %s' % _("The current task was gracefully closed on user request..."))
  4300. self.abort_flag = False
  4301. def on_selectall(self):
  4302. """
  4303. Will draw a selection box shape around the selected objects.
  4304. :return:
  4305. """
  4306. self.defaults.report_usage("on_selectall()")
  4307. # delete the possible selection box around a possible selected object
  4308. self.delete_selection_shape()
  4309. for name in self.collection.get_names():
  4310. self.collection.set_active(name)
  4311. curr_sel_obj = self.collection.get_by_name(name)
  4312. # create the selection box around the selected object
  4313. if self.defaults['global_selection_shape'] is True:
  4314. self.draw_selection_shape(curr_sel_obj)
  4315. def on_toggle_preferences(self):
  4316. pref_open = False
  4317. for idx in range(self.ui.plot_tab_area.count()):
  4318. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  4319. pref_open = True
  4320. if pref_open:
  4321. for idx in range(self.ui.plot_tab_area.count()):
  4322. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  4323. self.ui.plot_tab_area.removeTab(idx)
  4324. break
  4325. self.ui.pref_status_label.setStyleSheet("")
  4326. else:
  4327. self.on_preferences()
  4328. def on_preferences(self):
  4329. """
  4330. Adds the Preferences in a Tab in Plot Area
  4331. :return:
  4332. """
  4333. # add the tab if it was closed
  4334. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  4335. # delete the absolute and relative position and messages in the infobar
  4336. # self.ui.position_label.setText("")
  4337. # self.ui.rel_position_label.setText("")
  4338. # hide coordinates toolbars in the infobar while in DB
  4339. self.ui.coords_toolbar.hide()
  4340. self.ui.delta_coords_toolbar.hide()
  4341. # Switch plot_area to preferences page
  4342. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  4343. # self.ui.show()
  4344. self.ui.pref_status_label.setStyleSheet("""
  4345. QLabel
  4346. {
  4347. color: black;
  4348. background-color: lightseagreen;
  4349. }
  4350. """
  4351. )
  4352. # detect changes in the preferences
  4353. for idx in range(self.ui.pref_tab_area.count()):
  4354. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  4355. try:
  4356. try:
  4357. tb.textEdited.disconnect(self.preferencesUiManager.on_preferences_edited)
  4358. except (TypeError, AttributeError):
  4359. pass
  4360. tb.textEdited.connect(self.preferencesUiManager.on_preferences_edited)
  4361. except AttributeError:
  4362. pass
  4363. try:
  4364. try:
  4365. tb.modificationChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4366. except (TypeError, AttributeError):
  4367. pass
  4368. tb.modificationChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4369. except AttributeError:
  4370. pass
  4371. try:
  4372. try:
  4373. tb.toggled.disconnect(self.preferencesUiManager.on_preferences_edited)
  4374. except (TypeError, AttributeError):
  4375. pass
  4376. tb.toggled.connect(self.preferencesUiManager.on_preferences_edited)
  4377. except AttributeError:
  4378. pass
  4379. try:
  4380. try:
  4381. tb.valueChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4382. except (TypeError, AttributeError):
  4383. pass
  4384. tb.valueChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4385. except AttributeError:
  4386. pass
  4387. try:
  4388. try:
  4389. tb.currentIndexChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4390. except (TypeError, AttributeError):
  4391. pass
  4392. tb.currentIndexChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4393. except AttributeError:
  4394. pass
  4395. def on_tools_database(self, source='app'):
  4396. """
  4397. Adds the Tools Database in a Tab in Plot Area.
  4398. :return:
  4399. """
  4400. for idx in range(self.ui.plot_tab_area.count()):
  4401. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4402. # there can be only one instance of Tools Database at one time
  4403. return
  4404. if source == 'app':
  4405. self.tools_db_tab = ToolsDB2(
  4406. app=self,
  4407. parent=self.ui,
  4408. callback_on_edited=self.on_tools_db_edited,
  4409. callback_on_tool_request=self.on_geometry_tool_add_from_db_executed
  4410. )
  4411. elif source == 'ncc':
  4412. self.tools_db_tab = ToolsDB2(
  4413. app=self,
  4414. parent=self.ui,
  4415. callback_on_edited=self.on_tools_db_edited,
  4416. callback_on_tool_request=self.ncclear_tool.on_ncc_tool_add_from_db_executed
  4417. )
  4418. elif source == 'paint':
  4419. self.tools_db_tab = ToolsDB2(
  4420. app=self,
  4421. parent=self.ui,
  4422. callback_on_edited=self.on_tools_db_edited,
  4423. callback_on_tool_request=self.paint_tool.on_paint_tool_add_from_db_executed
  4424. )
  4425. elif source == 'iso':
  4426. self.tools_db_tab = ToolsDB2(
  4427. app=self,
  4428. parent=self.ui,
  4429. callback_on_edited=self.on_tools_db_edited,
  4430. callback_on_tool_request=self.isolation_tool.on_iso_tool_add_from_db_executed
  4431. )
  4432. # add the tab if it was closed
  4433. try:
  4434. self.ui.plot_tab_area.addTab(self.tools_db_tab, _("Tools Database"))
  4435. self.tools_db_tab.setObjectName("database_tab")
  4436. except Exception as e:
  4437. log.debug("App.on_tools_database() --> %s" % str(e))
  4438. return
  4439. # delete the absolute and relative position and messages in the infobar
  4440. # self.ui.position_label.setText("")
  4441. # self.ui.rel_position_label.setText("")
  4442. # hide coordinates toolbars in the infobar while in DB
  4443. self.ui.coords_toolbar.hide()
  4444. self.ui.delta_coords_toolbar.hide()
  4445. # Switch plot_area to preferences page
  4446. self.ui.plot_tab_area.setCurrentWidget(self.tools_db_tab)
  4447. # detect changes in the Tools in Tools DB, connect signals from table widget in tab
  4448. self.tools_db_tab.ui_connect()
  4449. def on_tools_db_edited(self):
  4450. """
  4451. Executed whenever a tool is edited in Tools Database.
  4452. Will color the text of the Tools Database tab to Red color.
  4453. :return:
  4454. """
  4455. self.inform[str, bool].emit('[WARNING_NOTCL] %s' % _("Tools in Tools Database edited but not saved."), False)
  4456. for idx in range(self.ui.plot_tab_area.count()):
  4457. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4458. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  4459. self.tools_db_tab.save_db_btn.setStyleSheet("QPushButton {color: red;}")
  4460. self.tools_db_changed_flag = True
  4461. def on_geometry_tool_add_from_db_executed(self, tool):
  4462. """
  4463. Here add the tool from DB in the selected geometry object.
  4464. :return:
  4465. """
  4466. tool_from_db = deepcopy(tool)
  4467. obj = self.collection.get_active()
  4468. if obj.kind == 'geometry':
  4469. obj.on_tool_from_db_inserted(tool=tool_from_db)
  4470. # close the tab and delete it
  4471. for idx in range(self.ui.plot_tab_area.count()):
  4472. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4473. wdg = self.ui.plot_tab_area.widget(idx)
  4474. wdg.deleteLater()
  4475. self.ui.plot_tab_area.removeTab(idx)
  4476. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4477. elif obj.kind == 'gerber':
  4478. self.isolation_tool.on_tool_from_db_inserted(tool=tool_from_db)
  4479. # close the tab and delete it
  4480. for idx in range(self.ui.plot_tab_area.count()):
  4481. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4482. wdg = self.ui.plot_tab_area.widget(idx)
  4483. wdg.deleteLater()
  4484. self.ui.plot_tab_area.removeTab(idx)
  4485. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4486. else:
  4487. self.inform.emit('[ERROR_NOTCL] %s' % _("Adding tool from DB is not allowed for this object."))
  4488. def on_plot_area_tab_closed(self, tab_obj_name):
  4489. """
  4490. Executed whenever a QTab is closed in the Plot Area.
  4491. :param tab_obj_name: The objectName of the Tab that was closed. This objectName is assigned on Tab creation
  4492. :return:
  4493. """
  4494. if tab_obj_name == "preferences_tab":
  4495. self.preferencesUiManager.on_close_preferences_tab()
  4496. elif tab_obj_name == "database_tab":
  4497. # disconnect the signals from the table widget in tab
  4498. self.tools_db_tab.ui_disconnect()
  4499. if self.tools_db_changed_flag is True:
  4500. msgbox = QtWidgets.QMessageBox()
  4501. msgbox.setText(_("One or more Tools are edited.\n"
  4502. "Do you want to update the Tools Database?"))
  4503. msgbox.setWindowTitle(_("Save Tools Database"))
  4504. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  4505. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  4506. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4507. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4508. msgbox.setDefaultButton(bt_yes)
  4509. msgbox.exec_()
  4510. response = msgbox.clickedButton()
  4511. if response == bt_yes:
  4512. self.tools_db_tab.on_save_tools_db()
  4513. self.inform.emit('[success] %s' % "Tools DB saved to file.")
  4514. else:
  4515. self.tools_db_changed_flag = False
  4516. self.inform.emit('')
  4517. return
  4518. self.tools_db_tab.deleteLater()
  4519. elif tab_obj_name == "text_editor_tab":
  4520. self.toggle_codeeditor = False
  4521. elif tab_obj_name == "bookmarks_tab":
  4522. self.book_dialog_tab.rebuild_actions()
  4523. self.book_dialog_tab.deleteLater()
  4524. else:
  4525. pass
  4526. # restore the coords toolbars
  4527. self.ui.toggle_coords(checked=self.defaults["global_coords_show"])
  4528. self.ui.toggle_delta_coords(checked=self.defaults["global_delta_coords_show"])
  4529. def on_flipy(self):
  4530. """
  4531. Executed when the menu entry in Options -> Flip on Y axis is clicked.
  4532. :return:
  4533. """
  4534. self.defaults.report_usage("on_flipy()")
  4535. obj_list = self.collection.get_selected()
  4536. xminlist = []
  4537. yminlist = []
  4538. xmaxlist = []
  4539. ymaxlist = []
  4540. if not obj_list:
  4541. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Flip on Y axis."))
  4542. else:
  4543. try:
  4544. # first get a bounding box to fit all
  4545. for obj in obj_list:
  4546. xmin, ymin, xmax, ymax = obj.bounds()
  4547. xminlist.append(xmin)
  4548. yminlist.append(ymin)
  4549. xmaxlist.append(xmax)
  4550. ymaxlist.append(ymax)
  4551. # get the minimum x,y and maximum x,y for all objects selected
  4552. xminimal = min(xminlist)
  4553. yminimal = min(yminlist)
  4554. xmaximal = max(xmaxlist)
  4555. ymaximal = max(ymaxlist)
  4556. px = 0.5 * (xminimal + xmaximal)
  4557. py = 0.5 * (yminimal + ymaximal)
  4558. # execute mirroring
  4559. for obj in obj_list:
  4560. obj.mirror('X', [px, py])
  4561. obj.plot()
  4562. self.app_obj.object_changed.emit(obj)
  4563. self.inform.emit('[success] %s' %
  4564. _("Flip on Y axis done."))
  4565. except Exception as e:
  4566. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4567. return
  4568. def on_flipx(self):
  4569. """
  4570. Executed when the menu entry in Options -> Flip on X axis is clicked.
  4571. :return:
  4572. """
  4573. self.defaults.report_usage("on_flipx()")
  4574. obj_list = self.collection.get_selected()
  4575. xminlist = []
  4576. yminlist = []
  4577. xmaxlist = []
  4578. ymaxlist = []
  4579. if not obj_list:
  4580. self.inform.emit('[WARNING_NOTCL] %s' %
  4581. _("No object selected to Flip on X axis."))
  4582. else:
  4583. try:
  4584. # first get a bounding box to fit all
  4585. for obj in obj_list:
  4586. xmin, ymin, xmax, ymax = obj.bounds()
  4587. xminlist.append(xmin)
  4588. yminlist.append(ymin)
  4589. xmaxlist.append(xmax)
  4590. ymaxlist.append(ymax)
  4591. # get the minimum x,y and maximum x,y for all objects selected
  4592. xminimal = min(xminlist)
  4593. yminimal = min(yminlist)
  4594. xmaximal = max(xmaxlist)
  4595. ymaximal = max(ymaxlist)
  4596. px = 0.5 * (xminimal + xmaximal)
  4597. py = 0.5 * (yminimal + ymaximal)
  4598. # execute mirroring
  4599. for obj in obj_list:
  4600. obj.mirror('Y', [px, py])
  4601. obj.plot()
  4602. self.app_obj.object_changed.emit(obj)
  4603. self.inform.emit('[success] %s' %
  4604. _("Flip on X axis done."))
  4605. except Exception as e:
  4606. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4607. return
  4608. def on_rotate(self, silent=False, preset=None):
  4609. """
  4610. Executed when Options -> Rotate Selection menu entry is clicked.
  4611. :param silent: If silent is True then use the preset value for the angle of the rotation.
  4612. :param preset: A value to be used as predefined angle for rotation.
  4613. :return:
  4614. """
  4615. self.defaults.report_usage("on_rotate()")
  4616. obj_list = self.collection.get_selected()
  4617. xminlist = []
  4618. yminlist = []
  4619. xmaxlist = []
  4620. ymaxlist = []
  4621. if not obj_list:
  4622. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Rotate."))
  4623. else:
  4624. if silent is False:
  4625. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4626. min=-360, max=360, decimals=4,
  4627. init_val=float(self.defaults['tools_transform_rotate']))
  4628. num, ok = rotatebox.get_value()
  4629. else:
  4630. num = preset
  4631. ok = True
  4632. if ok:
  4633. try:
  4634. # first get a bounding box to fit all
  4635. for obj in obj_list:
  4636. xmin, ymin, xmax, ymax = obj.bounds()
  4637. xminlist.append(xmin)
  4638. yminlist.append(ymin)
  4639. xmaxlist.append(xmax)
  4640. ymaxlist.append(ymax)
  4641. # get the minimum x,y and maximum x,y for all objects selected
  4642. xminimal = min(xminlist)
  4643. yminimal = min(yminlist)
  4644. xmaximal = max(xmaxlist)
  4645. ymaximal = max(ymaxlist)
  4646. px = 0.5 * (xminimal + xmaximal)
  4647. py = 0.5 * (yminimal + ymaximal)
  4648. for sel_obj in obj_list:
  4649. sel_obj.rotate(-float(num), point=(px, py))
  4650. sel_obj.plot()
  4651. self.app_obj.object_changed.emit(sel_obj)
  4652. self.inform.emit('[success] %s' % _("Rotation done."))
  4653. except Exception as e:
  4654. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Rotation movement was not executed."), str(e)))
  4655. return
  4656. def on_skewx(self):
  4657. """
  4658. Executed when the menu entry in Options -> Skew on X axis is clicked.
  4659. :return:
  4660. """
  4661. self.defaults.report_usage("on_skewx()")
  4662. obj_list = self.collection.get_selected()
  4663. xminlist = []
  4664. yminlist = []
  4665. if not obj_list:
  4666. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Skew/Shear on X axis."))
  4667. else:
  4668. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4669. min=-360, max=360, decimals=4,
  4670. init_val=float(self.defaults['tools_transform_skew_x']))
  4671. num, ok = skewxbox.get_value()
  4672. if ok:
  4673. # first get a bounding box to fit all
  4674. for obj in obj_list:
  4675. xmin, ymin, xmax, ymax = obj.bounds()
  4676. xminlist.append(xmin)
  4677. yminlist.append(ymin)
  4678. # get the minimum x,y and maximum x,y for all objects selected
  4679. xminimal = min(xminlist)
  4680. yminimal = min(yminlist)
  4681. for obj in obj_list:
  4682. obj.skew(num, 0, point=(xminimal, yminimal))
  4683. obj.plot()
  4684. self.app_obj.object_changed.emit(obj)
  4685. self.inform.emit('[success] %s' % _("Skew on X axis done."))
  4686. def on_skewy(self):
  4687. """
  4688. Executed when the menu entry in Options -> Skew on Y axis is clicked.
  4689. :return:
  4690. """
  4691. self.defaults.report_usage("on_skewy()")
  4692. obj_list = self.collection.get_selected()
  4693. xminlist = []
  4694. yminlist = []
  4695. if not obj_list:
  4696. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Skew/Shear on Y axis."))
  4697. else:
  4698. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4699. min=-360, max=360, decimals=4,
  4700. init_val=float(self.defaults['tools_transform_skew_y']))
  4701. num, ok = skewybox.get_value()
  4702. if ok:
  4703. # first get a bounding box to fit all
  4704. for obj in obj_list:
  4705. xmin, ymin, xmax, ymax = obj.bounds()
  4706. xminlist.append(xmin)
  4707. yminlist.append(ymin)
  4708. # get the minimum x,y and maximum x,y for all objects selected
  4709. xminimal = min(xminlist)
  4710. yminimal = min(yminlist)
  4711. for obj in obj_list:
  4712. obj.skew(0, num, point=(xminimal, yminimal))
  4713. obj.plot()
  4714. self.app_obj.object_changed.emit(obj)
  4715. self.inform.emit('[success] %s' % _("Skew on Y axis done."))
  4716. def on_plots_updated(self):
  4717. """
  4718. Callback used to report when the plots have changed.
  4719. Adjust axes and zooms to fit.
  4720. :return: None
  4721. """
  4722. if self.is_legacy is False:
  4723. self.plotcanvas.update()
  4724. else:
  4725. self.plotcanvas.auto_adjust_axes()
  4726. self.on_zoom_fit()
  4727. self.collection.update_view()
  4728. # self.inform.emit(_("Plots updated ..."))
  4729. def on_toolbar_replot(self):
  4730. """
  4731. Callback for toolbar button. Re-plots all objects.
  4732. :return: None
  4733. """
  4734. self.log.debug("on_toolbar_replot()")
  4735. try:
  4736. obj = self.collection.get_active()
  4737. if obj:
  4738. obj.read_form()
  4739. else:
  4740. self.on_zoom_fit()
  4741. except AttributeError as e:
  4742. log.debug("on_toolbar_replot() -> %s" % str(e))
  4743. pass
  4744. self.plot_all()
  4745. def grid_status(self):
  4746. return True if self.ui.grid_snap_btn.isChecked() else False
  4747. def populate_cmenu_grids(self):
  4748. units = self.defaults['units'].lower()
  4749. # for act in self.ui.cmenu_gridmenu.actions():
  4750. # act.triggered.disconnect()
  4751. self.ui.cmenu_gridmenu.clear()
  4752. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  4753. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  4754. _("Grid On/Off"))
  4755. grid_toggle.setCheckable(True)
  4756. grid_toggle.setChecked(True) if self.grid_status() else grid_toggle.setChecked(False)
  4757. self.ui.cmenu_gridmenu.addSeparator()
  4758. for grid in sorted_list:
  4759. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  4760. "%s" % str(grid))
  4761. action.triggered.connect(self.set_grid)
  4762. self.ui.cmenu_gridmenu.addSeparator()
  4763. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/plus32.png'),
  4764. _("Add"))
  4765. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/delete32.png'),
  4766. _("Delete"))
  4767. grid_add.triggered.connect(self.on_grid_add)
  4768. grid_delete.triggered.connect(self.on_grid_delete)
  4769. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  4770. def set_grid(self):
  4771. menu_action = self.sender()
  4772. assert isinstance(menu_action, QtWidgets.QAction), "Expected QAction got %s" % type(menu_action)
  4773. self.ui.grid_gap_x_entry.setText(menu_action.text())
  4774. self.ui.grid_gap_y_entry.setText(menu_action.text())
  4775. def on_grid_add(self):
  4776. # ## Current application units in lower Case
  4777. units = self.defaults['units'].lower()
  4778. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  4779. text=_('Enter a Grid Value:'),
  4780. min=0.0000, max=99.9999, decimals=4)
  4781. grid_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/plus32.png'))
  4782. val, ok = grid_add_popup.get_value()
  4783. if ok:
  4784. if float(val) == 0:
  4785. self.inform.emit('[WARNING_NOTCL] %s' %
  4786. _("Please enter a grid value with non-zero value, in Float format."))
  4787. return
  4788. else:
  4789. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  4790. self.defaults["global_grid_context_menu"][str(units)].append(val)
  4791. self.inform.emit('[success] %s...' % _("New Grid added"))
  4792. else:
  4793. self.inform.emit('[WARNING_NOTCL] %s...' % _("Grid already exists"))
  4794. else:
  4795. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding New Grid cancelled"))
  4796. def on_grid_delete(self):
  4797. # ## Current application units in lower Case
  4798. units = self.defaults['units'].lower()
  4799. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  4800. text='Enter a Grid Value:',
  4801. min=0.0000, max=99.9999, decimals=4)
  4802. grid_del_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/delete32.png'))
  4803. val, ok = grid_del_popup.get_value()
  4804. if ok:
  4805. if float(val) == 0:
  4806. self.inform.emit('[WARNING_NOTCL] %s' %
  4807. _("Please enter a grid value with non-zero value, in Float format."))
  4808. return
  4809. else:
  4810. try:
  4811. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  4812. except ValueError:
  4813. self.inform.emit('[ERROR_NOTCL]%s...' % _(" Grid Value does not exist"))
  4814. return
  4815. self.inform.emit('[success] %s...' % _("Grid Value deleted"))
  4816. else:
  4817. self.inform.emit('[WARNING_NOTCL] %s...' % _("Delete Grid value cancelled"))
  4818. def on_shortcut_list(self):
  4819. self.defaults.report_usage("on_shortcut_list()")
  4820. # add the tab if it was closed
  4821. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  4822. # delete the absolute and relative position and messages in the infobar
  4823. # self.ui.position_label.setText("")
  4824. # self.ui.rel_position_label.setText("")
  4825. # hide coordinates toolbars in the infobar while in DB
  4826. self.ui.coords_toolbar.hide()
  4827. self.ui.delta_coords_toolbar.hide()
  4828. # Switch plot_area to preferences page
  4829. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  4830. # self.ui.show()
  4831. def on_select_tab(self, name):
  4832. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  4833. if self.ui.splitter.sizes()[0] == 0:
  4834. self.ui.splitter.setSizes([1, 1])
  4835. else:
  4836. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  4837. self.ui.splitter.setSizes([0, 1])
  4838. if name == 'project':
  4839. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  4840. elif name == 'selected':
  4841. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  4842. elif name == 'tool':
  4843. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  4844. def on_copy_name(self):
  4845. self.defaults.report_usage("on_copy_name()")
  4846. obj = self.collection.get_active()
  4847. try:
  4848. name = obj.options["name"]
  4849. except AttributeError:
  4850. log.debug("on_copy_name() --> No object selected to copy it's name")
  4851. self.inform.emit('[WARNING_NOTCL] %s' %
  4852. _(" No object selected to copy it's name"))
  4853. return
  4854. self.clipboard.setText(name)
  4855. self.inform.emit(_("Name copied on clipboard ..."))
  4856. def on_mouse_click_over_plot(self, event):
  4857. """
  4858. Default actions are:
  4859. :param event: Contains information about the event, like which button
  4860. was clicked, the pixel coordinates and the axes coordinates.
  4861. :return: None
  4862. """
  4863. self.pos = []
  4864. if self.is_legacy is False:
  4865. event_pos = event.pos
  4866. # pan_button = 2 if self.defaults["global_pan_button"] == '2'else 3
  4867. # # Set the mouse button for panning
  4868. # self.plotcanvas.view.camera.pan_button_setting = pan_button
  4869. else:
  4870. event_pos = (event.xdata, event.ydata)
  4871. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  4872. # pan_button = 3 if self.defaults["global_pan_button"] == '2' else 2
  4873. # So it can receive key presses
  4874. self.plotcanvas.native.setFocus()
  4875. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  4876. if self.grid_status():
  4877. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  4878. else:
  4879. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  4880. try:
  4881. if event.button == 1:
  4882. # Reset here the relative coordinates so there is a new reference on the click position
  4883. if self.rel_point1 is None:
  4884. self.rel_point1 = self.pos
  4885. else:
  4886. self.rel_point2 = copy(self.rel_point1)
  4887. self.rel_point1 = self.pos
  4888. self.on_mouse_move_over_plot(event, origin_click=True)
  4889. except Exception as e:
  4890. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  4891. def on_mouse_double_click_over_plot(self, event):
  4892. if event.button == 1:
  4893. self.doubleclick = True
  4894. def on_mouse_move_over_plot(self, event, origin_click=None):
  4895. """
  4896. Callback for the mouse motion event over the plot.
  4897. :param event: Contains information about the event.
  4898. :param origin_click
  4899. :return: None
  4900. """
  4901. if self.is_legacy is False:
  4902. event_pos = event.pos
  4903. if self.defaults["global_pan_button"] == '2':
  4904. pan_button = 2
  4905. else:
  4906. pan_button = 3
  4907. self.event_is_dragging = event.is_dragging
  4908. else:
  4909. event_pos = (event.xdata, event.ydata)
  4910. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  4911. if self.defaults["global_pan_button"] == '2':
  4912. pan_button = 3
  4913. else:
  4914. pan_button = 2
  4915. self.event_is_dragging = self.plotcanvas.is_dragging
  4916. # So it can receive key presses but not when the Tcl Shell is active
  4917. if not self.ui.shell_dock.isVisible():
  4918. if not self.plotcanvas.native.hasFocus():
  4919. self.plotcanvas.native.setFocus()
  4920. self.pos_jump = event_pos
  4921. self.ui.popMenu.mouse_is_panning = False
  4922. if origin_click is None:
  4923. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  4924. if event.button == pan_button and self.event_is_dragging == 1:
  4925. # if a popup menu is active don't change mouse_is_panning variable because is not True
  4926. if self.ui.popMenu.popup_active:
  4927. self.ui.popMenu.popup_active = False
  4928. return
  4929. self.ui.popMenu.mouse_is_panning = True
  4930. return
  4931. if self.rel_point1 is not None:
  4932. try: # May fail in case mouse not within axes
  4933. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  4934. if pos_canvas[0] is None or pos_canvas[1] is None:
  4935. return
  4936. if self.grid_status():
  4937. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4938. # Update cursor
  4939. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  4940. symbol='++', edge_color=self.cursor_color_3D,
  4941. edge_width=self.defaults["global_cursor_width"],
  4942. size=self.defaults["global_cursor_size"])
  4943. else:
  4944. pos = (pos_canvas[0], pos_canvas[1])
  4945. self.dx = pos[0] - float(self.rel_point1[0])
  4946. self.dy = pos[1] - float(self.rel_point1[1])
  4947. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4948. "<b>Y</b>: %.4f&nbsp;" % (pos[0], pos[1]))
  4949. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4950. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  4951. units = self.defaults["units"].lower()
  4952. self.plotcanvas.text_hud.text = \
  4953. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  4954. self.dx, units, self.dy, units, pos[0], units, pos[1], units)
  4955. self.mouse = [pos[0], pos[1]]
  4956. if self.defaults['global_selection_shape'] is False:
  4957. self.selection_type = None
  4958. return
  4959. # if the mouse is moved and the LMB is clicked then the action is a selection
  4960. if self.event_is_dragging == 1 and event.button == 1:
  4961. self.delete_selection_shape()
  4962. if self.dx < 0:
  4963. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  4964. face_color=self.defaults['global_alt_sel_fill'])
  4965. self.selection_type = False
  4966. elif self.dx >= 0:
  4967. self.draw_moving_selection_shape(self.pos, pos)
  4968. self.selection_type = True
  4969. else:
  4970. self.selection_type = None
  4971. else:
  4972. self.selection_type = None
  4973. # hover effect - enabled in Preferences -> General -> appGUI Settings
  4974. if self.defaults['global_hover']:
  4975. for obj in self.collection.get_list():
  4976. try:
  4977. # select the object(s) only if it is enabled (plotted)
  4978. if obj.options['plot']:
  4979. if obj not in self.collection.get_selected():
  4980. poly_obj = Polygon(
  4981. [(obj.options['xmin'], obj.options['ymin']),
  4982. (obj.options['xmax'], obj.options['ymin']),
  4983. (obj.options['xmax'], obj.options['ymax']),
  4984. (obj.options['xmin'], obj.options['ymax'])]
  4985. )
  4986. if Point(pos).within(poly_obj):
  4987. if obj.isHovering is False:
  4988. obj.isHovering = True
  4989. obj.notHovering = True
  4990. # create the selection box around the selected object
  4991. self.draw_hover_shape(obj, color='#d1e0e0FF')
  4992. else:
  4993. if obj.notHovering is True:
  4994. obj.notHovering = False
  4995. obj.isHovering = False
  4996. self.delete_hover_shape()
  4997. except Exception:
  4998. # the Exception here will happen if we try to select on screen and we have an
  4999. # newly (and empty) just created Geometry or Excellon object that do not have the
  5000. # xmin, xmax, ymin, ymax options.
  5001. # In this case poly_obj creation (see above) will fail
  5002. pass
  5003. except Exception as e:
  5004. log.debug("App.on_mouse_move_over_plot() - rel_point1 is not None -> %s" % str(e))
  5005. self.ui.position_label.setText("")
  5006. self.ui.rel_position_label.setText("")
  5007. self.mouse = None
  5008. def on_mouse_click_release_over_plot(self, event):
  5009. """
  5010. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  5011. and has been registered in ''self.__init__()''.
  5012. :param event: contains information about the event.
  5013. :return:
  5014. """
  5015. if self.is_legacy is False:
  5016. event_pos = event.pos
  5017. right_button = 2
  5018. else:
  5019. event_pos = (event.xdata, event.ydata)
  5020. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5021. right_button = 3
  5022. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5023. if self.grid_status():
  5024. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5025. else:
  5026. pos = (pos_canvas[0], pos_canvas[1])
  5027. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  5028. # canvas menu
  5029. if event.button == right_button and self.ui.popMenu.mouse_is_panning is False: # right click
  5030. self.ui.popMenu.mouse_is_panning = False
  5031. self.cursor = QtGui.QCursor()
  5032. self.populate_cmenu_grids()
  5033. self.ui.popMenu.popup(self.cursor.pos())
  5034. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  5035. # selection and then select a type of selection ("enclosing" or "touching")
  5036. if event.button == 1: # left click
  5037. modifiers = QtWidgets.QApplication.keyboardModifiers()
  5038. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  5039. if modifiers == QtCore.Qt.ShiftModifier:
  5040. # do not auto open the Project Tab
  5041. self.click_noproject = True
  5042. self.clipboard.setText(
  5043. self.defaults["global_point_clipboard_format"] %
  5044. (self.decimals, self.pos[0], self.decimals, self.pos[1])
  5045. )
  5046. self.inform.emit('[success] %s' % _("Coordinates copied to clipboard."))
  5047. return
  5048. if self.doubleclick is True:
  5049. self.doubleclick = False
  5050. if self.collection.get_selected():
  5051. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5052. if self.ui.splitter.sizes()[0] == 0:
  5053. self.ui.splitter.setSizes([1, 1])
  5054. try:
  5055. # delete the selection shape(S) as it may be in the way
  5056. self.delete_selection_shape()
  5057. self.delete_hover_shape()
  5058. except Exception as e:
  5059. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() double click --> Error: %s" % str(e))
  5060. return
  5061. else:
  5062. # WORKAROUND for LEGACY MODE
  5063. if self.is_legacy is True:
  5064. # if there is no move on canvas then we have no dragging selection
  5065. if self.dx == 0 or self.dy == 0:
  5066. self.selection_type = None
  5067. if self.selection_type is not None:
  5068. try:
  5069. self.selection_area_handler(self.pos, pos, self.selection_type)
  5070. self.selection_type = None
  5071. except Exception as e:
  5072. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select area --> Error: %s" % str(e))
  5073. return
  5074. else:
  5075. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  5076. if key_modifier == QtCore.Qt.ShiftModifier:
  5077. mod_key = 'Shift'
  5078. elif key_modifier == QtCore.Qt.ControlModifier:
  5079. mod_key = 'Control'
  5080. else:
  5081. mod_key = None
  5082. try:
  5083. if self.command_active is None:
  5084. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  5085. # deselect, and if it's not selected then it will be selected
  5086. # If there is no active command (self.command_active is None) then we check if we clicked
  5087. # on a object by checking the bounding limits against mouse click position
  5088. if mod_key == self.defaults["global_mselect_key"]:
  5089. self.select_objects(key='multisel')
  5090. else:
  5091. # If there is no active command (self.command_active is None) then we check if
  5092. # we clicked on a object by checking the bounding limits against mouse click position
  5093. self.select_objects()
  5094. self.delete_hover_shape()
  5095. except Exception as e:
  5096. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select click --> Error: %s" % str(e))
  5097. return
  5098. def selection_area_handler(self, start_pos, end_pos, sel_type):
  5099. """
  5100. :param start_pos: mouse position when the selection LMB click was done
  5101. :param end_pos: mouse position when the left mouse button is released
  5102. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  5103. :return:
  5104. """
  5105. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  5106. # delete previous selection shape
  5107. self.delete_selection_shape()
  5108. # make all objects inactive
  5109. self.collection.set_all_inactive()
  5110. for obj in self.collection.get_list():
  5111. try:
  5112. # select the object(s) only if it is enabled (plotted)
  5113. if obj.options['plot']:
  5114. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  5115. (obj.options['xmax'], obj.options['ymin']),
  5116. (obj.options['xmax'], obj.options['ymax']),
  5117. (obj.options['xmin'], obj.options['ymax'])])
  5118. if sel_type is True:
  5119. if poly_obj.within(poly_selection):
  5120. # create the selection box around the selected object
  5121. if self.defaults['global_selection_shape'] is True:
  5122. self.draw_selection_shape(obj)
  5123. self.collection.set_active(obj.options['name'])
  5124. else:
  5125. if poly_selection.intersects(poly_obj):
  5126. # create the selection box around the selected object
  5127. if self.defaults['global_selection_shape'] is True:
  5128. self.draw_selection_shape(obj)
  5129. self.collection.set_active(obj.options['name'])
  5130. obj.selection_shape_drawn = True
  5131. except Exception as e:
  5132. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  5133. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  5134. # In this case poly_obj creation (see above) will fail
  5135. log.debug("App.selection_area_handler() --> %s" % str(e))
  5136. def select_objects(self, key=None):
  5137. """
  5138. Will select objects clicked on canvas
  5139. :param key: for future use in cumulative selection
  5140. :return:
  5141. """
  5142. # list where we store the overlapped objects under our mouse left click position
  5143. if key is None:
  5144. self.objects_under_the_click_list = []
  5145. # Populate the list with the overlapped objects on the click position
  5146. curr_x, curr_y = self.pos
  5147. for obj in self.all_objects_list:
  5148. # ScriptObject and DocumentObject objects can't be selected
  5149. if obj.kind == 'script' or obj.kind == 'document':
  5150. continue
  5151. if key == 'multisel' and obj.options['name'] in self.objects_under_the_click_list:
  5152. continue
  5153. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  5154. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  5155. if obj.options['name'] not in self.objects_under_the_click_list:
  5156. if obj.options['plot']:
  5157. # add objects to the objects_under_the_click list only if the object is plotted
  5158. # (active and not disabled)
  5159. self.objects_under_the_click_list.append(obj.options['name'])
  5160. try:
  5161. if self.objects_under_the_click_list:
  5162. curr_sel_obj = self.collection.get_active()
  5163. # case when there is only an object under the click and we toggle it
  5164. if len(self.objects_under_the_click_list) == 1:
  5165. if curr_sel_obj is None:
  5166. self.collection.set_active(self.objects_under_the_click_list[0])
  5167. curr_sel_obj = self.collection.get_active()
  5168. # create the selection box around the selected object
  5169. if self.defaults['global_selection_shape'] is True:
  5170. self.draw_selection_shape(curr_sel_obj)
  5171. curr_sel_obj.selection_shape_drawn = True
  5172. elif curr_sel_obj.options['name'] not in self.objects_under_the_click_list:
  5173. self.collection.on_objects_selection(False)
  5174. self.delete_selection_shape()
  5175. curr_sel_obj.selection_shape_drawn = False
  5176. self.collection.set_active(self.objects_under_the_click_list[0])
  5177. curr_sel_obj = self.collection.get_active()
  5178. # create the selection box around the selected object
  5179. if self.defaults['global_selection_shape'] is True:
  5180. self.draw_selection_shape(curr_sel_obj)
  5181. curr_sel_obj.selection_shape_drawn = True
  5182. self.selected_message(curr_sel_obj=curr_sel_obj)
  5183. elif curr_sel_obj.selection_shape_drawn is False:
  5184. if self.defaults['global_selection_shape'] is True:
  5185. self.draw_selection_shape(curr_sel_obj)
  5186. curr_sel_obj.selection_shape_drawn = True
  5187. else:
  5188. self.collection.on_objects_selection(False)
  5189. self.delete_selection_shape()
  5190. if self.call_source != 'app':
  5191. self.call_source = 'app'
  5192. self.selected_message(curr_sel_obj=curr_sel_obj)
  5193. else:
  5194. # If there is no selected object
  5195. # make active the first element of the overlapped objects list
  5196. if self.collection.get_active() is None:
  5197. self.collection.set_active(self.objects_under_the_click_list[0])
  5198. self.collection.get_by_name(self.objects_under_the_click_list[0]).selection_shape_drawn = True
  5199. name_sel_obj = self.collection.get_active().options['name']
  5200. # In case that there is a selected object but it is not in the overlapped object list
  5201. # make that object inactive and activate the first element in the overlapped object list
  5202. if name_sel_obj not in self.objects_under_the_click_list:
  5203. self.collection.set_inactive(name_sel_obj)
  5204. name_sel_obj = self.objects_under_the_click_list[0]
  5205. self.collection.set_active(name_sel_obj)
  5206. else:
  5207. sel_idx = self.objects_under_the_click_list.index(name_sel_obj)
  5208. self.collection.set_all_inactive()
  5209. self.collection.set_active(
  5210. self.objects_under_the_click_list[(sel_idx + 1) % len(self.objects_under_the_click_list)])
  5211. curr_sel_obj = self.collection.get_active()
  5212. # delete the possible selection box around a possible selected object
  5213. self.delete_selection_shape()
  5214. curr_sel_obj.selection_shape_drawn = False
  5215. # create the selection box around the selected object
  5216. if self.defaults['global_selection_shape'] is True:
  5217. self.draw_selection_shape(curr_sel_obj)
  5218. curr_sel_obj.selection_shape_drawn = True
  5219. self.selected_message(curr_sel_obj=curr_sel_obj)
  5220. else:
  5221. # deselect everything
  5222. self.collection.on_objects_selection(False)
  5223. # delete the possible selection box around a possible selected object
  5224. self.delete_selection_shape()
  5225. for o in self.collection.get_list():
  5226. o.selection_shape_drawn = False
  5227. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  5228. # only when working on App
  5229. if self.call_source == 'app':
  5230. if self.click_noproject is False:
  5231. # if the Tool Tab is in focus don't change focus to Project Tab
  5232. if not self.ui.notebook.currentWidget() is self.ui.tool_tab:
  5233. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5234. else:
  5235. # restore auto open the Project Tab
  5236. self.click_noproject = False
  5237. # delete any text in the status bar, implicitly the last object name that was selected
  5238. # self.inform.emit("")
  5239. else:
  5240. self.call_source = 'app'
  5241. except Exception as e:
  5242. log.error("[ERROR] Something went bad in App.select_objects(). %s" % str(e))
  5243. def selected_message(self, curr_sel_obj):
  5244. if curr_sel_obj:
  5245. if curr_sel_obj.kind == 'gerber':
  5246. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5247. color='green',
  5248. name=str(curr_sel_obj.options['name']),
  5249. tx=_("selected"))
  5250. )
  5251. elif curr_sel_obj.kind == 'excellon':
  5252. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5253. color='brown',
  5254. name=str(curr_sel_obj.options['name']),
  5255. tx=_("selected"))
  5256. )
  5257. elif curr_sel_obj.kind == 'cncjob':
  5258. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5259. color='blue',
  5260. name=str(curr_sel_obj.options['name']),
  5261. tx=_("selected"))
  5262. )
  5263. elif curr_sel_obj.kind == 'geometry':
  5264. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5265. color='red',
  5266. name=str(curr_sel_obj.options['name']),
  5267. tx=_("selected"))
  5268. )
  5269. def delete_hover_shape(self):
  5270. self.hover_shapes.clear()
  5271. self.hover_shapes.redraw()
  5272. def draw_hover_shape(self, sel_obj, color=None):
  5273. """
  5274. :param sel_obj: The object for which the hover shape must be drawn
  5275. :param color: The color of the hover shape
  5276. :return: None
  5277. """
  5278. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5279. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5280. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5281. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5282. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  5283. if self.defaults['units'].upper() == 'MM':
  5284. hover_rect = hover_rect.buffer(-0.1)
  5285. hover_rect = hover_rect.buffer(0.2)
  5286. else:
  5287. hover_rect = hover_rect.buffer(-0.00393)
  5288. hover_rect = hover_rect.buffer(0.00787)
  5289. # if color:
  5290. # face = Color(color)
  5291. # face.alpha = 0.2
  5292. # outline = Color(color, alpha=0.8)
  5293. # else:
  5294. # face = Color(self.defaults['global_sel_fill'])
  5295. # face.alpha = 0.2
  5296. # outline = self.defaults['global_sel_line']
  5297. if color:
  5298. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5299. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5300. else:
  5301. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5302. outline = self.defaults['global_sel_line']
  5303. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  5304. if self.is_legacy is True:
  5305. self.hover_shapes.redraw()
  5306. def delete_selection_shape(self):
  5307. self.move_tool.sel_shapes.clear()
  5308. self.move_tool.sel_shapes.redraw()
  5309. def draw_selection_shape(self, sel_obj, color=None):
  5310. """
  5311. Will draw a selection shape around the selected object.
  5312. :param sel_obj: The object for which the selection shape must be drawn
  5313. :param color: The color for the selection shape.
  5314. :return: None
  5315. """
  5316. if sel_obj is None:
  5317. return
  5318. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5319. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5320. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5321. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5322. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5323. if self.defaults['units'].upper() == 'MM':
  5324. sel_rect = sel_rect.buffer(-0.1)
  5325. sel_rect = sel_rect.buffer(0.2)
  5326. else:
  5327. sel_rect = sel_rect.buffer(-0.00393)
  5328. sel_rect = sel_rect.buffer(0.00787)
  5329. if color:
  5330. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5331. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5332. else:
  5333. if self.is_legacy is False:
  5334. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5335. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  5336. else:
  5337. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  5338. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  5339. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  5340. color=outline,
  5341. face_color=face,
  5342. update=True,
  5343. layer=0,
  5344. tolerance=None))
  5345. if self.is_legacy is True:
  5346. self.move_tool.sel_shapes.redraw()
  5347. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  5348. """
  5349. Will draw a selection shape when dragging mouse on canvas.
  5350. :param old_coords: Old coordinates
  5351. :param coords: New coordinates
  5352. :param kwargs: Keyword arguments
  5353. :return:
  5354. """
  5355. if 'color' in kwargs:
  5356. color = kwargs['color']
  5357. else:
  5358. color = self.defaults['global_sel_line']
  5359. if 'face_color' in kwargs:
  5360. face_color = kwargs['face_color']
  5361. else:
  5362. face_color = self.defaults['global_sel_fill']
  5363. if 'face_alpha' in kwargs:
  5364. face_alpha = kwargs['face_alpha']
  5365. else:
  5366. face_alpha = 0.3
  5367. x0, y0 = old_coords
  5368. x1, y1 = coords
  5369. pt1 = (x0, y0)
  5370. pt2 = (x1, y0)
  5371. pt3 = (x1, y1)
  5372. pt4 = (x0, y1)
  5373. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5374. # color_t = Color(face_color)
  5375. # color_t.alpha = face_alpha
  5376. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  5377. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  5378. layer=0, tolerance=None)
  5379. if self.is_legacy is True:
  5380. self.move_tool.sel_shapes.redraw()
  5381. def on_file_new_click(self):
  5382. """
  5383. Callback for menu item File -> New.
  5384. Executed on clicking the Menu -> File -> New Project
  5385. :return:
  5386. """
  5387. if self.collection.get_list() and self.should_we_save:
  5388. msgbox = QtWidgets.QMessageBox()
  5389. # msgbox.setText("<B>Save changes ...</B>")
  5390. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  5391. "Creating a New project will delete them.\n"
  5392. "Do you want to Save the project?"))
  5393. msgbox.setWindowTitle(_("Save changes"))
  5394. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  5395. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  5396. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  5397. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  5398. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  5399. msgbox.setDefaultButton(bt_yes)
  5400. msgbox.exec_()
  5401. response = msgbox.clickedButton()
  5402. if response == bt_yes:
  5403. self.on_file_saveprojectas()
  5404. elif response == bt_cancel:
  5405. return
  5406. elif response == bt_no:
  5407. self.on_file_new()
  5408. else:
  5409. self.on_file_new()
  5410. self.inform.emit('[success] %s...' % _("New Project created"))
  5411. def on_file_new(self, cli=None):
  5412. """
  5413. Returns the application to its startup state. This method is thread-safe.
  5414. :param cli: Boolean. If True this method was run from command line
  5415. :return: None
  5416. """
  5417. self.defaults.report_usage("on_file_new")
  5418. # Remove everything from memory
  5419. App.log.debug("on_file_new()")
  5420. # close any editor that might be open
  5421. if self.call_source != 'app':
  5422. self.editor2object(cleanup=True)
  5423. # ## EDITOR section
  5424. self.geo_editor = AppGeoEditor(self)
  5425. self.exc_editor = AppExcEditor(self)
  5426. self.grb_editor = AppGerberEditor(self)
  5427. # Clear pool
  5428. self.clear_pool()
  5429. for obj in self.collection.get_list():
  5430. # delete shapes left drawn from mark shape_collections, if any
  5431. if isinstance(obj, GerberObject):
  5432. try:
  5433. for el in obj.mark_shapes:
  5434. obj.mark_shapes[el].clear(update=True)
  5435. obj.mark_shapes[el].enabled = False
  5436. del el
  5437. except AttributeError:
  5438. pass
  5439. # also delete annotation shapes, if any
  5440. elif isinstance(obj, CNCJobObject):
  5441. try:
  5442. obj.text_col.enabled = False
  5443. del obj.text_col
  5444. obj.annotation.clear(update=True)
  5445. del obj.annotation
  5446. except AttributeError:
  5447. pass
  5448. # delete the exclusion areas
  5449. self.exc_areas.clear_shapes()
  5450. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  5451. self.shell.init_tcl()
  5452. # delete any selection shape on canvas
  5453. self.delete_selection_shape()
  5454. # delete all FlatCAM objects
  5455. self.collection.delete_all()
  5456. # add in Selected tab an initial text that describe the flow of work in FlatCAm
  5457. self.setup_component_editor()
  5458. # Clear project filename
  5459. self.project_filename = None
  5460. # Load the application defaults
  5461. self.defaults.load(filename=os.path.join(self.data_path, 'current_defaults.FlatConfig'))
  5462. # Re-fresh project options
  5463. self.on_options_app2project()
  5464. # Init FlatCAMTools
  5465. self.init_tools()
  5466. # Try to close all tabs in the PlotArea but only if the appGUI is active (CLI is None)
  5467. if cli is None:
  5468. # we need to go in reverse because once we remove a tab then the index changes
  5469. # meaning that removing the first tab (idx = 0) then the tab at former idx = 1 will assume idx = 0
  5470. # and so on. Therefore the deletion should be done in reverse
  5471. wdg_count = self.ui.plot_tab_area.tabBar.count() - 1
  5472. for index in range(wdg_count, -1, -1):
  5473. try:
  5474. self.ui.plot_tab_area.closeTab(index)
  5475. except Exception as e:
  5476. log.debug("App.on_file_new() --> %s" % str(e))
  5477. # # And then add again the Plot Area
  5478. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  5479. self.ui.plot_tab_area.protectTab(0)
  5480. # take the focus of the Notebook on Project Tab.
  5481. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5482. self.set_ui_title(name=_("New Project - Not saved"))
  5483. def obj_properties(self):
  5484. """
  5485. Will launch the object Properties Tool
  5486. :return:
  5487. """
  5488. self.defaults.report_usage("obj_properties()")
  5489. self.properties_tool.run(toggle=False)
  5490. def on_project_context_save(self):
  5491. """
  5492. Wrapper, will save the object function of it's type
  5493. :return:
  5494. """
  5495. sel_objects = self.collection.get_selected()
  5496. len_objects = len(sel_objects)
  5497. cnt = 0
  5498. if len_objects > 1:
  5499. for o in sel_objects:
  5500. if o.kind == 'cncjob':
  5501. cnt += 1
  5502. if len_objects == cnt:
  5503. # all selected objects are of type CNCJOB therefore we issue a multiple save
  5504. _filter_ = self.defaults['cncjob_save_filters'] + \
  5505. ";;RML1 Files .rol (*.rol);;HPGL Files .plt (*.plt)"
  5506. dir_file_to_save = self.get_last_save_folder() + '/multi_save'
  5507. try:
  5508. filename, _f = FCFileSaveDialog.get_saved_filename(
  5509. caption=_("Export Code ..."),
  5510. directory=dir_file_to_save,
  5511. ext_filter=_filter_
  5512. )
  5513. except TypeError:
  5514. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Code ..."),
  5515. ext_filter=_filter_)
  5516. filename = filename.rpartition('/')[0]
  5517. for ob in sel_objects:
  5518. ob.read_form()
  5519. fname = '%s/%s' % (filename, ob.options['name'])
  5520. ob.export_gcode_handler(fname, is_gcode=True)
  5521. return
  5522. obj = self.collection.get_active()
  5523. if type(obj) == GeometryObject:
  5524. self.on_file_exportdxf()
  5525. elif type(obj) == ExcellonObject:
  5526. self.on_file_saveexcellon()
  5527. elif type(obj) == CNCJobObject:
  5528. obj.on_exportgcode_button_click()
  5529. elif type(obj) == GerberObject:
  5530. self.on_file_savegerber()
  5531. elif type(obj) == ScriptObject:
  5532. self.on_file_savescript()
  5533. elif type(obj) == DocumentObject:
  5534. self.on_file_savedocument()
  5535. def obj_move(self):
  5536. """
  5537. Callback for the Move menu entry in various Context Menu's.
  5538. :return:
  5539. """
  5540. self.defaults.report_usage("obj_move()")
  5541. self.move_tool.run(toggle=False)
  5542. def on_fileopengerber(self, signal, name=None):
  5543. """
  5544. File menu callback for opening a Gerber.
  5545. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5546. :param name:
  5547. :return: None
  5548. """
  5549. self.defaults.report_usage("on_fileopengerber")
  5550. App.log.debug("on_fileopengerber()")
  5551. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 " \
  5552. "*.gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb " \
  5553. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd *.outline);;" \
  5554. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko " \
  5555. "*.outline);;" \
  5556. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  5557. "*.mil);;" \
  5558. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  5559. "Allegro Files (*.art);;" \
  5560. "Mentor Files (*.pho *.gdo);;" \
  5561. "All Files (*.*)"
  5562. if name is None:
  5563. try:
  5564. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  5565. directory=self.get_last_folder(),
  5566. filter=_filter_,
  5567. initialFilter=self.last_op_gerber_filter)
  5568. except TypeError:
  5569. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  5570. filenames = [str(filename) for filename in filenames]
  5571. self.last_op_gerber_filter = _f
  5572. else:
  5573. filenames = [name]
  5574. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5575. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5576. _("Opening Gerber file.")),
  5577. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5578. color=QtGui.QColor("gray"))
  5579. if len(filenames) == 0:
  5580. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5581. else:
  5582. for filename in filenames:
  5583. if filename != '':
  5584. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  5585. def on_fileopenexcellon(self, signal, name=None):
  5586. """
  5587. File menu callback for opening an Excellon file.
  5588. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5589. :param name:
  5590. :return: None
  5591. """
  5592. self.defaults.report_usage("on_fileopenexcellon")
  5593. App.log.debug("on_fileopenexcellon()")
  5594. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  5595. "All Files (*.*)"
  5596. if name is None:
  5597. try:
  5598. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  5599. directory=self.get_last_folder(),
  5600. filter=_filter_,
  5601. initialFilter=self.last_op_excellon_filter)
  5602. except TypeError:
  5603. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  5604. filenames = [str(filename) for filename in filenames]
  5605. self.last_op_excellon_filter = _f
  5606. else:
  5607. filenames = [str(name)]
  5608. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5609. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5610. _("Opening Excellon file.")),
  5611. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5612. color=QtGui.QColor("gray"))
  5613. if len(filenames) == 0:
  5614. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5615. else:
  5616. for filename in filenames:
  5617. if filename != '':
  5618. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  5619. def on_fileopengcode(self, signal, name=None):
  5620. """
  5621. File menu call back for opening gcode.
  5622. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5623. :param name:
  5624. :return:
  5625. """
  5626. self.defaults.report_usage("on_fileopengcode")
  5627. App.log.debug("on_fileopengcode()")
  5628. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  5629. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  5630. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.sbp *.mpf);;" \
  5631. "All Files (*.*)"
  5632. if name is None:
  5633. try:
  5634. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  5635. directory=self.get_last_folder(),
  5636. filter=_filter_,
  5637. initialFilter=self.last_op_gcode_filter)
  5638. except TypeError:
  5639. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  5640. filenames = [str(filename) for filename in filenames]
  5641. self.last_op_gcode_filter = _f
  5642. else:
  5643. filenames = [name]
  5644. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5645. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5646. _("Opening G-Code file.")),
  5647. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5648. color=QtGui.QColor("gray"))
  5649. if len(filenames) == 0:
  5650. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5651. else:
  5652. for filename in filenames:
  5653. if filename != '':
  5654. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename, None, True]})
  5655. def on_file_openproject(self, signal):
  5656. """
  5657. File menu callback for opening a project.
  5658. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5659. :return: None
  5660. """
  5661. self.defaults.report_usage("on_file_openproject")
  5662. App.log.debug("on_file_openproject()")
  5663. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  5664. try:
  5665. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  5666. directory=self.get_last_folder(), filter=_filter_)
  5667. except TypeError:
  5668. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  5669. # The Qt methods above will return a QString which can cause problems later.
  5670. # So far json.dump() will fail to serialize it.
  5671. # TODO: Improve the serialization methods and remove this fix.
  5672. filename = str(filename)
  5673. if filename == "":
  5674. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5675. else:
  5676. # self.worker_task.emit({'fcn': self.open_project,
  5677. # 'params': [filename]})
  5678. # The above was failing because open_project() is not
  5679. # thread safe. The new_project()
  5680. self.open_project(filename)
  5681. def on_fileopenhpgl2(self, signal, name=None):
  5682. """
  5683. File menu callback for opening a HPGL2.
  5684. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5685. :param name:
  5686. :return: None
  5687. """
  5688. self.defaults.report_usage("on_fileopenhpgl2")
  5689. App.log.debug("on_fileopenhpgl2()")
  5690. _filter_ = "HPGL2 Files (*.plt);;" \
  5691. "All Files (*.*)"
  5692. if name is None:
  5693. try:
  5694. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"),
  5695. directory=self.get_last_folder(),
  5696. filter=_filter_)
  5697. except TypeError:
  5698. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"), filter=_filter_)
  5699. filenames = [str(filename) for filename in filenames]
  5700. else:
  5701. filenames = [name]
  5702. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5703. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5704. _("Opening HPGL2 file.")),
  5705. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5706. color=QtGui.QColor("gray"))
  5707. if len(filenames) == 0:
  5708. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5709. else:
  5710. for filename in filenames:
  5711. if filename != '':
  5712. self.worker_task.emit({'fcn': self.open_hpgl2, 'params': [filename]})
  5713. def on_file_openconfig(self, signal):
  5714. """
  5715. File menu callback for opening a config file.
  5716. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5717. :return: None
  5718. """
  5719. self.defaults.report_usage("on_file_openconfig")
  5720. App.log.debug("on_file_openconfig()")
  5721. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  5722. try:
  5723. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  5724. directory=self.data_path, filter=_filter_)
  5725. except TypeError:
  5726. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  5727. filter=_filter_)
  5728. if filename == "":
  5729. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5730. else:
  5731. self.open_config_file(filename)
  5732. def on_file_exportsvg(self):
  5733. """
  5734. Callback for menu item File->Export SVG.
  5735. :return: None
  5736. """
  5737. self.defaults.report_usage("on_file_exportsvg")
  5738. App.log.debug("on_file_exportsvg()")
  5739. obj = self.collection.get_active()
  5740. if obj is None:
  5741. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5742. msg = _("Please Select a Geometry object to export")
  5743. msgbox = QtWidgets.QMessageBox()
  5744. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  5745. msgbox.setInformativeText(msg)
  5746. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5747. msgbox.setDefaultButton(bt_ok)
  5748. msgbox.exec_()
  5749. return
  5750. # Check for more compatible types and add as required
  5751. if (not isinstance(obj, GeometryObject)
  5752. and not isinstance(obj, GerberObject)
  5753. and not isinstance(obj, CNCJobObject)
  5754. and not isinstance(obj, ExcellonObject)):
  5755. msg = '[ERROR_NOTCL] %s' % \
  5756. _("Only Geometry, Gerber and CNCJob objects can be used.")
  5757. msgbox = QtWidgets.QMessageBox()
  5758. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  5759. msgbox.setInformativeText(msg)
  5760. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5761. msgbox.setDefaultButton(bt_ok)
  5762. msgbox.exec_()
  5763. return
  5764. name = obj.options["name"]
  5765. _filter = "SVG File (*.svg);;All Files (*.*)"
  5766. try:
  5767. filename, _f = FCFileSaveDialog.get_saved_filename(
  5768. caption=_("Export SVG"),
  5769. directory=self.get_last_save_folder() + '/' + str(name) + '_svg',
  5770. ext_filter=_filter)
  5771. except TypeError:
  5772. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export SVG"), ext_filter=_filter)
  5773. filename = str(filename)
  5774. if filename == "":
  5775. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5776. return
  5777. else:
  5778. self.export_svg(name, filename)
  5779. if self.defaults["global_open_style"] is False:
  5780. self.file_opened.emit("SVG", filename)
  5781. self.file_saved.emit("SVG", filename)
  5782. def on_file_exportpng(self):
  5783. self.defaults.report_usage("on_file_exportpng")
  5784. App.log.debug("on_file_exportpng()")
  5785. self.date = str(datetime.today()).rpartition('.')[0]
  5786. self.date = ''.join(c for c in self.date if c not in ':-')
  5787. self.date = self.date.replace(' ', '_')
  5788. data = None
  5789. if self.is_legacy is False:
  5790. image = _screenshot(alpha=False)
  5791. data = np.asarray(image)
  5792. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  5793. self.inform.emit('[[WARNING_NOTCL]] %s' % _('Data must be a 3D array with last dimension 3 or 4'))
  5794. return
  5795. filter_ = "PNG File (*.png);;All Files (*.*)"
  5796. try:
  5797. filename, _f = FCFileSaveDialog.get_saved_filename(
  5798. caption=_("Export PNG Image"),
  5799. directory=self.get_last_save_folder() + '/png_' + self.date,
  5800. ext_filter=filter_)
  5801. except TypeError:
  5802. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export PNG Image"), ext_filter=filter_)
  5803. filename = str(filename)
  5804. if filename == "":
  5805. self.inform.emit(_("Cancelled."))
  5806. return
  5807. else:
  5808. if self.is_legacy is False:
  5809. write_png(filename, data)
  5810. else:
  5811. self.plotcanvas.figure.savefig(filename)
  5812. if self.defaults["global_open_style"] is False:
  5813. self.file_opened.emit("png", filename)
  5814. self.file_saved.emit("png", filename)
  5815. def on_file_savegerber(self):
  5816. """
  5817. Callback for menu item in Project context menu.
  5818. :return: None
  5819. """
  5820. self.defaults.report_usage("on_file_savegerber")
  5821. App.log.debug("on_file_savegerber()")
  5822. obj = self.collection.get_active()
  5823. if obj is None:
  5824. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5825. return
  5826. # Check for more compatible types and add as required
  5827. if not isinstance(obj, GerberObject):
  5828. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  5829. return
  5830. name = self.collection.get_active().options["name"]
  5831. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  5832. try:
  5833. filename, _f = FCFileSaveDialog.get_saved_filename(
  5834. caption="Save Gerber source file",
  5835. directory=self.get_last_save_folder() + '/' + name,
  5836. ext_filter=_filter)
  5837. except TypeError:
  5838. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Gerber source file"), ext_filter=_filter)
  5839. filename = str(filename)
  5840. if filename == "":
  5841. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5842. return
  5843. else:
  5844. self.save_source_file(name, filename)
  5845. if self.defaults["global_open_style"] is False:
  5846. self.file_opened.emit("Gerber", filename)
  5847. self.file_saved.emit("Gerber", filename)
  5848. def on_file_savescript(self):
  5849. """
  5850. Callback for menu item in Project context menu.
  5851. :return: None
  5852. """
  5853. self.defaults.report_usage("on_file_savescript")
  5854. App.log.debug("on_file_savescript()")
  5855. obj = self.collection.get_active()
  5856. if obj is None:
  5857. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5858. return
  5859. # Check for more compatible types and add as required
  5860. if not isinstance(obj, ScriptObject):
  5861. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Script objects can be saved as TCL Script files..."))
  5862. return
  5863. name = self.collection.get_active().options["name"]
  5864. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  5865. try:
  5866. filename, _f = FCFileSaveDialog.get_saved_filename(
  5867. caption="Save Script source file",
  5868. directory=self.get_last_save_folder() + '/' + name,
  5869. ext_filter=_filter)
  5870. except TypeError:
  5871. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Script source file"), ext_filter=_filter)
  5872. filename = str(filename)
  5873. if filename == "":
  5874. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5875. return
  5876. else:
  5877. self.save_source_file(name, filename)
  5878. if self.defaults["global_open_style"] is False:
  5879. self.file_opened.emit("Script", filename)
  5880. self.file_saved.emit("Script", filename)
  5881. def on_file_savedocument(self):
  5882. """
  5883. Callback for menu item in Project context menu.
  5884. :return: None
  5885. """
  5886. self.defaults.report_usage("on_file_savedocument")
  5887. App.log.debug("on_file_savedocument()")
  5888. obj = self.collection.get_active()
  5889. if obj is None:
  5890. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5891. return
  5892. # Check for more compatible types and add as required
  5893. if not isinstance(obj, ScriptObject):
  5894. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Document objects can be saved as Document files..."))
  5895. return
  5896. name = self.collection.get_active().options["name"]
  5897. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  5898. try:
  5899. filename, _f = FCFileSaveDialog.get_saved_filename(
  5900. caption="Save Document source file",
  5901. directory=self.get_last_save_folder() + '/' + name,
  5902. ext_filter=_filter)
  5903. except TypeError:
  5904. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Document source file"),
  5905. ext_filter=_filter)
  5906. filename = str(filename)
  5907. if filename == "":
  5908. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5909. return
  5910. else:
  5911. self.save_source_file(name, filename)
  5912. if self.defaults["global_open_style"] is False:
  5913. self.file_opened.emit("Document", filename)
  5914. self.file_saved.emit("Document", filename)
  5915. def on_file_saveexcellon(self):
  5916. """
  5917. Callback for menu item in project context menu.
  5918. :return: None
  5919. """
  5920. self.defaults.report_usage("on_file_saveexcellon")
  5921. App.log.debug("on_file_saveexcellon()")
  5922. obj = self.collection.get_active()
  5923. if obj is None:
  5924. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5925. return
  5926. # Check for more compatible types and add as required
  5927. if not isinstance(obj, ExcellonObject):
  5928. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  5929. return
  5930. name = self.collection.get_active().options["name"]
  5931. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  5932. try:
  5933. filename, _f = FCFileSaveDialog.get_saved_filename(
  5934. caption=_("Save Excellon source file"),
  5935. directory=self.get_last_save_folder() + '/' + name,
  5936. ext_filter=_filter)
  5937. except TypeError:
  5938. filename, _f = FCFileSaveDialog.get_saved_filename(
  5939. caption=_("Save Excellon source file"), ext_filter=_filter)
  5940. filename = str(filename)
  5941. if filename == "":
  5942. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5943. return
  5944. else:
  5945. self.save_source_file(name, filename)
  5946. if self.defaults["global_open_style"] is False:
  5947. self.file_opened.emit("Excellon", filename)
  5948. self.file_saved.emit("Excellon", filename)
  5949. def on_file_exportexcellon(self):
  5950. """
  5951. Callback for menu item File->Export->Excellon.
  5952. :return: None
  5953. """
  5954. self.defaults.report_usage("on_file_exportexcellon")
  5955. App.log.debug("on_file_exportexcellon()")
  5956. obj = self.collection.get_active()
  5957. if obj is None:
  5958. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5959. return
  5960. # Check for more compatible types and add as required
  5961. if not isinstance(obj, ExcellonObject):
  5962. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  5963. return
  5964. name = self.collection.get_active().options["name"]
  5965. _filter = self.defaults["excellon_save_filters"]
  5966. try:
  5967. filename, _f = FCFileSaveDialog.get_saved_filename(
  5968. caption=_("Export Excellon"),
  5969. directory=self.get_last_save_folder() + '/' + name,
  5970. ext_filter=_filter)
  5971. except TypeError:
  5972. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Excellon"), ext_filter=_filter)
  5973. filename = str(filename)
  5974. if filename == "":
  5975. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5976. return
  5977. else:
  5978. used_extension = filename.rpartition('.')[2]
  5979. obj.update_filters(last_ext=used_extension, filter_string='excellon_save_filters')
  5980. self.export_excellon(name, filename)
  5981. if self.defaults["global_open_style"] is False:
  5982. self.file_opened.emit("Excellon", filename)
  5983. self.file_saved.emit("Excellon", filename)
  5984. def on_file_exportgerber(self):
  5985. """
  5986. Callback for menu item File->Export->Gerber.
  5987. :return: None
  5988. """
  5989. self.defaults.report_usage("on_file_exportgerber")
  5990. App.log.debug("on_file_exportgerber()")
  5991. obj = self.collection.get_active()
  5992. if obj is None:
  5993. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5994. return
  5995. # Check for more compatible types and add as required
  5996. if not isinstance(obj, GerberObject):
  5997. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  5998. return
  5999. name = self.collection.get_active().options["name"]
  6000. _filter_ = self.defaults['gerber_save_filters']
  6001. try:
  6002. filename, _f = FCFileSaveDialog.get_saved_filename(
  6003. caption=_("Export Gerber"),
  6004. directory=self.get_last_save_folder() + '/' + name,
  6005. ext_filter=_filter_)
  6006. except TypeError:
  6007. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Gerber"), ext_filter=_filter_)
  6008. filename = str(filename)
  6009. if filename == "":
  6010. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6011. return
  6012. else:
  6013. used_extension = filename.rpartition('.')[2]
  6014. obj.update_filters(last_ext=used_extension, filter_string='gerber_save_filters')
  6015. self.export_gerber(name, filename)
  6016. if self.defaults["global_open_style"] is False:
  6017. self.file_opened.emit("Gerber", filename)
  6018. self.file_saved.emit("Gerber", filename)
  6019. def on_file_exportdxf(self):
  6020. """
  6021. Callback for menu item File->Export DXF.
  6022. :return: None
  6023. """
  6024. self.defaults.report_usage("on_file_exportdxf")
  6025. App.log.debug("on_file_exportdxf()")
  6026. obj = self.collection.get_active()
  6027. if obj is None:
  6028. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6029. msg = _("Please Select a Geometry object to export")
  6030. msgbox = QtWidgets.QMessageBox()
  6031. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  6032. msgbox.setInformativeText(msg)
  6033. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6034. msgbox.setDefaultButton(bt_ok)
  6035. msgbox.exec_()
  6036. return
  6037. # Check for more compatible types and add as required
  6038. if not isinstance(obj, GeometryObject):
  6039. msg = '[ERROR_NOTCL] %s' % _("Only Geometry objects can be used.")
  6040. msgbox = QtWidgets.QMessageBox()
  6041. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  6042. msgbox.setInformativeText(msg)
  6043. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6044. msgbox.setDefaultButton(bt_ok)
  6045. msgbox.exec_()
  6046. return
  6047. name = self.collection.get_active().options["name"]
  6048. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  6049. try:
  6050. filename, _f = FCFileSaveDialog.get_saved_filename(
  6051. caption=_("Export DXF"),
  6052. directory=self.get_last_save_folder() + '/' + name,
  6053. ext_filter=_filter_)
  6054. except TypeError:
  6055. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export DXF"), ext_filter=_filter_)
  6056. filename = str(filename)
  6057. if filename == "":
  6058. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6059. return
  6060. else:
  6061. self.export_dxf(name, filename)
  6062. if self.defaults["global_open_style"] is False:
  6063. self.file_opened.emit("DXF", filename)
  6064. self.file_saved.emit("DXF", filename)
  6065. def on_file_importsvg(self, type_of_obj):
  6066. """
  6067. Callback for menu item File->Import SVG.
  6068. :param type_of_obj: to import the SVG as Geometry or as Gerber
  6069. :type type_of_obj: str
  6070. :return: None
  6071. """
  6072. self.defaults.report_usage("on_file_importsvg")
  6073. App.log.debug("on_file_importsvg()")
  6074. _filter_ = "SVG File .svg (*.svg);;All Files (*.*)"
  6075. try:
  6076. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6077. directory=self.get_last_folder(), filter=_filter_)
  6078. except TypeError:
  6079. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6080. filter=_filter_)
  6081. if type_of_obj != "geometry" and type_of_obj != "gerber":
  6082. type_of_obj = "geometry"
  6083. filenames = [str(filename) for filename in filenames]
  6084. if len(filenames) == 0:
  6085. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6086. else:
  6087. for filename in filenames:
  6088. if filename != '':
  6089. self.worker_task.emit({'fcn': self.import_svg,
  6090. 'params': [filename, type_of_obj]})
  6091. def on_file_importdxf(self, type_of_obj):
  6092. """
  6093. Callback for menu item File->Import DXF.
  6094. :param type_of_obj: to import the DXF as Geometry or as Gerber
  6095. :type type_of_obj: str
  6096. :return: None
  6097. """
  6098. self.defaults.report_usage("on_file_importdxf")
  6099. App.log.debug("on_file_importdxf()")
  6100. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  6101. try:
  6102. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6103. directory=self.get_last_folder(),
  6104. filter=_filter_)
  6105. except TypeError:
  6106. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6107. filter=_filter_)
  6108. if type_of_obj != "geometry" and type_of_obj != "gerber":
  6109. type_of_obj = "geometry"
  6110. filenames = [str(filename) for filename in filenames]
  6111. if len(filenames) == 0:
  6112. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6113. else:
  6114. for filename in filenames:
  6115. if filename != '':
  6116. self.worker_task.emit({'fcn': self.import_dxf,
  6117. 'params': [filename, type_of_obj]})
  6118. # ###############################################################################################################
  6119. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  6120. # ###############################################################################################################
  6121. def init_code_editor(self, name):
  6122. self.text_editor_tab = AppTextEditor(app=self, plain_text=True)
  6123. # add the tab if it was closed
  6124. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  6125. self.text_editor_tab.setObjectName('text_editor_tab')
  6126. # delete the absolute and relative position and messages in the infobar
  6127. # self.ui.position_label.setText("")
  6128. # self.ui.rel_position_label.setText("")
  6129. # hide coordinates toolbars in the infobar while in DB
  6130. self.ui.coords_toolbar.hide()
  6131. self.ui.delta_coords_toolbar.hide()
  6132. # first clear previous text in text editor (if any)
  6133. self.text_editor_tab.code_editor.clear()
  6134. self.text_editor_tab.code_editor.setReadOnly(False)
  6135. self.toggle_codeeditor = True
  6136. self.text_editor_tab.code_editor.completer_enable = False
  6137. self.text_editor_tab.buttonRun.hide()
  6138. # make sure to keep a reference to the code editor
  6139. self.reference_code_editor = self.text_editor_tab.code_editor
  6140. # Switch plot_area to CNCJob tab
  6141. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  6142. def on_view_source(self):
  6143. """
  6144. Called when the user wants to see the source file of the selected object
  6145. :return:
  6146. """
  6147. try:
  6148. obj = self.collection.get_active()
  6149. except Exception as e:
  6150. log.debug("App.on_view_source() --> %s" % str(e))
  6151. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  6152. return 'fail'
  6153. if obj is None:
  6154. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  6155. return 'fail'
  6156. self.inform.emit('%s' % _("Viewing the source code of the selected object."))
  6157. self.proc_container.view.set_busy(_("Loading..."))
  6158. flt = "All Files (*.*)"
  6159. if obj.kind == 'gerber':
  6160. flt = "Gerber Files .gbr (*.GBR);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6161. elif obj.kind == 'excellon':
  6162. flt = "Excellon Files .drl (*.DRL);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6163. elif obj.kind == 'cncjob':
  6164. flt = "GCode Files .nc (*.NC);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6165. self.source_editor_tab = AppTextEditor(app=self, plain_text=True)
  6166. # add the tab if it was closed
  6167. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  6168. self.source_editor_tab.setObjectName('source_editor_tab')
  6169. # delete the absolute and relative position and messages in the infobar
  6170. # self.ui.position_label.setText("")
  6171. # self.ui.rel_position_label.setText("")
  6172. # hide coordinates toolbars in the infobar while in DB
  6173. self.ui.coords_toolbar.hide()
  6174. self.ui.delta_coords_toolbar.hide()
  6175. # first clear previous text in text editor (if any)
  6176. self.source_editor_tab.code_editor.clear()
  6177. self.source_editor_tab.code_editor.setReadOnly(False)
  6178. self.source_editor_tab.code_editor.completer_enable = False
  6179. self.source_editor_tab.buttonRun.hide()
  6180. # Switch plot_area to CNCJob tab
  6181. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  6182. try:
  6183. self.source_editor_tab.buttonOpen.clicked.disconnect()
  6184. except TypeError:
  6185. pass
  6186. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  6187. try:
  6188. self.source_editor_tab.buttonSave.clicked.disconnect()
  6189. except TypeError:
  6190. pass
  6191. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  6192. # then append the text from GCode to the text editor
  6193. if obj.kind == 'cncjob':
  6194. try:
  6195. file = obj.export_gcode(
  6196. preamble=self.defaults["cncjob_prepend"],
  6197. postamble=self.defaults["cncjob_append"],
  6198. to_file=True)
  6199. if file == 'fail':
  6200. return 'fail'
  6201. except AttributeError:
  6202. self.inform.emit('[WARNING_NOTCL] %s' %
  6203. _("There is no selected object for which to see it's source file code."))
  6204. return 'fail'
  6205. else:
  6206. try:
  6207. file = StringIO(obj.source_file)
  6208. except (AttributeError, TypeError):
  6209. self.inform.emit('[WARNING_NOTCL] %s' %
  6210. _("There is no selected object for which to see it's source file code."))
  6211. return 'fail'
  6212. self.source_editor_tab.t_frame.hide()
  6213. try:
  6214. self.source_editor_tab.code_editor.setPlainText(file.getvalue())
  6215. # for line in file:
  6216. # QtWidgets.QApplication.processEvents()
  6217. # proc_line = str(line).strip('\n')
  6218. # self.source_editor_tab.code_editor.append(proc_line)
  6219. except Exception as e:
  6220. log.debug('App.on_view_source() -->%s' % str(e))
  6221. self.inform.emit('[ERROR] %s: %s' % (_('Failed to load the source code for the selected object'), str(e)))
  6222. return
  6223. self.source_editor_tab.handleTextChanged()
  6224. self.source_editor_tab.t_frame.show()
  6225. self.source_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.Start)
  6226. self.proc_container.view.set_idle()
  6227. # self.ui.show()
  6228. def on_toggle_code_editor(self):
  6229. self.defaults.report_usage("on_toggle_code_editor()")
  6230. if self.toggle_codeeditor is False:
  6231. self.init_code_editor(name=_("Code Editor"))
  6232. self.text_editor_tab.buttonOpen.clicked.disconnect()
  6233. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  6234. self.text_editor_tab.buttonSave.clicked.disconnect()
  6235. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  6236. else:
  6237. for idx in range(self.ui.plot_tab_area.count()):
  6238. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  6239. self.ui.plot_tab_area.closeTab(idx)
  6240. break
  6241. self.toggle_codeeditor = False
  6242. def on_code_editor_close(self):
  6243. self.toggle_codeeditor = False
  6244. def goto_text_line(self):
  6245. """
  6246. Will scroll a text to the specified text line.
  6247. :return: None
  6248. """
  6249. dia_box = Dialog_box(title=_("Go to Line ..."),
  6250. label=_("Line:"),
  6251. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  6252. initial_text='')
  6253. try:
  6254. line = int(dia_box.location) - 1
  6255. except (ValueError, TypeError):
  6256. line = 0
  6257. if dia_box.ok:
  6258. # make sure to move first the cursor at the end so after finding the line the line will be positioned
  6259. # at the top of the window
  6260. self.ui.plot_tab_area.currentWidget().code_editor.moveCursor(QTextCursor.End)
  6261. # get the document() of the AppTextEditor
  6262. doc = self.ui.plot_tab_area.currentWidget().code_editor.document()
  6263. # create a Text Cursor based on the searched line
  6264. cursor = QTextCursor(doc.findBlockByLineNumber(line))
  6265. # set cursor of the code editor with the cursor at the searcehd line
  6266. self.ui.plot_tab_area.currentWidget().code_editor.setTextCursor(cursor)
  6267. def on_filenewscript(self, silent=False):
  6268. """
  6269. Will create a new script file and open it in the Code Editor
  6270. :param silent: if True will not display status messages
  6271. :return: None
  6272. """
  6273. if silent is False:
  6274. self.inform.emit('[success] %s' % _("New TCL script file created in Code Editor."))
  6275. # delete the absolute and relative position and messages in the infobar
  6276. # self.ui.position_label.setText("")
  6277. # self.ui.rel_position_label.setText("")
  6278. # hide coordinates toolbars in the infobar while in DB
  6279. self.ui.coords_toolbar.hide()
  6280. self.ui.delta_coords_toolbar.hide()
  6281. self.app_obj.new_script_object()
  6282. # script_text = script_obj.source_file
  6283. #
  6284. # self.proc_container.view.set_busy(_("Loading..."))
  6285. # script_obj.script_editor_tab.t_frame.hide()
  6286. #
  6287. # script_obj.script_editor_tab.t_frame.show()
  6288. # self.proc_container.view.set_idle()
  6289. def on_fileopenscript(self, name=None, silent=False):
  6290. """
  6291. Will open a Tcl script file into the Code Editor
  6292. :param silent: if True will not display status messages
  6293. :param name: name of a Tcl script file to open
  6294. :return: None
  6295. """
  6296. self.defaults.report_usage("on_fileopenscript")
  6297. App.log.debug("on_fileopenscript()")
  6298. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6299. "All Files (*.*)"
  6300. if name:
  6301. filenames = [name]
  6302. else:
  6303. try:
  6304. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6305. caption=_("Open TCL script"), directory=self.get_last_folder(), filter=_filter_)
  6306. except TypeError:
  6307. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6308. if len(filenames) == 0:
  6309. if silent is False:
  6310. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6311. else:
  6312. for filename in filenames:
  6313. if filename != '':
  6314. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6315. def on_fileopenscript_example(self, name=None, silent=False):
  6316. """
  6317. Will open a Tcl script file into the Code Editor
  6318. :param silent: if True will not display status messages
  6319. :param name: name of a Tcl script file to open
  6320. :return:
  6321. """
  6322. self.defaults.report_usage("on_fileopenscript_example")
  6323. log.debug("on_fileopenscript_example()")
  6324. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6325. "All Files (*.*)"
  6326. # test if the app was frozen and choose the path for the configuration file
  6327. if getattr(sys, "frozen", False) is True:
  6328. example_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\assets\\examples'
  6329. else:
  6330. example_path = os.path.dirname(os.path.realpath(__file__)) + '\\assets\\examples'
  6331. if name:
  6332. filenames = [name]
  6333. else:
  6334. try:
  6335. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6336. caption=_("Open TCL script"), directory=example_path, filter=_filter_)
  6337. except TypeError:
  6338. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6339. if len(filenames) == 0:
  6340. if silent is False:
  6341. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6342. else:
  6343. for filename in filenames:
  6344. if filename != '':
  6345. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6346. def on_filerunscript(self, name=None, silent=False):
  6347. """
  6348. File menu callback for loading and running a TCL script.
  6349. :param silent: if True will not display status messages
  6350. :param name: name of a Tcl script file to be run by FlatCAM
  6351. :return: None
  6352. """
  6353. self.defaults.report_usage("on_filerunscript")
  6354. App.log.debug("on_file_runscript()")
  6355. if name:
  6356. filename = name
  6357. if self.cmd_line_headless != 1:
  6358. self.splash.showMessage('%s: %ssec\n%s' %
  6359. (_("Canvas initialization started.\n"
  6360. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6361. _("Executing ScriptObject file.")
  6362. ),
  6363. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6364. color=QtGui.QColor("gray"))
  6365. else:
  6366. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6367. "All Files (*.*)"
  6368. try:
  6369. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  6370. directory=self.get_last_folder(), filter=_filter_)
  6371. except TypeError:
  6372. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  6373. # The Qt methods above will return a QString which can cause problems later.
  6374. # So far json.dump() will fail to serialize it.
  6375. filename = str(filename)
  6376. if filename == "":
  6377. if silent is False:
  6378. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6379. else:
  6380. if self.cmd_line_headless != 1:
  6381. if self.ui.shell_dock.isHidden():
  6382. self.ui.shell_dock.show()
  6383. try:
  6384. with open(filename, "r") as tcl_script:
  6385. cmd_line_shellfile_content = tcl_script.read()
  6386. if self.cmd_line_headless != 1:
  6387. self.shell.exec_command(cmd_line_shellfile_content)
  6388. else:
  6389. self.shell.exec_command(cmd_line_shellfile_content, no_echo=True)
  6390. if silent is False:
  6391. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor and executed."))
  6392. except Exception as e:
  6393. log.debug("App.on_filerunscript() -> %s" % str(e))
  6394. sys.exit(2)
  6395. def on_file_saveproject(self, silent=False):
  6396. """
  6397. Callback for menu item File->Save Project. Saves the project to
  6398. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  6399. if set to None. The project is saved by calling ``self.save_project()``.
  6400. :param silent: if True will not display status messages
  6401. :return: None
  6402. """
  6403. self.defaults.report_usage("on_file_saveproject")
  6404. if self.project_filename is None:
  6405. self.on_file_saveprojectas()
  6406. else:
  6407. self.worker_task.emit({'fcn': self.save_project,
  6408. 'params': [self.project_filename, silent]})
  6409. if self.defaults["global_open_style"] is False:
  6410. self.file_opened.emit("project", self.project_filename)
  6411. self.file_saved.emit("project", self.project_filename)
  6412. self.set_ui_title(name=self.project_filename)
  6413. self.should_we_save = False
  6414. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  6415. """
  6416. Callback for menu item File->Save Project As... Opens a file
  6417. chooser and saves the project to the given file via
  6418. ``self.save_project()``.
  6419. :param make_copy if to be create a copy of the project; boolean
  6420. :param use_thread: if to be run in a separate thread; boolean
  6421. :param quit_action: if to be followed by quiting the application; boolean
  6422. :return: None
  6423. """
  6424. self.defaults.report_usage("on_file_saveprojectas")
  6425. self.date = str(datetime.today()).rpartition('.')[0]
  6426. self.date = ''.join(c for c in self.date if c not in ':-')
  6427. self.date = self.date.replace(' ', '_')
  6428. filter_ = "FlatCAM Project .FlatPrj (*.FlatPrj);; All Files (*.*)"
  6429. try:
  6430. filename, _f = FCFileSaveDialog.get_saved_filename(
  6431. caption=_("Save Project As ..."),
  6432. directory='{l_save}/{proj}_{date}'.format(l_save=str(self.get_last_save_folder()), date=self.date,
  6433. proj=_("Project")),
  6434. ext_filter=filter_
  6435. )
  6436. except TypeError:
  6437. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Project As ..."), ext_filter=filter_)
  6438. filename = str(filename)
  6439. if filename == '':
  6440. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6441. return
  6442. if use_thread is True:
  6443. self.worker_task.emit({'fcn': self.save_project,
  6444. 'params': [filename, quit_action]})
  6445. else:
  6446. self.save_project(filename, quit_action)
  6447. # self.save_project(filename)
  6448. if self.defaults["global_open_style"] is False:
  6449. self.file_opened.emit("project", filename)
  6450. self.file_saved.emit("project", filename)
  6451. if not make_copy:
  6452. self.project_filename = filename
  6453. self.set_ui_title(name=self.project_filename)
  6454. self.should_we_save = False
  6455. def on_file_save_objects_pdf(self, use_thread=True):
  6456. self.date = str(datetime.today()).rpartition('.')[0]
  6457. self.date = ''.join(c for c in self.date if c not in ':-')
  6458. self.date = self.date.replace(' ', '_')
  6459. try:
  6460. obj_selection = self.collection.get_selected()
  6461. if len(obj_selection) == 1:
  6462. obj_name = str(obj_selection[0].options['name'])
  6463. else:
  6464. obj_name = _("FlatCAM objects print")
  6465. except AttributeError as err:
  6466. log.debug("App.on_file_save_object_pdf() --> %s" % str(err))
  6467. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  6468. return
  6469. if not obj_selection:
  6470. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  6471. return
  6472. filter_ = "PDF File .pdf (*.PDF);; All Files (*.*)"
  6473. try:
  6474. filename, _f = FCFileSaveDialog.get_saved_filename(
  6475. caption=_("Save Object as PDF ..."),
  6476. directory='{l_save}/{obj_name}_{date}'.format(l_save=str(self.get_last_save_folder()),
  6477. obj_name=obj_name,
  6478. date=self.date),
  6479. ext_filter=filter_
  6480. )
  6481. except TypeError:
  6482. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Object as PDF ..."), ext_filter=filter_)
  6483. filename = str(filename)
  6484. if filename == '':
  6485. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6486. return
  6487. if use_thread is True:
  6488. self.proc_container.new(_("Printing PDF ... Please wait."))
  6489. self.worker_task.emit({'fcn': self.save_pdf, 'params': [filename, obj_selection]})
  6490. else:
  6491. self.save_pdf(filename, obj_selection)
  6492. # self.save_project(filename)
  6493. if self.defaults["global_open_style"] is False:
  6494. self.file_opened.emit("pdf", filename)
  6495. self.file_saved.emit("pdf", filename)
  6496. def save_pdf(self, file_name, obj_selection):
  6497. p_size = self.defaults['global_workspaceT']
  6498. orientation = self.defaults['global_workspace_orientation']
  6499. color = 'black'
  6500. transparency_level = 1.0
  6501. self.pagesize = {}
  6502. self.pagesize.update(
  6503. {
  6504. 'Bounds': None,
  6505. 'A0': (841 * mm, 1189 * mm),
  6506. 'A1': (594 * mm, 841 * mm),
  6507. 'A2': (420 * mm, 594 * mm),
  6508. 'A3': (297 * mm, 420 * mm),
  6509. 'A4': (210 * mm, 297 * mm),
  6510. 'A5': (148 * mm, 210 * mm),
  6511. 'A6': (105 * mm, 148 * mm),
  6512. 'A7': (74 * mm, 105 * mm),
  6513. 'A8': (52 * mm, 74 * mm),
  6514. 'A9': (37 * mm, 52 * mm),
  6515. 'A10': (26 * mm, 37 * mm),
  6516. 'B0': (1000 * mm, 1414 * mm),
  6517. 'B1': (707 * mm, 1000 * mm),
  6518. 'B2': (500 * mm, 707 * mm),
  6519. 'B3': (353 * mm, 500 * mm),
  6520. 'B4': (250 * mm, 353 * mm),
  6521. 'B5': (176 * mm, 250 * mm),
  6522. 'B6': (125 * mm, 176 * mm),
  6523. 'B7': (88 * mm, 125 * mm),
  6524. 'B8': (62 * mm, 88 * mm),
  6525. 'B9': (44 * mm, 62 * mm),
  6526. 'B10': (31 * mm, 44 * mm),
  6527. 'C0': (917 * mm, 1297 * mm),
  6528. 'C1': (648 * mm, 917 * mm),
  6529. 'C2': (458 * mm, 648 * mm),
  6530. 'C3': (324 * mm, 458 * mm),
  6531. 'C4': (229 * mm, 324 * mm),
  6532. 'C5': (162 * mm, 229 * mm),
  6533. 'C6': (114 * mm, 162 * mm),
  6534. 'C7': (81 * mm, 114 * mm),
  6535. 'C8': (57 * mm, 81 * mm),
  6536. 'C9': (40 * mm, 57 * mm),
  6537. 'C10': (28 * mm, 40 * mm),
  6538. # American paper sizes
  6539. 'LETTER': (8.5 * inch, 11 * inch),
  6540. 'LEGAL': (8.5 * inch, 14 * inch),
  6541. 'ELEVENSEVENTEEN': (11 * inch, 17 * inch),
  6542. # From https://en.wikipedia.org/wiki/Paper_size
  6543. 'JUNIOR_LEGAL': (5 * inch, 8 * inch),
  6544. 'HALF_LETTER': (5.5 * inch, 8 * inch),
  6545. 'GOV_LETTER': (8 * inch, 10.5 * inch),
  6546. 'GOV_LEGAL': (8.5 * inch, 13 * inch),
  6547. 'LEDGER': (17 * inch, 11 * inch),
  6548. }
  6549. )
  6550. exported_svg = []
  6551. for obj in obj_selection:
  6552. svg_obj = obj.export_svg(scale_stroke_factor=0.0,
  6553. scale_factor_x=None, scale_factor_y=None,
  6554. skew_factor_x=None, skew_factor_y=None,
  6555. mirror=None)
  6556. if obj.kind.lower() == 'gerber':
  6557. # color = self.defaults["gerber_plot_fill"][:-2]
  6558. color = obj.fill_color[:-2]
  6559. elif obj.kind.lower() == 'excellon':
  6560. color = '#C40000'
  6561. elif obj.kind.lower() == 'geometry':
  6562. color = self.defaults["global_draw_color"]
  6563. # Change the attributes of the exported SVG
  6564. # We don't need stroke-width
  6565. # We set opacity to maximum
  6566. # We set the colour to WHITE
  6567. root = ET.fromstring(svg_obj)
  6568. for child in root:
  6569. child.set('fill', str(color))
  6570. child.set('opacity', str(transparency_level))
  6571. child.set('stroke', str(color))
  6572. exported_svg.append(ET.tostring(root))
  6573. xmin = Inf
  6574. ymin = Inf
  6575. xmax = -Inf
  6576. ymax = -Inf
  6577. for obj in obj_selection:
  6578. try:
  6579. gxmin, gymin, gxmax, gymax = obj.bounds()
  6580. xmin = min([xmin, gxmin])
  6581. ymin = min([ymin, gymin])
  6582. xmax = max([xmax, gxmax])
  6583. ymax = max([ymax, gymax])
  6584. except Exception as e:
  6585. log.warning("DEV WARNING: Tried to get bounds of empty geometry in App.save_pdf(). %s" % str(e))
  6586. # Determine bounding area for svg export
  6587. bounds = [xmin, ymin, xmax, ymax]
  6588. size = bounds[2] - bounds[0], bounds[3] - bounds[1]
  6589. # This contain the measure units
  6590. uom = obj_selection[0].units.lower()
  6591. # Define a boundary around SVG of about 1.0mm (~39mils)
  6592. if uom in "mm":
  6593. boundary = 1.0
  6594. else:
  6595. boundary = 0.0393701
  6596. # Convert everything to strings for use in the xml doc
  6597. svgwidth = str(size[0] + (2 * boundary))
  6598. svgheight = str(size[1] + (2 * boundary))
  6599. minx = str(bounds[0] - boundary)
  6600. miny = str(bounds[1] + boundary + size[1])
  6601. # Add a SVG Header and footer to the svg output from shapely
  6602. # The transform flips the Y Axis so that everything renders
  6603. # properly within svg apps such as inkscape
  6604. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  6605. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  6606. svg_header += 'width="' + svgwidth + uom + '" '
  6607. svg_header += 'height="' + svgheight + uom + '" '
  6608. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  6609. svg_header += '>'
  6610. svg_header += '<g transform="scale(1,-1)">'
  6611. svg_footer = '</g> </svg>'
  6612. svg_elem = str(svg_header)
  6613. for svg_item in exported_svg:
  6614. svg_elem += str(svg_item)
  6615. svg_elem += str(svg_footer)
  6616. # Parse the xml through a xml parser just to add line feeds
  6617. # and to make it look more pretty for the output
  6618. doc = parse_xml_string(svg_elem)
  6619. doc_final = doc.toprettyxml()
  6620. try:
  6621. if self.defaults['units'].upper() == 'IN':
  6622. unit = inch
  6623. else:
  6624. unit = mm
  6625. doc_final = StringIO(doc_final)
  6626. drawing = svg2rlg(doc_final)
  6627. if p_size == 'Bounds':
  6628. renderPDF.drawToFile(drawing, file_name)
  6629. else:
  6630. if orientation == 'p':
  6631. page_size = portrait(self.pagesize[p_size])
  6632. else:
  6633. page_size = landscape(self.pagesize[p_size])
  6634. my_canvas = canvas.Canvas(file_name, pagesize=page_size)
  6635. my_canvas.translate(bounds[0] * unit, bounds[1] * unit)
  6636. renderPDF.draw(drawing, my_canvas, 0, 0)
  6637. my_canvas.save()
  6638. except Exception as e:
  6639. log.debug("App.save_pdf() --> PDF output --> %s" % str(e))
  6640. return 'fail'
  6641. self.inform.emit('[success] %s: %s' % (_("PDF file saved to"), file_name))
  6642. def export_svg(self, obj_name, filename, scale_stroke_factor=0.00):
  6643. """
  6644. Exports a Geometry Object to an SVG file.
  6645. :param obj_name: the name of the FlatCAM object to be saved as SVG
  6646. :param filename: Path to the SVG file to save to.
  6647. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  6648. :return:
  6649. """
  6650. self.defaults.report_usage("export_svg()")
  6651. if filename is None:
  6652. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6653. is not None else self.defaults["global_last_folder"]
  6654. self.log.debug("export_svg()")
  6655. try:
  6656. obj = self.collection.get_by_name(str(obj_name))
  6657. except Exception:
  6658. # TODO: The return behavior has not been established... should raise exception?
  6659. return "Could not retrieve object: %s" % obj_name
  6660. with self.proc_container.new(_("Exporting SVG")) as proc:
  6661. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor)
  6662. # Determine bounding area for svg export
  6663. bounds = obj.bounds()
  6664. size = obj.size()
  6665. # Convert everything to strings for use in the xml doc
  6666. svgwidth = str(size[0])
  6667. svgheight = str(size[1])
  6668. minx = str(bounds[0])
  6669. miny = str(bounds[1] - size[1])
  6670. uom = obj.units.lower()
  6671. # Add a SVG Header and footer to the svg output from shapely
  6672. # The transform flips the Y Axis so that everything renders
  6673. # properly within svg apps such as inkscape
  6674. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  6675. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  6676. svg_header += 'width="' + svgwidth + uom + '" '
  6677. svg_header += 'height="' + svgheight + uom + '" '
  6678. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  6679. svg_header += '<g transform="scale(1,-1)">'
  6680. svg_footer = '</g> </svg>'
  6681. svg_elem = svg_header + exported_svg + svg_footer
  6682. # Parse the xml through a xml parser just to add line feeds
  6683. # and to make it look more pretty for the output
  6684. svgcode = parse_xml_string(svg_elem)
  6685. svgcode = svgcode.toprettyxml()
  6686. try:
  6687. with open(filename, 'w') as fp:
  6688. fp.write(svgcode)
  6689. except PermissionError:
  6690. self.inform.emit('[WARNING] %s' %
  6691. _("Permission denied, saving not possible.\n"
  6692. "Most likely another app is holding the file open and not accessible."))
  6693. return 'fail'
  6694. if self.defaults["global_open_style"] is False:
  6695. self.file_opened.emit("SVG", filename)
  6696. self.file_saved.emit("SVG", filename)
  6697. self.inform.emit('[success] %s: %s' % (_("SVG file exported to"), filename))
  6698. def save_source_file(self, obj_name, filename, use_thread=True):
  6699. """
  6700. Exports a FlatCAM Object to an Gerber/Excellon file.
  6701. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  6702. :param filename: Path to the Gerber file to save to.
  6703. :param use_thread: if to be run in a separate thread
  6704. :return:
  6705. """
  6706. self.defaults.report_usage("save source file()")
  6707. if filename is None:
  6708. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6709. is not None else self.defaults["global_last_folder"]
  6710. self.log.debug("save source file()")
  6711. obj = self.collection.get_by_name(obj_name)
  6712. file_string = StringIO(obj.source_file)
  6713. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6714. if file_string.getvalue() == '':
  6715. self.inform.emit('[ERROR_NOTCL] %s' %
  6716. _("Save cancelled because source file is empty. Try to export the Gerber file."))
  6717. return 'fail'
  6718. try:
  6719. with open(filename, 'w') as file:
  6720. file.writelines('G04*\n')
  6721. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  6722. (obj.kind.upper(), str(self.version), str(self.version_date)))
  6723. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  6724. file.writelines('G04 Created on : %s*\n' % time_string)
  6725. for line in file_string:
  6726. file.writelines(line)
  6727. except PermissionError:
  6728. self.inform.emit('[WARNING] %s' %
  6729. _("Permission denied, saving not possible.\n"
  6730. "Most likely another app is holding the file open and not accessible."))
  6731. return 'fail'
  6732. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  6733. """
  6734. Exports a Excellon Object to an Excellon file.
  6735. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  6736. :param filename: Path to the Excellon file to save to.
  6737. :param local_use:
  6738. :param use_thread: if to be run in a separate thread
  6739. :return:
  6740. """
  6741. self.defaults.report_usage("export_excellon()")
  6742. if filename is None:
  6743. if self.defaults["global_last_save_folder"]:
  6744. filename = self.defaults["global_last_save_folder"] + '/' + 'exported_excellon'
  6745. else:
  6746. filename = self.defaults["global_last_folder"] + '/' + 'exported_excellon'
  6747. self.log.debug("export_excellon()")
  6748. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  6749. self.defaults["excellon_exp_decimals"]
  6750. )
  6751. if local_use is None:
  6752. try:
  6753. obj = self.collection.get_by_name(str(obj_name))
  6754. except Exception:
  6755. return "Could not retrieve object: %s" % obj_name
  6756. else:
  6757. obj = local_use
  6758. if not isinstance(obj, ExcellonObject):
  6759. self.inform.emit('[ERROR_NOTCL] %s' %
  6760. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6761. return
  6762. # updated units
  6763. eunits = self.defaults["excellon_exp_units"]
  6764. ewhole = self.defaults["excellon_exp_integer"]
  6765. efract = self.defaults["excellon_exp_decimals"]
  6766. ezeros = self.defaults["excellon_exp_zeros"]
  6767. eformat = self.defaults["excellon_exp_format"]
  6768. slot_type = self.defaults["excellon_exp_slot_type"]
  6769. fc_units = self.defaults['units'].upper()
  6770. if fc_units == 'MM':
  6771. factor = 1 if eunits == 'METRIC' else 0.03937
  6772. else:
  6773. factor = 25.4 if eunits == 'METRIC' else 1
  6774. def make_excellon():
  6775. try:
  6776. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6777. header = 'M48\n'
  6778. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  6779. (str(self.version), str(self.version_date))
  6780. header += ';Filename: %s' % str(obj_name) + '\n'
  6781. header += ';Created on : %s' % time_str + '\n'
  6782. if eformat == 'dec':
  6783. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  6784. header += eunits + '\n'
  6785. for tool in obj.tools:
  6786. if eunits == 'METRIC':
  6787. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['tooldia']) * factor,
  6788. tool=str(tool),
  6789. dec=2)
  6790. else:
  6791. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['tooldia']) * factor,
  6792. tool=str(tool),
  6793. dec=4)
  6794. else:
  6795. if ezeros == 'LZ':
  6796. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  6797. form='ndec', e_zeros='LZ', factor=factor,
  6798. slot_type=slot_type)
  6799. header += '%s,%s\n' % (eunits, 'LZ')
  6800. header += format_exc
  6801. for tool in obj.tools:
  6802. if eunits == 'METRIC':
  6803. header += "T{tool}F00S00C{:.{dec}f}\n".format(
  6804. float(obj.tools[tool]['tooldia']) * factor,
  6805. tool=str(tool),
  6806. dec=2)
  6807. else:
  6808. header += "T{tool}F00S00C{:.{dec}f}\n".format(
  6809. float(obj.tools[tool]['tooldia']) * factor,
  6810. tool=str(tool),
  6811. dec=4)
  6812. else:
  6813. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  6814. form='ndec', e_zeros='TZ', factor=factor,
  6815. slot_type=slot_type)
  6816. header += '%s,%s\n' % (eunits, 'TZ')
  6817. header += format_exc
  6818. for tool in obj.tools:
  6819. if eunits == 'METRIC':
  6820. header += "T{tool}F00S00C{:.{dec}f}\n".format(
  6821. float(obj.tools[tool]['tooldia']) * factor,
  6822. tool=str(tool),
  6823. dec=2)
  6824. else:
  6825. header += "T{tool}F00S00C{:.{dec}f}\n".format(
  6826. float(obj.tools[tool]['tooldia']) * factor,
  6827. tool=str(tool),
  6828. dec=4)
  6829. header += '%\n'
  6830. footer = 'M30\n'
  6831. exported_excellon = header
  6832. exported_excellon += excellon_code
  6833. exported_excellon += footer
  6834. if local_use is None:
  6835. try:
  6836. with open(filename, 'w') as fp:
  6837. fp.write(exported_excellon)
  6838. except PermissionError:
  6839. self.inform.emit('[WARNING] %s' %
  6840. _("Permission denied, saving not possible.\n"
  6841. "Most likely another app is holding the file open and not accessible."))
  6842. return 'fail'
  6843. if self.defaults["global_open_style"] is False:
  6844. self.file_opened.emit("Excellon", filename)
  6845. self.file_saved.emit("Excellon", filename)
  6846. self.inform.emit('[success] %s: %s' % (_("Excellon file exported to"), filename))
  6847. else:
  6848. return exported_excellon
  6849. except Exception as e:
  6850. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  6851. return 'fail'
  6852. if use_thread is True:
  6853. with self.proc_container.new(_("Exporting Excellon")) as proc:
  6854. def job_thread_exc(app_obj):
  6855. ret = make_excellon()
  6856. if ret == 'fail':
  6857. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  6858. return
  6859. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  6860. else:
  6861. eret = make_excellon()
  6862. if eret == 'fail':
  6863. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  6864. return 'fail'
  6865. if local_use is not None:
  6866. return eret
  6867. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  6868. """
  6869. Exports a Gerber Object to an Gerber file.
  6870. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  6871. :param filename: Path to the Gerber file to save to.
  6872. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  6873. When not None, the value will be the actual Gerber object for which to create the Gerber code
  6874. :param use_thread: if to be run in a separate thread
  6875. :return:
  6876. """
  6877. self.defaults.report_usage("export_gerber()")
  6878. if filename is None:
  6879. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6880. is not None else self.defaults["global_last_folder"]
  6881. self.log.debug("export_gerber()")
  6882. if local_use is None:
  6883. try:
  6884. obj = self.collection.get_by_name(str(obj_name))
  6885. except Exception:
  6886. return "Could not retrieve object: %s" % obj_name
  6887. else:
  6888. obj = local_use
  6889. # updated units
  6890. gunits = self.defaults["gerber_exp_units"]
  6891. gwhole = self.defaults["gerber_exp_integer"]
  6892. gfract = self.defaults["gerber_exp_decimals"]
  6893. gzeros = self.defaults["gerber_exp_zeros"]
  6894. fc_units = self.defaults['units'].upper()
  6895. if fc_units == 'MM':
  6896. factor = 1 if gunits == 'MM' else 0.03937
  6897. else:
  6898. factor = 25.4 if gunits == 'MM' else 1
  6899. def make_gerber():
  6900. try:
  6901. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6902. header = 'G04*\n'
  6903. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  6904. (str(self.version), str(self.version_date))
  6905. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  6906. header += 'G04 Created on : %s*' % time_str + '\n'
  6907. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  6908. header += "%MO{units}*%\n".format(units=gunits)
  6909. for apid in obj.apertures:
  6910. if obj.apertures[apid]['type'] == 'C':
  6911. header += "%ADD{apid}{type},{size}*%\n".format(
  6912. apid=str(apid),
  6913. type='C',
  6914. size=(factor * obj.apertures[apid]['size'])
  6915. )
  6916. elif obj.apertures[apid]['type'] == 'R':
  6917. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  6918. apid=str(apid),
  6919. type='R',
  6920. width=(factor * obj.apertures[apid]['width']),
  6921. height=(factor * obj.apertures[apid]['height'])
  6922. )
  6923. elif obj.apertures[apid]['type'] == 'O':
  6924. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  6925. apid=str(apid),
  6926. type='O',
  6927. width=(factor * obj.apertures[apid]['width']),
  6928. height=(factor * obj.apertures[apid]['height'])
  6929. )
  6930. header += '\n'
  6931. # obsolete units but some software may need it
  6932. if gunits == 'IN':
  6933. header += 'G70*\n'
  6934. else:
  6935. header += 'G71*\n'
  6936. # Absolute Mode
  6937. header += 'G90*\n'
  6938. header += 'G01*\n'
  6939. # positive polarity
  6940. header += '%LPD*%\n'
  6941. footer = 'M02*\n'
  6942. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  6943. exported_gerber = header
  6944. exported_gerber += gerber_code
  6945. exported_gerber += footer
  6946. if local_use is None:
  6947. try:
  6948. with open(filename, 'w') as fp:
  6949. fp.write(exported_gerber)
  6950. except PermissionError:
  6951. self.inform.emit('[WARNING] %s' %
  6952. _("Permission denied, saving not possible.\n"
  6953. "Most likely another app is holding the file open and not accessible."))
  6954. return 'fail'
  6955. if self.defaults["global_open_style"] is False:
  6956. self.file_opened.emit("Gerber", filename)
  6957. self.file_saved.emit("Gerber", filename)
  6958. self.inform.emit('[success] %s: %s' % (_("Gerber file exported to"), filename))
  6959. else:
  6960. return exported_gerber
  6961. except Exception as e:
  6962. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  6963. return 'fail'
  6964. if use_thread is True:
  6965. with self.proc_container.new(_("Exporting Gerber")) as proc:
  6966. def job_thread_grb(app_obj):
  6967. ret = make_gerber()
  6968. if ret == 'fail':
  6969. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  6970. return
  6971. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  6972. else:
  6973. gret = make_gerber()
  6974. if gret == 'fail':
  6975. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  6976. return 'fail'
  6977. if local_use is not None:
  6978. return gret
  6979. def export_dxf(self, obj_name, filename, use_thread=True):
  6980. """
  6981. Exports a Geometry Object to an DXF file.
  6982. :param obj_name: the name of the FlatCAM object to be saved as DXF
  6983. :param filename: Path to the DXF file to save to.
  6984. :param use_thread: if to be run in a separate thread
  6985. :return:
  6986. """
  6987. self.defaults.report_usage("export_dxf()")
  6988. if filename is None:
  6989. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6990. is not None else self.defaults["global_last_folder"]
  6991. self.log.debug("export_dxf()")
  6992. try:
  6993. obj = self.collection.get_by_name(str(obj_name))
  6994. except Exception:
  6995. # TODO: The return behavior has not been established... should raise exception?
  6996. return "Could not retrieve object: %s" % obj_name
  6997. def make_dxf():
  6998. try:
  6999. dxf_code = obj.export_dxf()
  7000. dxf_code.saveas(filename)
  7001. if self.defaults["global_open_style"] is False:
  7002. self.file_opened.emit("DXF", filename)
  7003. self.file_saved.emit("DXF", filename)
  7004. self.inform.emit('[success] %s: %s' % (_("DXF file exported to"), filename))
  7005. except Exception:
  7006. return 'fail'
  7007. if use_thread is True:
  7008. with self.proc_container.new(_("Exporting DXF")) as proc:
  7009. def job_thread_exc(app_obj):
  7010. ret_dxf_val = make_dxf()
  7011. if ret_dxf_val == 'fail':
  7012. app_obj.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  7013. return
  7014. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7015. else:
  7016. ret = make_dxf()
  7017. if ret == 'fail':
  7018. self.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  7019. return
  7020. def import_svg(self, filename, geo_type='geometry', outname=None, plot=True):
  7021. """
  7022. Adds a new Geometry Object to the projects and populates
  7023. it with shapes extracted from the SVG file.
  7024. :param plot: If True then the resulting object will be plotted on canvas
  7025. :param filename: Path to the SVG file.
  7026. :param geo_type: Type of FlatCAM object that will be created from SVG
  7027. :param outname: The name given to the resulting FlatCAM object
  7028. :return:
  7029. """
  7030. self.defaults.report_usage("import_svg()")
  7031. log.debug("App.import_svg()")
  7032. obj_type = ""
  7033. if geo_type is None or geo_type == "geometry":
  7034. obj_type = "geometry"
  7035. elif geo_type == "gerber":
  7036. obj_type = "gerber"
  7037. else:
  7038. self.inform.emit('[ERROR_NOTCL] %s' %
  7039. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  7040. return
  7041. units = self.defaults['units'].upper()
  7042. def obj_init(geo_obj, app_obj):
  7043. geo_obj.import_svg(filename, obj_type, units=units)
  7044. geo_obj.multigeo = False
  7045. geo_obj.source_file = self.export_gerber(obj_name=name, filename=None, local_use=geo_obj, use_thread=False)
  7046. with self.proc_container.new(_("Importing SVG")) as proc:
  7047. # Object name
  7048. name = outname or filename.split('/')[-1].split('\\')[-1]
  7049. ret = self.app_obj.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  7050. if ret == 'fail':
  7051. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  7052. return 'fail'
  7053. # Register recent file
  7054. self.file_opened.emit("svg", filename)
  7055. # appGUI feedback
  7056. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7057. def import_dxf(self, filename, geo_type='geometry', outname=None, plot=True):
  7058. """
  7059. Adds a new Geometry Object to the projects and populates
  7060. it with shapes extracted from the DXF file.
  7061. :param filename: Path to the DXF file.
  7062. :param geo_type: Type of FlatCAM object that will be created from DXF
  7063. :param outname: Name for the imported Geometry
  7064. :param plot: If True then the resulting object will be plotted on canvas
  7065. :return:
  7066. """
  7067. log.debug(" ********* Importing SVG as: %s ********* " % geo_type.capitalize())
  7068. obj_type = ""
  7069. if geo_type is None or geo_type == "geometry":
  7070. obj_type = "geometry"
  7071. elif geo_type == "gerber":
  7072. obj_type = geo_type
  7073. else:
  7074. self.inform.emit('[ERROR_NOTCL] %s' %
  7075. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  7076. return
  7077. units = self.defaults['units'].upper()
  7078. def obj_init(geo_obj, app_obj):
  7079. if obj_type == "geometry":
  7080. geo_obj.import_dxf_as_geo(filename, units=units)
  7081. elif obj_type == "gerber":
  7082. geo_obj.import_dxf_as_gerber(filename, units=units)
  7083. else:
  7084. return "fail"
  7085. geo_obj.multigeo = True
  7086. with self.proc_container.new(_("Importing DXF")):
  7087. # Object name
  7088. name = outname or filename.split('/')[-1].split('\\')[-1]
  7089. ret = self.app_obj.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  7090. if ret == 'fail':
  7091. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  7092. return 'fail'
  7093. # Register recent file
  7094. self.file_opened.emit("dxf", filename)
  7095. # appGUI feedback
  7096. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7097. def open_gerber(self, filename, outname=None, plot=True, from_tcl=False):
  7098. """
  7099. Opens a Gerber file, parses it and creates a new object for
  7100. it in the program. Thread-safe.
  7101. :param outname: Name of the resulting object. None causes the
  7102. name to be that of the file. Str.
  7103. :param filename: Gerber file filename
  7104. :type filename: str
  7105. :param plot: boolean, to plot or not the resulting object
  7106. :param from_tcl: True if run from Tcl Shell
  7107. :return: None
  7108. """
  7109. # How the object should be initialized
  7110. def obj_init(gerber_obj, app_obj):
  7111. assert isinstance(gerber_obj, GerberObject), \
  7112. "Expected to initialize a GerberObject but got %s" % type(gerber_obj)
  7113. # Opening the file happens here
  7114. try:
  7115. gerber_obj.parse_file(filename)
  7116. except IOError:
  7117. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7118. return "fail"
  7119. except ParseError as err:
  7120. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7121. app_obj.log.error(str(err))
  7122. return "fail"
  7123. except Exception as e:
  7124. log.debug("App.open_gerber() --> %s" % str(e))
  7125. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7126. msg += traceback.format_exc()
  7127. app_obj.inform.emit(msg)
  7128. return "fail"
  7129. if gerber_obj.is_empty():
  7130. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7131. _("Object is not Gerber file or empty. Aborting object creation."))
  7132. return "fail"
  7133. App.log.debug("open_gerber()")
  7134. with self.proc_container.new(_("Opening Gerber")):
  7135. # Object name
  7136. name = outname or filename.split('/')[-1].split('\\')[-1]
  7137. # # ## Object creation # ##
  7138. ret_val = self.app_obj.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  7139. if ret_val == 'fail':
  7140. if from_tcl:
  7141. filename = self.defaults['global_tcl_path'] + '/' + name
  7142. ret_val = self.app_obj.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  7143. if ret_val == 'fail':
  7144. self.inform.emit('[ERROR_NOTCL]%s' % _('Open Gerber failed. Probable not a Gerber file.'))
  7145. return 'fail'
  7146. # Register recent file
  7147. self.file_opened.emit("gerber", filename)
  7148. # appGUI feedback
  7149. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7150. def open_excellon(self, filename, outname=None, plot=True, from_tcl=False):
  7151. """
  7152. Opens an Excellon file, parses it and creates a new object for
  7153. it in the program. Thread-safe.
  7154. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7155. :param filename: Excellon file filename
  7156. :type filename: str
  7157. :param plot: boolean, to plot or not the resulting object
  7158. :param from_tcl: True if run from Tcl Shell
  7159. :return: None
  7160. """
  7161. App.log.debug("open_excellon()")
  7162. # How the object should be initialized
  7163. def obj_init(excellon_obj, app_obj):
  7164. try:
  7165. ret = excellon_obj.parse_file(filename=filename)
  7166. if ret == "fail":
  7167. log.debug("Excellon parsing failed.")
  7168. self.inform.emit('[ERROR_NOTCL] %s' %
  7169. _("This is not Excellon file."))
  7170. return "fail"
  7171. except IOError:
  7172. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  7173. (_("Cannot open file"), filename))
  7174. log.debug("Could not open Excellon object.")
  7175. return "fail"
  7176. except Exception:
  7177. msg = '[ERROR_NOTCL] %s' % \
  7178. _("An internal error has occurred. See shell.\n")
  7179. msg += traceback.format_exc()
  7180. app_obj.inform.emit(msg)
  7181. return "fail"
  7182. ret = excellon_obj.create_geometry()
  7183. if ret == 'fail':
  7184. log.debug("Could not create geometry for Excellon object.")
  7185. return "fail"
  7186. for tool in excellon_obj.tools:
  7187. if excellon_obj.tools[tool]['solid_geometry']:
  7188. return
  7189. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("No geometry found in file"), filename))
  7190. return "fail"
  7191. with self.proc_container.new(_("Opening Excellon.")):
  7192. # Object name
  7193. name = outname or filename.split('/')[-1].split('\\')[-1]
  7194. ret_val = self.app_obj.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7195. if ret_val == 'fail':
  7196. if from_tcl:
  7197. filename = self.defaults['global_tcl_path'] + '/' + name
  7198. ret_val = self.app_obj.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7199. if ret_val == 'fail':
  7200. self.inform.emit('[ERROR_NOTCL] %s' %
  7201. _('Open Excellon file failed. Probable not an Excellon file.'))
  7202. return
  7203. # Register recent file
  7204. self.file_opened.emit("excellon", filename)
  7205. # appGUI feedback
  7206. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7207. def open_gcode(self, filename, outname=None, force_parsing=None, plot=True, from_tcl=False):
  7208. """
  7209. Opens a G-gcode file, parses it and creates a new object for
  7210. it in the program. Thread-safe.
  7211. :param filename: G-code file filename
  7212. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7213. :param force_parsing:
  7214. :param plot: If True plot the object on canvas
  7215. :param from_tcl: True if run from Tcl Shell
  7216. :return: None
  7217. """
  7218. App.log.debug("open_gcode()")
  7219. # How the object should be initialized
  7220. def obj_init(job_obj, app_obj_):
  7221. """
  7222. :param job_obj: the resulting object
  7223. :type app_obj_: App
  7224. """
  7225. assert isinstance(app_obj_, App), \
  7226. "Initializer expected App, got %s" % type(app_obj_)
  7227. app_obj_.inform.emit('%s...' % _("Reading GCode file"))
  7228. try:
  7229. f = open(filename)
  7230. gcode = f.read()
  7231. f.close()
  7232. except IOError:
  7233. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open"), filename))
  7234. return "fail"
  7235. job_obj.gcode = gcode
  7236. gcode_ret = job_obj.gcode_parse(force_parsing=force_parsing)
  7237. if gcode_ret == "fail":
  7238. self.inform.emit('[ERROR_NOTCL] %s' % _("This is not GCODE"))
  7239. return "fail"
  7240. job_obj.create_geometry()
  7241. with self.proc_container.new(_("Opening G-Code.")):
  7242. # Object name
  7243. name = outname or filename.split('/')[-1].split('\\')[-1]
  7244. # New object creation and file processing
  7245. ret_val = self.app_obj.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7246. if ret_val == 'fail':
  7247. if from_tcl:
  7248. filename = self.defaults['global_tcl_path'] + '/' + name
  7249. ret_val = self.app_obj.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7250. if ret_val == 'fail':
  7251. self.inform.emit('[ERROR_NOTCL] %s' %
  7252. _("Failed to create CNCJob Object. Probable not a GCode file. "
  7253. "Try to load it from File menu.\n "
  7254. "Attempting to create a FlatCAM CNCJob Object from "
  7255. "G-Code file failed during processing"))
  7256. return "fail"
  7257. # Register recent file
  7258. self.file_opened.emit("cncjob", filename)
  7259. # appGUI feedback
  7260. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7261. def open_hpgl2(self, filename, outname=None):
  7262. """
  7263. Opens a HPGL2 file, parses it and creates a new object for
  7264. it in the program. Thread-safe.
  7265. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7266. :param filename: HPGL2 file filename
  7267. :return: None
  7268. """
  7269. filename = filename
  7270. # How the object should be initialized
  7271. def obj_init(geo_obj, app_obj):
  7272. assert isinstance(geo_obj, GeometryObject), \
  7273. "Expected to initialize a GeometryObject but got %s" % type(geo_obj)
  7274. # Opening the file happens here
  7275. obj = HPGL2(self)
  7276. try:
  7277. HPGL2.parse_file(obj, filename)
  7278. except IOError:
  7279. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7280. return "fail"
  7281. except ParseError as err:
  7282. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7283. app_obj.log.error(str(err))
  7284. return "fail"
  7285. except Exception as e:
  7286. log.debug("App.open_hpgl2() --> %s" % str(e))
  7287. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7288. msg += traceback.format_exc()
  7289. app_obj.inform.emit(msg)
  7290. return "fail"
  7291. geo_obj.multigeo = True
  7292. geo_obj.solid_geometry = deepcopy(obj.solid_geometry)
  7293. geo_obj.tools = deepcopy(obj.tools)
  7294. geo_obj.source_file = deepcopy(obj.source_file)
  7295. del obj
  7296. if not geo_obj.solid_geometry:
  7297. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7298. _("Object is not HPGL2 file or empty. Aborting object creation."))
  7299. return "fail"
  7300. App.log.debug("open_hpgl2()")
  7301. with self.proc_container.new(_("Opening HPGL2")):
  7302. # Object name
  7303. name = outname or filename.split('/')[-1].split('\\')[-1]
  7304. # # ## Object creation # ##
  7305. ret = self.app_obj.new_object("geometry", name, obj_init, autoselected=False)
  7306. if ret == 'fail':
  7307. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open HPGL2 failed. Probable not a HPGL2 file.'))
  7308. return 'fail'
  7309. # Register recent file
  7310. self.file_opened.emit("geometry", filename)
  7311. # appGUI feedback
  7312. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7313. def open_script(self, filename, outname=None, silent=False):
  7314. """
  7315. Opens a Script file, parses it and creates a new object for
  7316. it in the program. Thread-safe.
  7317. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7318. :param filename: Script file filename
  7319. :param silent: If True there will be no messages printed to StatusBar
  7320. :return: None
  7321. """
  7322. def obj_init(script_obj, app_obj):
  7323. assert isinstance(script_obj, ScriptObject), \
  7324. "Expected to initialize a ScriptObject but got %s" % type(script_obj)
  7325. if silent is False:
  7326. app_obj.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  7327. try:
  7328. script_obj.parse_file(filename)
  7329. except IOError:
  7330. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7331. return "fail"
  7332. except ParseError as err:
  7333. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7334. app_obj.log.error(str(err))
  7335. return "fail"
  7336. except Exception as e:
  7337. log.debug("App.open_script() -> %s" % str(e))
  7338. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7339. msg += traceback.format_exc()
  7340. app_obj.inform.emit(msg)
  7341. return "fail"
  7342. App.log.debug("open_script()")
  7343. with self.proc_container.new(_("Opening TCL Script...")):
  7344. # Object name
  7345. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  7346. # Object creation
  7347. ret_val = self.app_obj.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7348. if ret_val == 'fail':
  7349. filename = self.defaults['global_tcl_path'] + '/' + script_name
  7350. ret_val = self.app_obj.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7351. if ret_val == 'fail':
  7352. self.inform.emit('[ERROR_NOTCL]%s' % _('Failed to open TCL Script.'))
  7353. return 'fail'
  7354. # Register recent file
  7355. self.file_opened.emit("script", filename)
  7356. # appGUI feedback
  7357. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7358. def open_config_file(self, filename, run_from_arg=None):
  7359. """
  7360. Loads a config file from the specified file.
  7361. :param filename: Name of the file from which to load.
  7362. :param run_from_arg: if True the FlatConfig file will be open as an command line argument
  7363. :return: None
  7364. """
  7365. App.log.debug("Opening config file: " + filename)
  7366. if run_from_arg:
  7367. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7368. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7369. _("Opening FlatCAM Config file.")),
  7370. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7371. color=QtGui.QColor("gray"))
  7372. # # add the tab if it was closed
  7373. # self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  7374. # # first clear previous text in text editor (if any)
  7375. # self.ui.text_editor_tab.code_editor.clear()
  7376. #
  7377. # # Switch plot_area to CNCJob tab
  7378. # self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  7379. # close the Code editor if already open
  7380. if self.toggle_codeeditor:
  7381. self.on_toggle_code_editor()
  7382. self.on_toggle_code_editor()
  7383. try:
  7384. if filename:
  7385. f = QtCore.QFile(filename)
  7386. if f.open(QtCore.QIODevice.ReadOnly):
  7387. stream = QtCore.QTextStream(f)
  7388. code_edited = stream.readAll()
  7389. self.text_editor_tab.code_editor.setPlainText(code_edited)
  7390. f.close()
  7391. except IOError:
  7392. App.log.error("Failed to open config file: %s" % filename)
  7393. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  7394. (_("Failed to open config file"), filename))
  7395. return
  7396. def open_project(self, filename, run_from_arg=None, plot=True, cli=None, from_tcl=False):
  7397. """
  7398. Loads a project from the specified file.
  7399. 1) Loads and parses file
  7400. 2) Registers the file as recently opened.
  7401. 3) Calls on_file_new()
  7402. 4) Updates options
  7403. 5) Calls app_obj.new_object() with the object's from_dict() as init method.
  7404. 6) Calls plot_all() if plot=True
  7405. :param filename: Name of the file from which to load.
  7406. :param run_from_arg: True if run for arguments
  7407. :param plot: If True plot all objects in the project
  7408. :param cli: Run from command line
  7409. :param from_tcl: True if run from Tcl Sehll
  7410. :return: None
  7411. """
  7412. App.log.debug("Opening project: " + filename)
  7413. # block autosaving while a project is loaded
  7414. self.block_autosave = True
  7415. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7416. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7417. if cli is None:
  7418. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  7419. if run_from_arg:
  7420. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7421. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7422. _("Opening FlatCAM Project file.")),
  7423. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7424. color=QtGui.QColor("gray"))
  7425. # Open and parse an uncompressed Project file
  7426. try:
  7427. f = open(filename, 'r')
  7428. except IOError:
  7429. if from_tcl:
  7430. name = filename.split('/')[-1].split('\\')[-1]
  7431. filename = self.defaults['global_tcl_path'] + '/' + name
  7432. try:
  7433. f = open(filename, 'r')
  7434. except IOError:
  7435. log.error("Failed to open project file: %s" % filename)
  7436. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7437. return
  7438. else:
  7439. log.error("Failed to open project file: %s" % filename)
  7440. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7441. return
  7442. try:
  7443. d = json.load(f, object_hook=dict2obj)
  7444. except Exception as e:
  7445. log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  7446. (filename, str(e)))
  7447. f.close()
  7448. # Open and parse a compressed Project file
  7449. try:
  7450. with lzma.open(filename) as f:
  7451. file_content = f.read().decode('utf-8')
  7452. d = json.loads(file_content, object_hook=dict2obj)
  7453. except Exception as e:
  7454. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  7455. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7456. return
  7457. # Clear the current project
  7458. # # NOT THREAD SAFE # ##
  7459. if run_from_arg is True:
  7460. pass
  7461. elif cli is True:
  7462. self.delete_selection_shape()
  7463. else:
  7464. self.on_file_new()
  7465. # Project options
  7466. self.options.update(d['options'])
  7467. self.project_filename = filename
  7468. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7469. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7470. if cli is None:
  7471. self.set_screen_units(self.options["units"])
  7472. # Re create objects
  7473. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  7474. for obj in d['objs']:
  7475. def obj_init(obj_inst, app_inst):
  7476. try:
  7477. obj_inst.from_dict(obj)
  7478. except Exception as e:
  7479. print('App.open_project() --> ' + str(e))
  7480. return 'fail'
  7481. App.log.debug("Recreating from opened project an %s object: %s" %
  7482. (obj['kind'].capitalize(), obj['options']['name']))
  7483. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7484. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7485. if cli is None:
  7486. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  7487. obj['kind'].upper(),
  7488. obj['options']['name']
  7489. )
  7490. )
  7491. self.app_obj.new_object(obj['kind'], obj['options']['name'], obj_init, plot=plot)
  7492. self.inform.emit('[success] %s: %s' % (_("Project loaded from"), filename))
  7493. self.should_we_save = False
  7494. self.file_opened.emit("project", filename)
  7495. # restore autosaving after a project was loaded
  7496. self.block_autosave = False
  7497. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7498. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7499. if cli is None:
  7500. self.set_ui_title(name=self.project_filename)
  7501. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  7502. def plot_all(self, fit_view=True, muted=False, use_thread=True):
  7503. """
  7504. Re-generates all plots from all objects.
  7505. :param fit_view: if True will plot the objects and will adjust the zoom to fit all plotted objects into view
  7506. :param muted: if True don't print messages
  7507. :param use_thread: if True will use threading for plotting the objects
  7508. :return: None
  7509. """
  7510. self.log.debug("Plot_all()")
  7511. if muted is not True:
  7512. self.inform[str, bool].emit('%s...' % _("Redrawing all objects"), False)
  7513. for plot_obj in self.collection.get_list():
  7514. def worker_task(obj):
  7515. with self.proc_container.new("Plotting"):
  7516. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  7517. if fit_view is True:
  7518. self.app_obj.object_plotted.emit(obj)
  7519. if use_thread is True:
  7520. # Send to worker
  7521. self.worker_task.emit({'fcn': worker_task, 'params': [plot_obj]})
  7522. else:
  7523. worker_task(plot_obj)
  7524. def register_folder(self, filename):
  7525. """
  7526. Register the last folder used by the app to open something
  7527. :param filename: the last folder is extracted from the filename
  7528. :return: None
  7529. """
  7530. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  7531. def register_save_folder(self, filename):
  7532. """
  7533. Register the last folder used by the app to save something
  7534. :param filename: the last folder is extracted from the filename
  7535. :return: None
  7536. """
  7537. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  7538. # def set_progress_bar(self, percentage, text=""):
  7539. # """
  7540. # Set a progress bar to a value (percentage)
  7541. #
  7542. # :param percentage: Value set to the progressbar
  7543. # :param text: Not used
  7544. # :return: None
  7545. # """
  7546. # self.ui.progress_bar.setValue(int(percentage))
  7547. def setup_recent_items(self):
  7548. """
  7549. Setup a dictionary with the recent files accessed, organized by type
  7550. :return:
  7551. """
  7552. icons = {
  7553. "gerber": self.resource_location + "/flatcam_icon16.png",
  7554. "excellon": self.resource_location + "/drill16.png",
  7555. 'geometry': self.resource_location + "/geometry16.png",
  7556. "cncjob": self.resource_location + "/cnc16.png",
  7557. "script": self.resource_location + "/script_new24.png",
  7558. "document": self.resource_location + "/notes16_1.png",
  7559. "project": self.resource_location + "/project16.png",
  7560. "svg": self.resource_location + "/geometry16.png",
  7561. "dxf": self.resource_location + "/dxf16.png",
  7562. "pdf": self.resource_location + "/pdf32.png",
  7563. "image": self.resource_location + "/image16.png"
  7564. }
  7565. try:
  7566. image_opener = self.image_tool.import_image
  7567. except AttributeError:
  7568. image_opener = None
  7569. openers = {
  7570. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  7571. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  7572. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  7573. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  7574. "script": lambda fname: self.worker_task.emit({'fcn': self.open_script, 'params': [fname]}),
  7575. "document": None,
  7576. 'project': self.open_project,
  7577. 'svg': self.import_svg,
  7578. 'dxf': self.import_dxf,
  7579. 'image': image_opener,
  7580. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  7581. }
  7582. # Open recent file for files
  7583. try:
  7584. f = open(self.data_path + '/recent.json')
  7585. except IOError:
  7586. App.log.error("Failed to load recent item list.")
  7587. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent item list."))
  7588. return
  7589. try:
  7590. self.recent = json.load(f)
  7591. except json.errors.JSONDecodeError:
  7592. App.log.error("Failed to parse recent item list.")
  7593. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent item list."))
  7594. f.close()
  7595. return
  7596. f.close()
  7597. # Open recent file for projects
  7598. try:
  7599. fp = open(self.data_path + '/recent_projects.json')
  7600. except IOError:
  7601. App.log.error("Failed to load recent project item list.")
  7602. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent projects item list."))
  7603. return
  7604. try:
  7605. self.recent_projects = json.load(fp)
  7606. except json.errors.JSONDecodeError:
  7607. App.log.error("Failed to parse recent project item list.")
  7608. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent project item list."))
  7609. fp.close()
  7610. return
  7611. fp.close()
  7612. # Closure needed to create callbacks in a loop.
  7613. # Otherwise late binding occurs.
  7614. def make_callback(func, fname):
  7615. def opener():
  7616. func(fname)
  7617. return opener
  7618. def reset_recent_files():
  7619. # Reset menu
  7620. self.ui.recent.clear()
  7621. self.recent = []
  7622. try:
  7623. ff = open(self.data_path + '/recent.json', 'w')
  7624. except IOError:
  7625. App.log.error("Failed to open recent items file for writing.")
  7626. return
  7627. json.dump(self.recent, ff)
  7628. def reset_recent_projects():
  7629. # Reset menu
  7630. self.ui.recent_projects.clear()
  7631. self.recent_projects = []
  7632. try:
  7633. frp = open(self.data_path + '/recent_projects.json', 'w')
  7634. except IOError:
  7635. App.log.error("Failed to open recent projects items file for writing.")
  7636. return
  7637. json.dump(self.recent, frp)
  7638. # Reset menu
  7639. self.ui.recent.clear()
  7640. self.ui.recent_projects.clear()
  7641. # Create menu items for projects
  7642. for recent in self.recent_projects:
  7643. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  7644. if recent['kind'] == 'project':
  7645. try:
  7646. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  7647. # Attach callback
  7648. o = make_callback(openers[recent["kind"]], recent['filename'])
  7649. action.triggered.connect(o)
  7650. self.ui.recent_projects.addAction(action)
  7651. except KeyError:
  7652. App.log.error("Unsupported file type: %s" % recent["kind"])
  7653. # Last action in Recent Files menu is one that Clear the content
  7654. clear_action_proj = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  7655. (_("Clear Recent projects")), self)
  7656. clear_action_proj.triggered.connect(reset_recent_projects)
  7657. self.ui.recent_projects.addSeparator()
  7658. self.ui.recent_projects.addAction(clear_action_proj)
  7659. # Create menu items for files
  7660. for recent in self.recent:
  7661. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  7662. if recent['kind'] != 'project':
  7663. try:
  7664. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  7665. # Attach callback
  7666. o = make_callback(openers[recent["kind"]], recent['filename'])
  7667. action.triggered.connect(o)
  7668. self.ui.recent.addAction(action)
  7669. except KeyError:
  7670. App.log.error("Unsupported file type: %s" % recent["kind"])
  7671. # Last action in Recent Files menu is one that Clear the content
  7672. clear_action = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  7673. (_("Clear Recent files")), self)
  7674. clear_action.triggered.connect(reset_recent_files)
  7675. self.ui.recent.addSeparator()
  7676. self.ui.recent.addAction(clear_action)
  7677. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  7678. # self.ui.menufilerecent.set_submenu(recent_menu)
  7679. # recent_menu.show_all()
  7680. # self.ui.recent.show()
  7681. self.log.debug("Recent items list has been populated.")
  7682. def setup_component_editor(self):
  7683. """
  7684. Default text for the Selected tab when is not taken by the Object UI.
  7685. :return:
  7686. """
  7687. # label = QtWidgets.QLabel("Choose an item from Project")
  7688. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  7689. sel_title = QtWidgets.QTextEdit(
  7690. _('<b>Shortcut Key List</b>'))
  7691. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  7692. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  7693. f_settings = QSettings("Open Source", "FlatCAM")
  7694. if f_settings.contains("notebook_font_size"):
  7695. fsize = f_settings.value('notebook_font_size', type=int)
  7696. else:
  7697. fsize = 12
  7698. tsize = fsize + int(fsize / 2)
  7699. # selected_text = (_('''
  7700. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span>
  7701. # </p>
  7702. #
  7703. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  7704. # The normal flow when working in FlatCAM is the following:</span></p>
  7705. #
  7706. # <ol>
  7707. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG
  7708. # file into
  7709. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  7710. # even dragging and dropping the files on the appGUI.<br />
  7711. # <br />
  7712. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp;
  7713. # drop of the
  7714. # file into the FLATCAM appGUI or through the menu/toolbar links offered within the app.</span><br />
  7715. # &nbsp;</li>
  7716. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it
  7717. # and then
  7718. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  7719. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  7720. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  7721. # <br />
  7722. # If the selection of the object is done on the canvas by single click instead, and the
  7723. # <strong>SELECTED TAB</strong>
  7724. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  7725. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  7726. # it even if it was out of focus.<br />
  7727. # <br />
  7728. # You can change the parameters in this screen and the flow direction is like this:<br />
  7729. # <br />
  7730. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;
  7731. # <strong> Geometry Object
  7732. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  7733. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  7734. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  7735. # </ol>
  7736. #
  7737. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  7738. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  7739. # <strong>F3</strong>.</span></p>
  7740. #
  7741. # ''').format(fsize=fsize, tsize=tsize))
  7742. selected_text = '''
  7743. <p><span style="font-size:{tsize}px"><strong>{title}</strong></span></p>
  7744. <p><span style="font-size:{fsize}px"><strong>{subtitle}</strong>:<br />
  7745. {s1}</span></p>
  7746. <ol>
  7747. <li><span style="font-size:{fsize}px">{s2}<br />
  7748. <br />
  7749. {s3}</span><br />
  7750. &nbsp;</li>
  7751. <li><span style="font-size:{fsize}px">{s4}<br />
  7752. &nbsp;</li>
  7753. <br />
  7754. <li><span style="font-size:{fsize}px">{s5}<br />
  7755. &nbsp;</li>
  7756. <br />
  7757. <li><span style="font-size:{fsize}px">{s6}<br />
  7758. <br />
  7759. {s7}</span></li>
  7760. </ol>
  7761. <p><span style="font-size:{fsize}px">{s8}</span></p>
  7762. '''.format(
  7763. title=_("Selected Tab - Choose an Item from Project Tab"),
  7764. subtitle=_("Details"),
  7765. s1=_("The normal flow when working with the application is the following:"),
  7766. s2=_("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into the application "
  7767. "using either the toolbars, key shortcuts or even dragging and dropping the "
  7768. "files on the GUI."),
  7769. s3=_("You can also load a project by double clicking on the project file, "
  7770. "drag and drop of the file into the GUI or through the menu (or toolbar) "
  7771. "actions offered within the app."),
  7772. s4=_("Once an object is available in the Project Tab, by selecting it and then focusing "
  7773. "on SELECTED TAB (more simpler is to double click the object name in the Project Tab, "
  7774. "SELECTED TAB will be updated with the object properties according to its kind: "
  7775. "Gerber, Excellon, Geometry or CNCJob object."),
  7776. s5=_("If the selection of the object is done on the canvas by single click instead, "
  7777. "and the SELECTED TAB is in focus, again the object properties will be displayed into the "
  7778. "Selected Tab. Alternatively, double clicking on the object on the canvas will bring "
  7779. "the SELECTED TAB and populate it even if it was out of focus."),
  7780. s6=_("You can change the parameters in this screen and the flow direction is like this:"),
  7781. s7=_("Gerber/Excellon Object --> Change Parameter --> Generate Geometry --> Geometry Object --> "
  7782. "Add tools (change param in Selected Tab) --> Generate CNCJob --> CNCJob Object --> "
  7783. "Verify GCode (through Edit CNC Code) and/or append/prepend to GCode "
  7784. "(again, done in SELECTED TAB) --> Save GCode."),
  7785. s8=_("A list of key shortcuts is available through an menu entry in Help --> Shortcuts List "
  7786. "or through its own key shortcut: <b>F3</b>."),
  7787. tsize=tsize,
  7788. fsize=fsize
  7789. )
  7790. sel_title.setText(selected_text)
  7791. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  7792. self.ui.selected_scroll_area.setWidget(sel_title)
  7793. def setup_obj_classes(self):
  7794. """
  7795. Sets up application specifics on the FlatCAMObj class. This way the object.app attribute will point to the App
  7796. class.
  7797. :return: None
  7798. """
  7799. FlatCAMObj.app = self
  7800. ObjectCollection.app = self
  7801. Gerber.app = self
  7802. Excellon.app = self
  7803. Geometry.app = self
  7804. CNCjob.app = self
  7805. FCProcess.app = self
  7806. FCProcessContainer.app = self
  7807. OptionsGroupUI.app = self
  7808. def version_check(self):
  7809. """
  7810. Checks for the latest version of the program. Alerts the
  7811. user if theirs is outdated. This method is meant to be run
  7812. in a separate thread.
  7813. :return: None
  7814. """
  7815. self.log.debug("version_check()")
  7816. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  7817. full_url = "%s?s=%s&v=%s&os=%s&%s" % (
  7818. App.version_url,
  7819. str(self.defaults['global_serial']),
  7820. str(self.version),
  7821. str(self.os),
  7822. urllib.parse.urlencode(self.defaults["global_stats"])
  7823. )
  7824. # full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + \
  7825. # "&v=" + str(self.version) + "&os=" + str(self.os) + "&" + \
  7826. # urllib.parse.urlencode(self.defaults["global_stats"])
  7827. else:
  7828. # no_stats dict; just so it won't break things on website
  7829. no_ststs_dict = {}
  7830. no_ststs_dict["global_ststs"] = {}
  7831. full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + "&v=" + str(self.version)
  7832. full_url += "&os=" + str(self.os) + "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  7833. App.log.debug("Checking for updates @ %s" % full_url)
  7834. # ## Get the data
  7835. try:
  7836. f = urllib.request.urlopen(full_url)
  7837. except Exception:
  7838. # App.log.warning("Failed checking for latest version. Could not connect.")
  7839. self.log.warning("Failed checking for latest version. Could not connect.")
  7840. self.inform.emit('[WARNING_NOTCL] %s' % _("Failed checking for latest version. Could not connect."))
  7841. return
  7842. try:
  7843. data = json.load(f)
  7844. except Exception as e:
  7845. App.log.error("Could not parse information about latest version.")
  7846. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not parse information about latest version."))
  7847. App.log.debug("json.load(): %s" % str(e))
  7848. f.close()
  7849. return
  7850. f.close()
  7851. # ## Latest version?
  7852. if self.version >= data["version"]:
  7853. App.log.debug("FlatCAM is up to date!")
  7854. self.inform.emit('[success] %s' % _("FlatCAM is up to date!"))
  7855. return
  7856. App.log.debug("Newer version available.")
  7857. self.message.emit(
  7858. _("Newer Version Available"),
  7859. '%s<br><br>><b>%s</b><br>%s' % (
  7860. _("There is a newer version of FlatCAM available for download:"),
  7861. str(data["name"]),
  7862. str(data["message"])
  7863. ),
  7864. _("info")
  7865. )
  7866. def on_plotcanvas_setup(self, container=None):
  7867. """
  7868. This is doing the setup for the plot area (canvas).
  7869. :param container: QT Widget where to install the canvas
  7870. :return: None
  7871. """
  7872. if container:
  7873. plot_container = container
  7874. else:
  7875. plot_container = self.ui.right_layout
  7876. modifier = QtWidgets.QApplication.queryKeyboardModifiers()
  7877. if self.is_legacy is True or modifier == QtCore.Qt.ControlModifier:
  7878. self.is_legacy = True
  7879. self.defaults["global_graphic_engine"] = "2D"
  7880. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  7881. else:
  7882. try:
  7883. self.plotcanvas = PlotCanvas(plot_container, self)
  7884. except Exception as er:
  7885. msg_txt = traceback.format_exc()
  7886. log.debug("App.on_plotcanvas_setup() failed -> %s" % str(er))
  7887. log.debug("OpenGL canvas initialization failed with the following error.\n" + msg_txt)
  7888. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  7889. msg += _("OpenGL canvas initialization failed. HW or HW configuration not supported."
  7890. "Change the graphic engine to Legacy(2D) in Edit -> Preferences -> General tab.\n\n")
  7891. msg += msg_txt
  7892. self.inform.emit(msg)
  7893. return 'fail'
  7894. # So it can receive key presses
  7895. self.plotcanvas.native.setFocus()
  7896. if self.is_legacy is False:
  7897. pan_button = 2 if self.defaults["global_pan_button"] == '2' else 3
  7898. # Set the mouse button for panning
  7899. self.plotcanvas.view.camera.pan_button_setting = pan_button
  7900. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  7901. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  7902. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  7903. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_mouse_double_click_over_plot)
  7904. # Keys over plot enabled
  7905. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  7906. if self.defaults['global_cursor_type'] == 'small':
  7907. self.app_cursor = self.plotcanvas.new_cursor()
  7908. else:
  7909. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  7910. if self.ui.grid_snap_btn.isChecked():
  7911. self.app_cursor.enabled = True
  7912. else:
  7913. self.app_cursor.enabled = False
  7914. if self.is_legacy is False:
  7915. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  7916. else:
  7917. # will use the default Matplotlib axes
  7918. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  7919. def on_zoom_fit(self):
  7920. """
  7921. Callback for zoom-fit request. This can be either from the corresponding
  7922. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  7923. with axes limits from the geometry bounds of all objects.
  7924. :return: None
  7925. """
  7926. if self.is_legacy is False:
  7927. self.plotcanvas.fit_view()
  7928. else:
  7929. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  7930. width = xmax - xmin
  7931. height = ymax - ymin
  7932. xmin -= 0.05 * width
  7933. xmax += 0.05 * width
  7934. ymin -= 0.05 * height
  7935. ymax += 0.05 * height
  7936. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  7937. def on_zoom_in(self):
  7938. """
  7939. Callback for zoom-in request.
  7940. :return:
  7941. """
  7942. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  7943. def on_zoom_out(self):
  7944. """
  7945. Callback for zoom-out request.
  7946. :return:
  7947. """
  7948. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  7949. def disable_all_plots(self):
  7950. self.defaults.report_usage("disable_all_plots()")
  7951. self.disable_plots(self.collection.get_list())
  7952. self.inform.emit('[success] %s' %
  7953. _("All plots disabled."))
  7954. def disable_other_plots(self):
  7955. self.defaults.report_usage("disable_other_plots()")
  7956. self.disable_plots(self.collection.get_non_selected())
  7957. self.inform.emit('[success] %s' %
  7958. _("All non selected plots disabled."))
  7959. def enable_all_plots(self):
  7960. self.defaults.report_usage("enable_all_plots()")
  7961. self.enable_plots(self.collection.get_list())
  7962. self.inform.emit('[success] %s' %
  7963. _("All plots enabled."))
  7964. def on_enable_sel_plots(self):
  7965. log.debug("App.on_enable_sel_plot()")
  7966. object_list = self.collection.get_selected()
  7967. self.enable_plots(objects=object_list)
  7968. self.inform.emit('[success] %s' % _("Selected plots enabled..."))
  7969. def on_disable_sel_plots(self):
  7970. log.debug("App.on_disable_sel_plot()")
  7971. # self.inform.emit(_("Disabling plots ..."))
  7972. object_list = self.collection.get_selected()
  7973. self.disable_plots(objects=object_list)
  7974. self.inform.emit('[success] %s' % _("Selected plots disabled..."))
  7975. def enable_plots(self, objects):
  7976. """
  7977. Enable plots
  7978. :param objects: list of Objects to be enabled
  7979. :return:
  7980. """
  7981. log.debug("Enabling plots ...")
  7982. # self.inform.emit(_("Working ..."))
  7983. for obj in objects:
  7984. if obj.options['plot'] is False:
  7985. obj.options.set_change_callback(lambda x: None)
  7986. obj.options['plot'] = True
  7987. try:
  7988. # only the Gerber obj has on_plot_cb_click() method
  7989. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  7990. # disable this cb while disconnected,
  7991. # in case the operation takes time the user is not allowed to change it
  7992. obj.ui.plot_cb.setDisabled(True)
  7993. except AttributeError:
  7994. pass
  7995. obj.set_form_item("plot")
  7996. try:
  7997. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  7998. obj.ui.plot_cb.setDisabled(False)
  7999. except AttributeError:
  8000. pass
  8001. obj.options.set_change_callback(obj.on_options_change)
  8002. def worker_task(objs):
  8003. with self.proc_container.new(_("Enabling plots ...")):
  8004. for plot_obj in objs:
  8005. # obj.options['plot'] = True
  8006. if isinstance(plot_obj, CNCJobObject):
  8007. plot_obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  8008. else:
  8009. plot_obj.plot(visible=True)
  8010. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8011. def disable_plots(self, objects):
  8012. """
  8013. Disables plots
  8014. :param objects: list of Objects to be disabled
  8015. :return:
  8016. """
  8017. # if no objects selected then do nothing
  8018. if not self.collection.get_selected():
  8019. return
  8020. log.debug("Disabling plots ...")
  8021. # self.inform.emit(_("Working ..."))
  8022. for obj in objects:
  8023. if obj.options['plot'] is True:
  8024. obj.options.set_change_callback(lambda x: None)
  8025. obj.options['plot'] = False
  8026. try:
  8027. # only the Gerber obj has on_plot_cb_click() method
  8028. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  8029. obj.ui.plot_cb.setDisabled(True)
  8030. except AttributeError:
  8031. pass
  8032. obj.set_form_item("plot")
  8033. try:
  8034. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  8035. obj.ui.plot_cb.setDisabled(False)
  8036. except AttributeError:
  8037. pass
  8038. obj.options.set_change_callback(obj.on_options_change)
  8039. try:
  8040. self.delete_selection_shape()
  8041. except Exception as e:
  8042. log.debug("App.disable_plots() --> %s" % str(e))
  8043. def worker_task(objs):
  8044. with self.proc_container.new(_("Disabling plots ...")):
  8045. for plot_obj in objs:
  8046. # obj.options['plot'] = True
  8047. if isinstance(plot_obj, CNCJobObject):
  8048. plot_obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  8049. else:
  8050. plot_obj.plot(visible=False)
  8051. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8052. def toggle_plots(self, objects):
  8053. """
  8054. Toggle plots visibility
  8055. :param objects: list of Objects for which to be toggled the visibility
  8056. :return: None
  8057. """
  8058. # if no objects selected then do nothing
  8059. if not self.collection.get_selected():
  8060. return
  8061. log.debug("Toggling plots ...")
  8062. self.inform.emit(_("Working ..."))
  8063. for obj in objects:
  8064. if obj.options['plot'] is False:
  8065. obj.options['plot'] = True
  8066. else:
  8067. obj.options['plot'] = False
  8068. self.app_obj.plots_updated.emit()
  8069. def clear_plots(self):
  8070. """
  8071. Clear the plots
  8072. :return: None
  8073. """
  8074. objects = self.collection.get_list()
  8075. for obj in objects:
  8076. obj.clear(obj == objects[-1])
  8077. # Clear pool to free memory
  8078. self.clear_pool()
  8079. def on_set_color_action_triggered(self):
  8080. """
  8081. This slot gets called by clicking on the menu entry in the Set Color submenu of the context menu in Project Tab
  8082. :return:
  8083. """
  8084. new_color = self.defaults['gerber_plot_fill']
  8085. clicked_action = self.sender()
  8086. assert isinstance(clicked_action, QAction), "Expected a QAction, got %s" % type(clicked_action)
  8087. act_name = clicked_action.text()
  8088. sel_obj_list = self.collection.get_selected()
  8089. if not sel_obj_list:
  8090. return
  8091. # a default value, I just chose this one
  8092. alpha_level = 'BF'
  8093. for sel_obj in sel_obj_list:
  8094. if sel_obj.kind == 'excellon':
  8095. alpha_level = str(hex(
  8096. self.ui.excellon_defaults_form.excellon_gen_group.excellon_alpha_entry.get_value())[2:])
  8097. elif sel_obj.kind == 'gerber':
  8098. alpha_level = str(hex(self.ui.gerber_defaults_form.gerber_gen_group.gerber_alpha_entry.get_value())[2:])
  8099. elif sel_obj.kind == 'geometry':
  8100. alpha_level = 'FF'
  8101. else:
  8102. log.debug(
  8103. "App.on_set_color_action_triggered() --> Default alpfa for this object type not supported yet")
  8104. continue
  8105. sel_obj.alpha_level = alpha_level
  8106. if act_name == _('Red'):
  8107. new_color = '#FF0000' + alpha_level
  8108. if act_name == _('Blue'):
  8109. new_color = '#0000FF' + alpha_level
  8110. if act_name == _('Yellow'):
  8111. new_color = '#FFDF00' + alpha_level
  8112. if act_name == _('Green'):
  8113. new_color = '#00FF00' + alpha_level
  8114. if act_name == _('Purple'):
  8115. new_color = '#FF00FF' + alpha_level
  8116. if act_name == _('Brown'):
  8117. new_color = '#A52A2A' + alpha_level
  8118. if act_name == _('White'):
  8119. new_color = '#FFFFFF' + alpha_level
  8120. if act_name == _('Black'):
  8121. new_color = '#000000' + alpha_level
  8122. if act_name == _('Custom'):
  8123. new_color = QtGui.QColor(self.defaults['gerber_plot_fill'][:7])
  8124. c_dialog = QtWidgets.QColorDialog()
  8125. plot_fill_color = c_dialog.getColor(initial=new_color)
  8126. if plot_fill_color.isValid() is False:
  8127. return
  8128. new_color = str(plot_fill_color.name()) + alpha_level
  8129. if act_name == _("Default"):
  8130. for sel_obj in sel_obj_list:
  8131. if sel_obj.kind == 'excellon':
  8132. new_color = self.defaults['excellon_plot_fill']
  8133. new_line_color = self.defaults['excellon_plot_line']
  8134. elif sel_obj.kind == 'gerber':
  8135. new_color = self.defaults['gerber_plot_fill']
  8136. new_line_color = self.defaults['gerber_plot_line']
  8137. elif sel_obj.kind == 'geometry':
  8138. new_color = self.defaults['geometry_plot_line']
  8139. new_line_color = self.defaults['geometry_plot_line']
  8140. else:
  8141. log.debug(
  8142. "App.on_set_color_action_triggered() --> Default color for this object type not supported yet")
  8143. continue
  8144. sel_obj.fill_color = new_color
  8145. sel_obj.outline_color = new_line_color
  8146. sel_obj.shapes.redraw(
  8147. update_colors=(new_color, new_line_color)
  8148. )
  8149. return
  8150. if act_name == _("Opacity"):
  8151. alpha_level, ok_button = QtWidgets.QInputDialog.getInt(
  8152. self.ui, _("Set alpha level ..."), '%s:' % _("Value"), min=0, max=255, step=1, value=191)
  8153. if ok_button:
  8154. alpha_str = str(hex(alpha_level)[2:]) if alpha_level != 0 else '00'
  8155. for sel_obj in sel_obj_list:
  8156. sel_obj.fill_color = sel_obj.fill_color[:-2] + alpha_str
  8157. sel_obj.shapes.redraw(
  8158. update_colors=(sel_obj.fill_color, sel_obj.outline_color)
  8159. )
  8160. return
  8161. new_line_color = color_variant(new_color[:7], 0.7)
  8162. if act_name == _("White"):
  8163. new_line_color = color_variant("#dedede", 0.7)
  8164. for sel_obj in sel_obj_list:
  8165. sel_obj.fill_color = new_color
  8166. sel_obj.outline_color = new_line_color
  8167. sel_obj.shapes.redraw(
  8168. update_colors=(new_color, new_line_color)
  8169. )
  8170. def generate_cnc_job(self, objects):
  8171. """
  8172. Slot that will be called by clicking an entry in the contextual menu generated in the Project Tab tree
  8173. :param objects: Selected objects in the Project Tab
  8174. :return:
  8175. """
  8176. self.defaults.report_usage("generate_cnc_job()")
  8177. # for obj in objects:
  8178. # obj.generatecncjob()
  8179. for obj in objects:
  8180. obj.on_generatecnc_button_click()
  8181. def save_project(self, filename, quit_action=False, silent=False, from_tcl=False):
  8182. """
  8183. Saves the current project to the specified file.
  8184. :param filename: Name of the file in which to save.
  8185. :type filename: str
  8186. :param quit_action: if the project saving will be followed by an app quit; boolean
  8187. :param silent: if True will not display status messages
  8188. :param from_tcl True is run from Tcl Shell
  8189. :return: None
  8190. """
  8191. self.log.debug("save_project()")
  8192. self.save_in_progress = True
  8193. with self.proc_container.new(_("Saving FlatCAM Project")):
  8194. # Capture the latest changes
  8195. # Current object
  8196. try:
  8197. current_object = self.collection.get_active()
  8198. if current_object:
  8199. current_object.read_form()
  8200. except Exception as e:
  8201. self.log.debug("save_project() --> There was no active object. Skipping read_form. %s" % str(e))
  8202. pass
  8203. # Serialize the whole project
  8204. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  8205. "options": self.options,
  8206. "version": self.version}
  8207. if self.defaults["global_save_compressed"] is True:
  8208. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  8209. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  8210. # # Write
  8211. f.write(g)
  8212. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8213. else:
  8214. # Open file
  8215. try:
  8216. f = open(filename, 'w')
  8217. except IOError:
  8218. App.log.error("Failed to open file for saving: %s", filename)
  8219. self.inform.emit('[ERROR_NOTCL] %s' % _("The object is used by another application."))
  8220. return
  8221. # Write
  8222. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  8223. f.close()
  8224. # verification of the saved project
  8225. # Open and parse
  8226. try:
  8227. saved_f = open(filename, 'r')
  8228. except IOError:
  8229. if silent is False:
  8230. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8231. (_("Failed to verify project file"), filename, _("Retry to save it.")))
  8232. return
  8233. try:
  8234. saved_d = json.load(saved_f, object_hook=dict2obj)
  8235. except Exception:
  8236. if silent is False:
  8237. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8238. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8239. f.close()
  8240. return
  8241. saved_f.close()
  8242. if silent is False:
  8243. if 'version' in saved_d:
  8244. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8245. else:
  8246. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8247. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8248. tb_settings = QSettings("Open Source", "FlatCAM")
  8249. lock_state = self.ui.lock_action.isChecked()
  8250. tb_settings.setValue('toolbar_lock', lock_state)
  8251. # This will write the setting to the platform specific storage.
  8252. del tb_settings
  8253. # if quit:
  8254. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  8255. # t.start()
  8256. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  8257. def start_delayed_quit(self, delay, filename, should_quit=None):
  8258. """
  8259. :param delay: period of checking if project file size is more than zero; in seconds
  8260. :param filename: the name of the project file to be checked periodically for size more than zero
  8261. :param should_quit: if the task finished will be followed by an app quit; boolean
  8262. :return:
  8263. """
  8264. to_quit = should_quit
  8265. self.save_timer = QtCore.QTimer()
  8266. self.save_timer.setInterval(delay)
  8267. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  8268. self.save_timer.start()
  8269. def check_project_file_size(self, filename, should_quit=None):
  8270. """
  8271. :param filename: the name of the project file to be checked periodically for size more than zero
  8272. :param should_quit: will quit the app if True; boolean
  8273. :return:
  8274. """
  8275. try:
  8276. if os.stat(filename).st_size > 0:
  8277. self.save_in_progress = False
  8278. self.save_timer.stop()
  8279. if should_quit:
  8280. self.app_quit.emit()
  8281. except Exception:
  8282. traceback.print_exc()
  8283. def save_project_auto(self):
  8284. """
  8285. Called periodically to save the project.
  8286. It will save if there is no block on the save, if the project was saved at least once and if there is no save in
  8287. # progress.
  8288. :return:
  8289. """
  8290. if self.block_autosave is False and self.should_we_save is True and self.save_in_progress is False:
  8291. self.on_file_saveproject()
  8292. def save_project_auto_update(self):
  8293. """
  8294. Update the auto save time interval value.
  8295. :return:
  8296. """
  8297. log.debug("App.save_project_auto_update() --> updated the interval timeout.")
  8298. try:
  8299. if self.autosave_timer.isActive():
  8300. self.autosave_timer.stop()
  8301. except Exception:
  8302. pass
  8303. if self.defaults['global_autosave'] is True:
  8304. self.autosave_timer.setInterval(int(self.defaults['global_autosave_timeout']))
  8305. self.autosave_timer.start()
  8306. def on_options_app2project(self):
  8307. """
  8308. Callback for Options->Transfer Options->App=>Project. Copies options
  8309. from application defaults to project defaults.
  8310. :return: None
  8311. """
  8312. self.defaults.report_usage("on_options_app2project")
  8313. self.preferencesUiManager.defaults_read_form()
  8314. self.options.update(self.defaults)
  8315. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  8316. """
  8317. Shows a message on the FlatCAM Shell
  8318. :param msg: Message to display.
  8319. :param show: Opens the shell.
  8320. :param error: Shows the message as an error.
  8321. :param warning: Shows the message as an warning.
  8322. :param success: Shows the message as an success.
  8323. :param selected: Indicate that something was selected on canvas
  8324. :return: None
  8325. """
  8326. if show:
  8327. self.ui.shell_dock.show()
  8328. try:
  8329. if error:
  8330. self.shell.append_error(msg + "\n")
  8331. elif warning:
  8332. self.shell.append_warning(msg + "\n")
  8333. elif success:
  8334. self.shell.append_success(msg + "\n")
  8335. elif selected:
  8336. self.shell.append_selected(msg + "\n")
  8337. else:
  8338. self.shell.append_output(msg + "\n")
  8339. except AttributeError:
  8340. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  8341. class ArgsThread(QtCore.QObject):
  8342. open_signal = pyqtSignal(list)
  8343. start = pyqtSignal()
  8344. stop = pyqtSignal()
  8345. if sys.platform == 'win32':
  8346. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  8347. else:
  8348. address = ('/tmp/testipc', 'AF_UNIX')
  8349. def __init__(self):
  8350. super().__init__()
  8351. self.listener = None
  8352. self.thread_exit = False
  8353. self.start.connect(self.run)
  8354. self.stop.connect(self.close_listener)
  8355. def my_loop(self, address):
  8356. try:
  8357. self.listener = Listener(*address)
  8358. while self.thread_exit is False:
  8359. conn = self.listener.accept()
  8360. self.serve(conn)
  8361. except socket.error:
  8362. try:
  8363. conn = Client(*address)
  8364. conn.send(sys.argv)
  8365. conn.send('close')
  8366. # close the current instance only if there are args
  8367. if len(sys.argv) > 1:
  8368. try:
  8369. self.listener.close()
  8370. except Exception:
  8371. pass
  8372. sys.exit()
  8373. except ConnectionRefusedError:
  8374. if sys.platform == 'win32':
  8375. pass
  8376. else:
  8377. os.system('rm /tmp/testipc')
  8378. self.listener = Listener(*address)
  8379. while True:
  8380. conn = self.listener.accept()
  8381. self.serve(conn)
  8382. def serve(self, conn):
  8383. while self.thread_exit is False:
  8384. msg = conn.recv()
  8385. if msg == 'close':
  8386. break
  8387. self.open_signal.emit(msg)
  8388. conn.close()
  8389. # the decorator is a must; without it this technique will not work unless the start signal is connected
  8390. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  8391. @pyqtSlot()
  8392. def run(self):
  8393. self.my_loop(self.address)
  8394. @pyqtSlot()
  8395. def close_listener(self):
  8396. self.thread_exit = True
  8397. self.listener.close()
  8398. # end of file