app_Main.py 455 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152
  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.optimal_tool = None
  1101. self.transform_tool = None
  1102. self.properties_tool = None
  1103. self.pdf_tool = None
  1104. self.image_tool = None
  1105. self.pcb_wizard_tool = None
  1106. self.cal_exc_tool = None
  1107. self.qrcode_tool = None
  1108. self.copper_thieving_tool = None
  1109. self.fiducial_tool = None
  1110. self.edrills_tool = None
  1111. self.align_objects_tool = None
  1112. self.punch_tool = None
  1113. self.invert_tool = None
  1114. self.corners_tool = None
  1115. self.etch_tool = None
  1116. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1117. try:
  1118. self.install_tools()
  1119. except AttributeError as e:
  1120. log.debug("App.__init__() install_tools() --> %s" % str(e))
  1121. # ###########################################################################################################
  1122. # ############################################ SETUP RECENT ITEMS ###########################################
  1123. # ###########################################################################################################
  1124. self.setup_recent_items()
  1125. # ###########################################################################################################
  1126. # ######################################### BookMarks Manager ###############################################
  1127. # ###########################################################################################################
  1128. # install Bookmark Manager and populate bookmarks in the Help -> Bookmarks
  1129. self.install_bookmarks()
  1130. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"])
  1131. # ###########################################################################################################
  1132. # ########################################### Tools Database ################################################
  1133. # ###########################################################################################################
  1134. self.tools_db_tab = None
  1135. # ### System Font Parsing ###
  1136. # self.f_parse = ParseFont(self)
  1137. # self.parse_system_fonts()
  1138. # ###########################################################################################################
  1139. # ############################################## Shell SETUP ################################################
  1140. # ###########################################################################################################
  1141. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1142. if self.defaults["global_shell_at_startup"]:
  1143. self.ui.shell_dock.show()
  1144. else:
  1145. self.ui.shell_dock.hide()
  1146. # ###########################################################################################################
  1147. # ######################################### Check for updates ###############################################
  1148. # ###########################################################################################################
  1149. # Separate thread (Not worker)
  1150. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1151. if (self.beta is False or self.beta is None) and \
  1152. self.ui.general_defaults_form.general_app_group.version_check_cb.get_value() is True:
  1153. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1154. # self.thr2 = QtCore.QThread()
  1155. self.worker_task.emit({'fcn': self.version_check,
  1156. 'params': []})
  1157. # self.thr2.start(QtCore.QThread.LowPriority)
  1158. # ###########################################################################################################
  1159. # ##################################### Register files with FlatCAM; #######################################
  1160. # ################################### It works only for Windows for now ####################################
  1161. # ###########################################################################################################
  1162. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  1163. self.on_register_files()
  1164. # ###########################################################################################################
  1165. # ######################################## Variables for global usage #######################################
  1166. # ###########################################################################################################
  1167. # hold the App units
  1168. self.units = 'MM'
  1169. # coordinates for relative position display
  1170. self.rel_point1 = (0, 0)
  1171. self.rel_point2 = (0, 0)
  1172. # variable to store coordinates
  1173. self.pos = (0, 0)
  1174. self.pos_canvas = (0, 0)
  1175. self.pos_jump = (0, 0)
  1176. # variable to store mouse coordinates
  1177. self.mouse = [0, 0]
  1178. # variable to store the delta positions on cavnas
  1179. self.dx = 0
  1180. self.dy = 0
  1181. # decide if we have a double click or single click
  1182. self.doubleclick = False
  1183. # store here the is_dragging value
  1184. self.event_is_dragging = False
  1185. # variable to store if a command is active (then the var is not None) and which one it is
  1186. self.command_active = None
  1187. # variable to store the status of moving selection action
  1188. # None value means that it's not an selection action
  1189. # True value = a selection from left to right
  1190. # False value = a selection from right to left
  1191. self.selection_type = None
  1192. # List to store the objects that are currently loaded in FlatCAM
  1193. # This list is updated on each object creation or object delete
  1194. self.all_objects_list = []
  1195. self.objects_under_the_click_list = []
  1196. # List to store the objects that are selected
  1197. self.sel_objects_list = []
  1198. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1199. self.key_modifiers = None
  1200. # Variable to store the status of the code editor
  1201. self.toggle_codeeditor = False
  1202. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  1203. self.click_noproject = False
  1204. self.cursor = None
  1205. # Variable to store the GCODE that was edited
  1206. self.gcode_edited = ""
  1207. self.text_editor_tab = None
  1208. # reference for the self.ui.code_editor
  1209. self.reference_code_editor = None
  1210. self.script_code = ''
  1211. # if Tools DB are changed/edited in the Edit -> Tools Database tab the value will be set to True
  1212. self.tools_db_changed_flag = False
  1213. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  1214. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  1215. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'outline',
  1216. 'pho', 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top',
  1217. 'tsm']
  1218. self.exc_list = ['drd', 'drl', 'drill', 'exc', 'ncd', 'tap', 'txt', 'xln']
  1219. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  1220. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ngc', 'ncp', 'out', 'ply', 'rol',
  1221. 'sbp', 'tap', 'xpi']
  1222. self.svg_list = ['svg']
  1223. self.dxf_list = ['dxf']
  1224. self.pdf_list = ['pdf']
  1225. self.prj_list = ['flatprj']
  1226. self.conf_list = ['flatconfig']
  1227. # last used filters
  1228. self.last_op_gerber_filter = None
  1229. self.last_op_excellon_filter = None
  1230. self.last_op_gcode_filter = None
  1231. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1232. # flag for polygons not cleared
  1233. self.poly_not_cleared = False
  1234. # VisPy visuals
  1235. self.isHovering = False
  1236. self.notHovering = True
  1237. # Window geometry
  1238. self.x_pos = None
  1239. self.y_pos = None
  1240. self.width = None
  1241. self.height = None
  1242. # when True, the app has to return from any thread
  1243. self.abort_flag = False
  1244. # set the value used in the Windows Title
  1245. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  1246. # this holds a widget that is installed in the Plot Area when View Source option is used
  1247. self.source_editor_tab = None
  1248. self.pagesize = {}
  1249. # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry
  1250. # VisPy visuals
  1251. if self.is_legacy is False:
  1252. try:
  1253. self.tool_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  1254. except AttributeError:
  1255. self.tool_shapes = None
  1256. else:
  1257. from appGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  1258. self.tool_shapes = ShapeCollectionLegacy(obj=self, app=self, name="tool")
  1259. # used in the delayed shutdown self.start_delayed_quit() method
  1260. self.save_timer = None
  1261. # ###########################################################################################################
  1262. # ################################## ADDING FlatCAM EDITORS section #########################################
  1263. # ###########################################################################################################
  1264. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  1265. # at the first launch of the App , the editors will not be functional.
  1266. try:
  1267. self.geo_editor = AppGeoEditor(self)
  1268. except Exception as es:
  1269. log.debug("app_Main.__init__() --> Geo Editor Error: %s" % str(es))
  1270. try:
  1271. self.exc_editor = AppExcEditor(self)
  1272. except Exception as es:
  1273. log.debug("app_Main.__init__() --> Excellon Editor Error: %s" % str(es))
  1274. try:
  1275. self.grb_editor = AppGerberEditor(self)
  1276. except Exception as es:
  1277. log.debug("app_Main.__init__() --> Gerber Editor Error: %s" % str(es))
  1278. self.log.debug("Finished adding FlatCAM Editor's.")
  1279. self.set_ui_title(name=_("New Project - Not saved"))
  1280. # disable the Excellon path optimizations made with Google OR-Tools if the app is run on a 32bit platform
  1281. current_platform = platform.architecture()[0]
  1282. if current_platform != '64bit':
  1283. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  1284. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.setDisabled(True)
  1285. # ###########################################################################################################
  1286. # ########################################### EXCLUSION AREAS ###############################################
  1287. # ###########################################################################################################
  1288. self.exc_areas = ExclusionAreas(app=self)
  1289. # ###########################################################################################################
  1290. # ##################################### Finished the CONSTRUCTOR ############################################
  1291. # ###########################################################################################################
  1292. App.log.debug("END of constructor. Releasing control.")
  1293. # ###########################################################################################################
  1294. # ########################################## SHOW GUI #######################################################
  1295. # ###########################################################################################################
  1296. # if the app is not started as headless, show it
  1297. if self.cmd_line_headless != 1:
  1298. if show_splash:
  1299. # finish the splash
  1300. self.splash.finish(self.ui)
  1301. mgui_settings = QSettings("Open Source", "FlatCAM")
  1302. if mgui_settings.contains("maximized_gui"):
  1303. maximized_ui = mgui_settings.value('maximized_gui', type=bool)
  1304. if maximized_ui is True:
  1305. self.ui.showMaximized()
  1306. else:
  1307. self.ui.show()
  1308. else:
  1309. self.ui.show()
  1310. if self.defaults["global_systray_icon"]:
  1311. self.trayIcon.show()
  1312. else:
  1313. log.warning("******************* RUNNING HEADLESS *******************")
  1314. # ###########################################################################################################
  1315. # ######################################## START-UP ARGUMENTS ###############################################
  1316. # ###########################################################################################################
  1317. # test if the program was started with a script as parameter
  1318. if self.cmd_line_shellvar:
  1319. try:
  1320. cnt = 0
  1321. command_tcl = 0
  1322. for i in self.cmd_line_shellvar.split(','):
  1323. if i is not None:
  1324. # noinspection PyBroadException
  1325. try:
  1326. command_tcl = eval(i)
  1327. except Exception:
  1328. command_tcl = i
  1329. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  1330. cnt += 1
  1331. # if there are Windows paths then replace the path separator with a Unix like one
  1332. if sys.platform == 'win32':
  1333. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  1334. self.shell.exec_command(command_tcl_formatted, no_echo=True)
  1335. except Exception as ext:
  1336. print("ERROR: ", ext)
  1337. sys.exit(2)
  1338. if self.cmd_line_shellfile:
  1339. if self.cmd_line_headless != 1:
  1340. if self.ui.shell_dock.isHidden():
  1341. self.ui.shell_dock.show()
  1342. try:
  1343. with open(self.cmd_line_shellfile, "r") as myfile:
  1344. # if show_splash:
  1345. # self.splash.showMessage('%s: %ssec\n%s' % (
  1346. # _("Canvas initialization started.\n"
  1347. # "Canvas initialization finished in"), '%.2f' % self.used_time,
  1348. # _("Executing Tcl Script ...")),
  1349. # alignment=Qt.AlignBottom | Qt.AlignLeft,
  1350. # color=QtGui.QColor("gray"))
  1351. cmd_line_shellfile_text = myfile.read()
  1352. if self.cmd_line_headless != 1:
  1353. self.shell.exec_command(cmd_line_shellfile_text)
  1354. else:
  1355. self.shell.exec_command(cmd_line_shellfile_text, no_echo=True)
  1356. except Exception as ext:
  1357. print("ERROR: ", ext)
  1358. sys.exit(2)
  1359. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  1360. # the path/file_name must be enclosed in quotes if it contain spaces
  1361. if App.args:
  1362. self.args_at_startup.emit(App.args)
  1363. if self.defaults.old_defaults_found is True:
  1364. self.inform.emit('[WARNING_NOTCL] %s' % _("Found old default preferences files. "
  1365. "Please reboot the application to update."))
  1366. self.defaults.old_defaults_found = False
  1367. # ######################################### INIT FINISHED #######################################################
  1368. # #################################################################################################################
  1369. # #################################################################################################################
  1370. # #################################################################################################################
  1371. # #################################################################################################################
  1372. # #################################################################################################################
  1373. @staticmethod
  1374. def copy_and_overwrite(from_path, to_path):
  1375. """
  1376. From here:
  1377. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  1378. :param from_path: source path
  1379. :param to_path: destination path
  1380. :return: None
  1381. """
  1382. if os.path.exists(to_path):
  1383. shutil.rmtree(to_path)
  1384. try:
  1385. shutil.copytree(from_path, to_path)
  1386. except FileNotFoundError:
  1387. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\appGUI\\VisPyData\\data'
  1388. shutil.copytree(from_new_path, to_path)
  1389. def on_startup_args(self, args, silent=False):
  1390. """
  1391. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  1392. :param silent: when True it will not print messages on Tcl Shell and/or status bar
  1393. :param args: a list containing the application args at startup
  1394. :return: None
  1395. """
  1396. if args is not None:
  1397. args_to_process = args
  1398. else:
  1399. args_to_process = App.args
  1400. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  1401. for argument in args_to_process:
  1402. if '.FlatPrj'.lower() in argument.lower():
  1403. try:
  1404. project_name = str(argument)
  1405. if project_name == "":
  1406. if silent is False:
  1407. self.inform.emit(_("Cancelled."))
  1408. else:
  1409. # self.open_project(project_name)
  1410. run_from_arg = True
  1411. # self.worker_task.emit({'fcn': self.open_project,
  1412. # 'params': [project_name, run_from_arg]})
  1413. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  1414. except Exception as e:
  1415. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1416. elif '.FlatConfig'.lower() in argument.lower():
  1417. try:
  1418. file_name = str(argument)
  1419. if file_name == "":
  1420. if silent is False:
  1421. self.inform.emit(_("Open Config file failed."))
  1422. else:
  1423. run_from_arg = True
  1424. # self.worker_task.emit({'fcn': self.open_config_file,
  1425. # 'params': [file_name, run_from_arg]})
  1426. self.open_config_file(file_name, run_from_arg=run_from_arg)
  1427. except Exception as e:
  1428. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1429. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  1430. try:
  1431. file_name = str(argument)
  1432. if file_name == "":
  1433. if silent is False:
  1434. self.inform.emit(_("Open Script file failed."))
  1435. else:
  1436. if silent is False:
  1437. self.on_fileopenscript(name=file_name)
  1438. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  1439. self.on_filerunscript(name=file_name)
  1440. except Exception as e:
  1441. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  1442. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  1443. log.debug("App.on_startup_args() --> Quit event.")
  1444. sys.exit()
  1445. elif 'save'.lower() in argument.lower():
  1446. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  1447. self.preferencesUiManager.save_defaults()
  1448. else:
  1449. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  1450. proc_arg = argument.lower()
  1451. for ext in exc_list:
  1452. proc_ext = ext.replace(' ', '')
  1453. proc_ext = '.%s' % proc_ext
  1454. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1455. file_name = str(argument)
  1456. if file_name == "":
  1457. if silent is False:
  1458. self.inform.emit(_("Open Excellon file failed."))
  1459. else:
  1460. self.on_fileopenexcellon(name=file_name, signal=None)
  1461. return
  1462. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  1463. for ext in gco_list:
  1464. proc_ext = ext.replace(' ', '')
  1465. proc_ext = '.%s' % proc_ext
  1466. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1467. file_name = str(argument)
  1468. if file_name == "":
  1469. if silent is False:
  1470. self.inform.emit(_("Open GCode file failed."))
  1471. else:
  1472. self.on_fileopengcode(name=file_name, signal=None)
  1473. return
  1474. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  1475. for ext in grb_list:
  1476. proc_ext = ext.replace(' ', '')
  1477. proc_ext = '.%s' % proc_ext
  1478. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1479. file_name = str(argument)
  1480. if file_name == "":
  1481. if silent is False:
  1482. self.inform.emit(_("Open Gerber file failed."))
  1483. else:
  1484. self.on_fileopengerber(name=file_name, signal=None)
  1485. return
  1486. # if it reached here without already returning then the app was registered with a file that it does not
  1487. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  1488. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  1489. # for arg in args_to_process:
  1490. # if 'FlatCAM.exe' in arg:
  1491. # continue
  1492. # else:
  1493. # sys.exit(2)
  1494. def set_ui_title(self, name):
  1495. """
  1496. Sets the title of the main window.
  1497. :param name: String that store the project path and project name
  1498. :return: None
  1499. """
  1500. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  1501. (self.version,
  1502. ('BETA' if self.beta else ''),
  1503. platform.architecture()[0],
  1504. self.engine,
  1505. name)
  1506. )
  1507. def on_app_restart(self):
  1508. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  1509. # be left in the SySTray
  1510. try:
  1511. self.trayIcon.hide()
  1512. except Exception:
  1513. pass
  1514. fcTranslate.restart_program(app=self)
  1515. def clear_pool(self):
  1516. """
  1517. Clear the multiprocessing pool and calls garbage collector.
  1518. :return: None
  1519. """
  1520. self.pool.close()
  1521. self.pool = Pool()
  1522. self.pool_recreated.emit(self.pool)
  1523. gc.collect()
  1524. def install_tools(self):
  1525. """
  1526. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  1527. Instantiation of the Tools classes.
  1528. The order that the tools are installed is important as they can depend on each other install position.
  1529. :return: None
  1530. """
  1531. # shell tool has t obe initialized always first because other tools print messages in the Shell Dock
  1532. self.shell = FCShell(app=self, version=self.version)
  1533. self.distance_tool = Distance(self)
  1534. self.distance_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance16.png'), pos=self.ui.menuedit,
  1535. before=self.ui.menueditorigin,
  1536. separator=False)
  1537. self.distance_min_tool = DistanceMin(self)
  1538. self.distance_min_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance_min16.png'),
  1539. pos=self.ui.menuedit,
  1540. before=self.ui.menueditorigin,
  1541. separator=True)
  1542. self.dblsidedtool = DblSidedTool(self)
  1543. self.dblsidedtool.install(icon=QtGui.QIcon(self.resource_location + '/doubleside16.png'), separator=False)
  1544. self.cal_exc_tool = ToolCalibration(self)
  1545. self.cal_exc_tool.install(icon=QtGui.QIcon(self.resource_location + '/calibrate_16.png'), pos=self.ui.menutool,
  1546. before=self.dblsidedtool.menuAction,
  1547. separator=False)
  1548. self.align_objects_tool = AlignObjects(self)
  1549. self.align_objects_tool.install(icon=QtGui.QIcon(self.resource_location + '/align16.png'), separator=False)
  1550. self.edrills_tool = ToolExtractDrills(self)
  1551. self.edrills_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), separator=True)
  1552. self.panelize_tool = Panelize(self)
  1553. self.panelize_tool.install(icon=QtGui.QIcon(self.resource_location + '/panelize16.png'))
  1554. self.film_tool = Film(self)
  1555. self.film_tool.install(icon=QtGui.QIcon(self.resource_location + '/film16.png'))
  1556. self.paste_tool = SolderPaste(self)
  1557. self.paste_tool.install(icon=QtGui.QIcon(self.resource_location + '/solderpastebis32.png'))
  1558. self.calculator_tool = ToolCalculator(self)
  1559. self.calculator_tool.install(icon=QtGui.QIcon(self.resource_location + '/calculator16.png'), separator=True)
  1560. self.sub_tool = ToolSub(self)
  1561. self.sub_tool.install(icon=QtGui.QIcon(self.resource_location + '/sub32.png'),
  1562. pos=self.ui.menutool, separator=True)
  1563. self.rules_tool = RulesCheck(self)
  1564. self.rules_tool.install(icon=QtGui.QIcon(self.resource_location + '/rules32.png'),
  1565. pos=self.ui.menutool, separator=False)
  1566. self.optimal_tool = ToolOptimal(self)
  1567. self.optimal_tool.install(icon=QtGui.QIcon(self.resource_location + '/open_excellon32.png'),
  1568. pos=self.ui.menutool, separator=True)
  1569. self.move_tool = ToolMove(self)
  1570. self.move_tool.install(icon=QtGui.QIcon(self.resource_location + '/move16.png'), pos=self.ui.menuedit,
  1571. before=self.ui.menueditorigin, separator=True)
  1572. self.cutout_tool = CutOut(self)
  1573. self.cutout_tool.install(icon=QtGui.QIcon(self.resource_location + '/cut16_bis.png'), pos=self.ui.menutool,
  1574. before=self.sub_tool.menuAction)
  1575. self.ncclear_tool = NonCopperClear(self)
  1576. self.ncclear_tool.install(icon=QtGui.QIcon(self.resource_location + '/ncc16.png'), pos=self.ui.menutool,
  1577. before=self.sub_tool.menuAction, separator=True)
  1578. self.paint_tool = ToolPaint(self)
  1579. self.paint_tool.install(icon=QtGui.QIcon(self.resource_location + '/paint16.png'), pos=self.ui.menutool,
  1580. before=self.sub_tool.menuAction, separator=True)
  1581. self.isolation_tool = ToolIsolation(self)
  1582. self.isolation_tool.install(icon=QtGui.QIcon(self.resource_location + '/iso_16.png'), pos=self.ui.menutool,
  1583. before=self.sub_tool.menuAction, separator=True)
  1584. self.copper_thieving_tool = ToolCopperThieving(self)
  1585. self.copper_thieving_tool.install(icon=QtGui.QIcon(self.resource_location + '/copperfill32.png'),
  1586. pos=self.ui.menutool)
  1587. self.fiducial_tool = ToolFiducials(self)
  1588. self.fiducial_tool.install(icon=QtGui.QIcon(self.resource_location + '/fiducials_32.png'),
  1589. pos=self.ui.menutool)
  1590. self.qrcode_tool = QRCode(self)
  1591. self.qrcode_tool.install(icon=QtGui.QIcon(self.resource_location + '/qrcode32.png'),
  1592. pos=self.ui.menutool)
  1593. self.punch_tool = ToolPunchGerber(self)
  1594. self.punch_tool.install(icon=QtGui.QIcon(self.resource_location + '/punch32.png'), pos=self.ui.menutool)
  1595. self.invert_tool = ToolInvertGerber(self)
  1596. self.invert_tool.install(icon=QtGui.QIcon(self.resource_location + '/invert32.png'), pos=self.ui.menutool)
  1597. self.corners_tool = ToolCorners(self)
  1598. self.corners_tool.install(icon=QtGui.QIcon(self.resource_location + '/corners_32.png'), pos=self.ui.menutool)
  1599. self.etch_tool = ToolEtchCompensation(self)
  1600. self.etch_tool.install(icon=QtGui.QIcon(self.resource_location + '/etch_32.png'), pos=self.ui.menutool)
  1601. self.transform_tool = ToolTransform(self)
  1602. self.transform_tool.install(icon=QtGui.QIcon(self.resource_location + '/transform.png'),
  1603. pos=self.ui.menuoptions, separator=True)
  1604. self.properties_tool = Properties(self)
  1605. self.properties_tool.install(icon=QtGui.QIcon(self.resource_location + '/properties32.png'),
  1606. pos=self.ui.menuoptions)
  1607. self.pdf_tool = ToolPDF(self)
  1608. self.pdf_tool.install(icon=QtGui.QIcon(self.resource_location + '/pdf32.png'),
  1609. pos=self.ui.menufileimport,
  1610. separator=True)
  1611. self.image_tool = ToolImage(self)
  1612. self.image_tool.install(icon=QtGui.QIcon(self.resource_location + '/image32.png'),
  1613. pos=self.ui.menufileimport,
  1614. separator=True)
  1615. self.pcb_wizard_tool = PcbWizard(self)
  1616. self.pcb_wizard_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill32.png'),
  1617. pos=self.ui.menufileimport)
  1618. self.log.debug("Tools are installed.")
  1619. def remove_tools(self):
  1620. """
  1621. Will remove all the actions in the Tool menu.
  1622. :return: None
  1623. """
  1624. for act in self.ui.menutool.actions():
  1625. self.ui.menutool.removeAction(act)
  1626. def init_tools(self):
  1627. """
  1628. Initialize the Tool tab in the notebook side of the central widget.
  1629. Remove the actions in the Tools menu.
  1630. Instantiate again the FlatCAM tools (plugins).
  1631. All this is required when changing the layout: standard, compact etc.
  1632. :return: None
  1633. """
  1634. log.debug("init_tools()")
  1635. # delete the data currently in the Tools Tab and the Tab itself
  1636. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1637. if widget is not None:
  1638. widget.deleteLater()
  1639. self.ui.notebook.removeTab(2)
  1640. # rebuild the Tools Tab
  1641. self.ui.tool_tab = QtWidgets.QWidget()
  1642. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1643. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1644. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  1645. self.ui.tool_scroll_area = VerticalScrollArea()
  1646. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1647. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1648. # first remove all of them
  1649. self.remove_tools()
  1650. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  1651. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon(self.resource_location + '/shell16.png'),
  1652. '&Command Line\tS')
  1653. self.ui.menutoolshell.triggered.connect(self.ui.toggle_shell_ui)
  1654. # third install all of them
  1655. try:
  1656. self.install_tools()
  1657. except AttributeError:
  1658. pass
  1659. self.log.debug("Tools are initialized.")
  1660. # def parse_system_fonts(self):
  1661. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1662. # 'params': []})
  1663. def connect_tools_signals_to_toolbar(self, ui):
  1664. ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  1665. ui.cal_btn.triggered.connect(lambda: self.cal_exc_tool.run(toggle=True))
  1666. ui.align_btn.triggered.connect(lambda: self.align_objects_tool.run(toggle=True))
  1667. ui.extract_btn.triggered.connect(lambda: self.edrills_tool.run(toggle=True))
  1668. ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  1669. ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  1670. ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  1671. ui.isolation_btn.triggered.connect(lambda: self.isolation_tool.run(toggle=True))
  1672. ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  1673. ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  1674. ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  1675. ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  1676. ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  1677. ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  1678. ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  1679. ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  1680. ui.qrcode_btn.triggered.connect(lambda: self.qrcode_tool.run(toggle=True))
  1681. ui.copperfill_btn.triggered.connect(lambda: self.copper_thieving_tool.run(toggle=True))
  1682. ui.fiducials_btn.triggered.connect(lambda: self.fiducial_tool.run(toggle=True))
  1683. ui.punch_btn.triggered.connect(lambda: self.punch_tool.run(toggle=True))
  1684. ui.invert_btn.triggered.connect(lambda: self.invert_tool.run(toggle=True))
  1685. ui.corners_tool_btn.triggered.connect(lambda: self.corners_tool.run(toggle=True))
  1686. ui.etch_btn.triggered.connect(lambda: self.etch_tool.run(toggle=True))
  1687. def connect_toolbar_signals(self, ui):
  1688. """
  1689. Reconnect the signals to the actions in the toolbar.
  1690. This has to be done each time after the FlatCAM tools are removed/installed.
  1691. :return: None
  1692. """
  1693. # Toolbar
  1694. # File Toolbar Signals
  1695. # ui.file_new_btn.triggered.connect(self.on_file_new)
  1696. ui.file_open_btn.triggered.connect(self.on_file_openproject)
  1697. ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  1698. ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  1699. ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  1700. # View Toolbar Signals
  1701. ui.clear_plot_btn.triggered.connect(self.clear_plots)
  1702. ui.replot_btn.triggered.connect(self.plot_all)
  1703. ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  1704. ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1705. ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1706. # Edit Toolbar Signals
  1707. ui.editgeo_btn.triggered.connect(self.object2editor)
  1708. ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  1709. ui.copy_btn.triggered.connect(self.on_copy_command)
  1710. ui.delete_btn.triggered.connect(self.on_delete)
  1711. ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  1712. ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  1713. ui.origin_btn.triggered.connect(self.on_set_origin)
  1714. ui.move2origin_btn.triggered.connect(self.on_move2origin)
  1715. ui.jmp_btn.triggered.connect(self.on_jump_to)
  1716. ui.locate_btn.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  1717. # Scripting Toolbar Signals
  1718. ui.shell_btn.triggered.connect(ui.toggle_shell_ui)
  1719. ui.new_script_btn.triggered.connect(self.on_filenewscript)
  1720. ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  1721. ui.run_script_btn.triggered.connect(self.on_filerunscript)
  1722. # Tools Toolbar Signals
  1723. try:
  1724. self.connect_tools_signals_to_toolbar(ui=ui)
  1725. except Exception as err:
  1726. log.debug("App.connect_toolbar_signals() tools signals -> %s" % str(err))
  1727. def object2editor(self):
  1728. """
  1729. Send the current Geometry, Gerber, Excellon object or CNCJob (if any) into the it's editor.
  1730. :return: None
  1731. """
  1732. self.defaults.report_usage("object2editor()")
  1733. # disable the objects menu as it may interfere with the appEditors
  1734. self.ui.menuobjects.setDisabled(True)
  1735. edited_object = self.collection.get_active()
  1736. if isinstance(edited_object, GerberObject) or isinstance(edited_object, GeometryObject) or \
  1737. isinstance(edited_object, ExcellonObject) or isinstance(edited_object, CNCJobObject):
  1738. pass
  1739. else:
  1740. self.inform.emit('[WARNING_NOTCL] %s' % _("Select a Geometry, Gerber, Excellon or CNCJob Object to edit."))
  1741. return
  1742. if isinstance(edited_object, GeometryObject):
  1743. # store the Geometry Editor Toolbar visibility before entering in the Editor
  1744. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  1745. # we set the notebook to hidden
  1746. # self.ui.splitter.setSizes([0, 1])
  1747. if edited_object.multigeo is True:
  1748. sel_rows = [item.row() for item in edited_object.ui.geo_tools_table.selectedItems()]
  1749. if len(sel_rows) > 1:
  1750. self.inform.emit('[WARNING_NOTCL] %s' %
  1751. _("Simultaneous editing of tools geometry in a MultiGeo Geometry "
  1752. "is not possible.\n"
  1753. "Edit only one geometry at a time."))
  1754. if not sel_rows:
  1755. self.inform.emit('[WARNING_NOTCL] %s.' % _("No Tool Selected"))
  1756. return
  1757. # determine the tool dia of the selected tool
  1758. selected_tooldia = float(edited_object.ui.geo_tools_table.item(sel_rows[0], 1).text())
  1759. # now find the key in the edited_object.tools that has this tooldia
  1760. multi_tool = 1
  1761. for tool in edited_object.tools:
  1762. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  1763. multi_tool = tool
  1764. break
  1765. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  1766. else:
  1767. self.geo_editor.edit_fcgeometry(edited_object)
  1768. # set call source to the Editor we go into
  1769. self.call_source = 'geo_editor'
  1770. elif isinstance(edited_object, ExcellonObject):
  1771. # store the Excellon Editor Toolbar visibility before entering in the Editor
  1772. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  1773. if self.ui.splitter.sizes()[0] == 0:
  1774. self.ui.splitter.setSizes([1, 1])
  1775. self.exc_editor.edit_fcexcellon(edited_object)
  1776. # set call source to the Editor we go into
  1777. self.call_source = 'exc_editor'
  1778. elif isinstance(edited_object, GerberObject):
  1779. # store the Gerber Editor Toolbar visibility before entering in the Editor
  1780. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  1781. if self.ui.splitter.sizes()[0] == 0:
  1782. self.ui.splitter.setSizes([1, 1])
  1783. self.grb_editor.edit_fcgerber(edited_object)
  1784. # set call source to the Editor we go into
  1785. self.call_source = 'grb_editor'
  1786. # reset the following variables so the UI is built again after edit
  1787. edited_object.ui_build = False
  1788. edited_object.build_aperture_storage = False
  1789. elif isinstance(edited_object, CNCJobObject):
  1790. if self.ui.splitter.sizes()[0] == 0:
  1791. self.ui.splitter.setSizes([1, 1])
  1792. edited_object.on_edit_code_click()
  1793. return
  1794. # make sure that we can't select another object while in Editor Mode:
  1795. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1796. self.ui.project_frame.setDisabled(True)
  1797. # delete any selection shape that might be active as they are not relevant in Editor
  1798. self.delete_selection_shape()
  1799. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  1800. self.ui.plot_tab_area.protectTab(0)
  1801. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor is activated ..."))
  1802. self.should_we_save = True
  1803. def editor2object(self, cleanup=None):
  1804. """
  1805. Transfers the Geometry or Excellon from it's editor to the current object.
  1806. :return: None
  1807. """
  1808. self.defaults.report_usage("editor2object()")
  1809. # re-enable the objects menu that was disabled on entry in Editor mode
  1810. self.ui.menuobjects.setDisabled(False)
  1811. # do not update a geometry or excellon object unless it comes out of an editor
  1812. if self.call_source != 'app':
  1813. edited_obj = self.collection.get_active()
  1814. if cleanup is None:
  1815. msgbox = QtWidgets.QMessageBox()
  1816. msgbox.setText(_("Do you want to save the edited object?"))
  1817. msgbox.setWindowTitle(_("Close Editor"))
  1818. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  1819. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  1820. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  1821. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  1822. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  1823. msgbox.setDefaultButton(bt_yes)
  1824. msgbox.exec_()
  1825. response = msgbox.clickedButton()
  1826. if response == bt_yes:
  1827. # clean the Tools Tab
  1828. self.ui.tool_scroll_area.takeWidget()
  1829. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1830. self.ui.notebook.setTabText(2, "Tool")
  1831. if isinstance(edited_obj, GeometryObject):
  1832. obj_type = "Geometry"
  1833. self.geo_editor.update_fcgeometry(edited_obj)
  1834. # self.geo_editor.update_options(edited_obj)
  1835. # restore GUI to the Selected TAB
  1836. # Remove anything else in the appGUI
  1837. self.ui.tool_scroll_area.takeWidget()
  1838. # update the geo object options so it is including the bounding box values
  1839. try:
  1840. xmin, ymin, xmax, ymax = edited_obj.bounds(flatten=True)
  1841. edited_obj.options['xmin'] = xmin
  1842. edited_obj.options['ymin'] = ymin
  1843. edited_obj.options['xmax'] = xmax
  1844. edited_obj.options['ymax'] = ymax
  1845. except AttributeError as e:
  1846. self.inform.emit('[WARNING] %s' % _("Object empty after edit."))
  1847. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  1848. edited_obj.build_ui()
  1849. edited_obj.plot()
  1850. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1851. elif isinstance(edited_obj, GerberObject):
  1852. obj_type = "Gerber"
  1853. self.grb_editor.update_fcgerber()
  1854. # self.grb_editor.update_options(edited_obj)
  1855. # delete the old object (the source object) if it was an empty one
  1856. try:
  1857. if len(edited_obj.solid_geometry) == 0:
  1858. old_name = edited_obj.options['name']
  1859. self.collection.delete_by_name(old_name)
  1860. except TypeError:
  1861. # if the solid_geometry is a single Polygon the len() will not work
  1862. # in any case, falling here means that we have something in the solid_geometry, even if only
  1863. # a single Polygon, therefore we pass this
  1864. pass
  1865. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1866. # restore GUI to the Selected TAB
  1867. # Remove anything else in the appGUI
  1868. self.ui.selected_scroll_area.takeWidget()
  1869. elif isinstance(edited_obj, ExcellonObject):
  1870. obj_type = "Excellon"
  1871. self.exc_editor.update_fcexcellon(edited_obj)
  1872. # self.exc_editor.update_options(edited_obj)
  1873. # restore GUI to the Selected TAB
  1874. # Remove anything else in the appGUI
  1875. self.ui.tool_scroll_area.takeWidget()
  1876. # delete the old object (the source object) if it was an empty one
  1877. if len(edited_obj.drills) == 0 and len(edited_obj.slots) == 0:
  1878. old_name = edited_obj.options['name']
  1879. self.collection.delete_by_name(name=old_name)
  1880. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1881. else:
  1882. self.inform.emit('[WARNING_NOTCL] %s' %
  1883. _("Select a Gerber, Geometry or Excellon Object to update."))
  1884. return
  1885. self.inform.emit('[selected] %s %s' % (obj_type, _("is updated, returning to App...")))
  1886. elif response == bt_no:
  1887. # clean the Tools Tab
  1888. self.ui.tool_scroll_area.takeWidget()
  1889. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1890. self.ui.notebook.setTabText(2, "Tool")
  1891. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor exited. Editor content was not saved."))
  1892. if isinstance(edited_obj, GeometryObject):
  1893. self.geo_editor.deactivate()
  1894. edited_obj.build_ui()
  1895. edited_obj.plot()
  1896. elif isinstance(edited_obj, GerberObject):
  1897. self.grb_editor.deactivate_grb_editor()
  1898. edited_obj.build_ui()
  1899. elif isinstance(edited_obj, ExcellonObject):
  1900. self.exc_editor.deactivate()
  1901. edited_obj.build_ui()
  1902. else:
  1903. self.inform.emit('[WARNING_NOTCL] %s' %
  1904. _("Select a Gerber, Geometry or Excellon Object to update."))
  1905. return
  1906. elif response == bt_cancel:
  1907. return
  1908. # edited_obj.set_ui(edited_obj.ui_type(decimals=self.decimals))
  1909. # edited_obj.build_ui()
  1910. # Switch notebook to Selected page
  1911. # self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  1912. else:
  1913. if isinstance(edited_obj, GeometryObject):
  1914. self.geo_editor.deactivate()
  1915. elif isinstance(edited_obj, GerberObject):
  1916. self.grb_editor.deactivate_grb_editor()
  1917. elif isinstance(edited_obj, ExcellonObject):
  1918. self.exc_editor.deactivate()
  1919. else:
  1920. self.inform.emit('[WARNING_NOTCL] %s' %
  1921. _("Select a Gerber, Geometry or Excellon Object to update."))
  1922. return
  1923. # if notebook is hidden we show it
  1924. if self.ui.splitter.sizes()[0] == 0:
  1925. self.ui.splitter.setSizes([1, 1])
  1926. # restore the call_source to app
  1927. self.call_source = 'app'
  1928. # edited_obj.plot()
  1929. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  1930. self.ui.plot_tab_area.protectTab(0)
  1931. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  1932. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1933. self.ui.project_frame.setDisabled(False)
  1934. def get_last_folder(self):
  1935. """
  1936. Get the folder path from where the last file was opened.
  1937. :return: String, last opened folder path
  1938. """
  1939. return self.defaults["global_last_folder"]
  1940. def get_last_save_folder(self):
  1941. """
  1942. Get the folder path from where the last file was saved.
  1943. :return: String, last saved folder path
  1944. """
  1945. loc = self.defaults["global_last_save_folder"]
  1946. if loc is None:
  1947. loc = self.defaults["global_last_folder"]
  1948. if loc is None:
  1949. loc = os.path.dirname(__file__)
  1950. return loc
  1951. @QtCore.pyqtSlot(str)
  1952. @QtCore.pyqtSlot(str, bool)
  1953. def info(self, msg, shell_echo=True):
  1954. """
  1955. Informs the user. Normally on the status bar, optionally
  1956. also on the shell.
  1957. :param msg: Text to write.
  1958. :type msg: str
  1959. :param shell_echo: Control if to display the message msg in the Shell
  1960. :type shell_echo: bool
  1961. :return: None
  1962. """
  1963. # Type of message in brackets at the beginning of the message.
  1964. match = re.search(r"\[(.*)\](.*)", msg)
  1965. if match:
  1966. level = match.group(1)
  1967. msg_ = match.group(2)
  1968. self.ui.fcinfo.set_status(str(msg_), level=level)
  1969. if shell_echo is True:
  1970. if level.lower() == "error":
  1971. self.shell_message(msg, error=True, show=True)
  1972. elif level.lower() == "warning":
  1973. self.shell_message(msg, warning=True, show=True)
  1974. elif level.lower() == "error_notcl":
  1975. self.shell_message(msg, error=True, show=False)
  1976. elif level.lower() == "warning_notcl":
  1977. self.shell_message(msg, warning=True, show=False)
  1978. elif level.lower() == "success":
  1979. self.shell_message(msg, success=True, show=False)
  1980. elif level.lower() == "selected":
  1981. self.shell_message(msg, selected=True, show=False)
  1982. else:
  1983. self.shell_message(msg, show=False)
  1984. else:
  1985. self.ui.fcinfo.set_status(str(msg), level="info")
  1986. # make sure that if the message is to clear the infobar with a space
  1987. # is not printed over and over on the shell
  1988. if msg != '' and shell_echo is True:
  1989. self.shell_message(msg)
  1990. def info_shell(self, msg):
  1991. self.shell_message(msg=msg)
  1992. def on_import_preferences(self):
  1993. """
  1994. Loads the application default settings from a saved file into
  1995. ``self.defaults`` dictionary.
  1996. :return: None
  1997. """
  1998. self.defaults.report_usage("on_import_preferences")
  1999. App.log.debug("App.on_import_preferences()")
  2000. # Show file chooser
  2001. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  2002. try:
  2003. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2004. directory=self.data_path,
  2005. filter=filter_)
  2006. except TypeError:
  2007. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2008. filter=filter_)
  2009. filename = str(filename)
  2010. if filename == "":
  2011. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2012. return
  2013. # Load in the defaults from the chosen file
  2014. self.defaults.load(filename=filename)
  2015. self.preferencesUiManager.on_preferences_edited()
  2016. self.inform.emit('[success] %s: %s' % (_("Imported Defaults from"), filename))
  2017. def on_export_preferences(self):
  2018. """
  2019. Save the defaults dictionary to a file.
  2020. :return: None
  2021. """
  2022. self.defaults.report_usage("on_export_preferences")
  2023. App.log.debug("on_export_preferences()")
  2024. # defaults_file_content = None
  2025. # Show file chooser
  2026. date = str(datetime.today()).rpartition('.')[0]
  2027. date = ''.join(c for c in date if c not in ':-')
  2028. date = date.replace(' ', '_')
  2029. filter__ = "Config File .FlatConfig (*.FlatConfig);;All Files (*.*)"
  2030. try:
  2031. filename, _f = FCFileSaveDialog.get_saved_filename(
  2032. caption=_("Export FlatCAM Preferences"),
  2033. directory=self.data_path + '/preferences_' + date,
  2034. ext_filter=filter__
  2035. )
  2036. except TypeError:
  2037. filename, _f = FCFileSaveDialog.get_saved_filename(
  2038. caption=_("Export FlatCAM Preferences"), ext_filter=filter__)
  2039. filename = str(filename)
  2040. if filename == "":
  2041. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2042. return
  2043. # Update options
  2044. self.preferencesUiManager.defaults_read_form()
  2045. self.defaults.propagate_defaults()
  2046. # Save update options
  2047. try:
  2048. self.defaults.write(filename=filename)
  2049. except Exception:
  2050. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2051. return
  2052. if self.defaults["global_open_style"] is False:
  2053. self.file_opened.emit("preferences", filename)
  2054. self.file_saved.emit("preferences", filename)
  2055. self.inform.emit('[success] %s: %s' % (_("Exported preferences to"), filename))
  2056. def save_to_file(self, content_to_save, txt_content):
  2057. """
  2058. Save something to a file.
  2059. :return: None
  2060. """
  2061. self.defaults.report_usage("save_to_file")
  2062. App.log.debug("save_to_file()")
  2063. self.date = str(datetime.today()).rpartition('.')[0]
  2064. self.date = ''.join(c for c in self.date if c not in ':-')
  2065. self.date = self.date.replace(' ', '_')
  2066. filter__ = "HTML File .html (*.html);;TXT File .txt (*.txt);;All Files (*.*)"
  2067. path_to_save = self.defaults["global_last_save_folder"] if \
  2068. self.defaults["global_last_save_folder"] is not None else self.data_path
  2069. try:
  2070. filename, _f = FCFileSaveDialog.get_saved_filename(
  2071. caption=_("Save to file"),
  2072. directory=path_to_save + '/file_' + self.date,
  2073. ext_filter=filter__
  2074. )
  2075. except TypeError:
  2076. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save to file"), ext_filter=filter__)
  2077. filename = str(filename)
  2078. if filename == "":
  2079. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2080. return
  2081. else:
  2082. try:
  2083. with open(filename, 'w') as f:
  2084. ___ = f.read()
  2085. except PermissionError:
  2086. self.inform.emit('[WARNING] %s' %
  2087. _("Permission denied, saving not possible.\n"
  2088. "Most likely another app is holding the file open and not accessible."))
  2089. return
  2090. except IOError:
  2091. App.log.debug('Creating a new file ...')
  2092. f = open(filename, 'w')
  2093. f.close()
  2094. except Exception:
  2095. e = sys.exc_info()[0]
  2096. App.log.error("Could not load the file.")
  2097. App.log.error(str(e))
  2098. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load the file."))
  2099. return
  2100. # Save content
  2101. if filename.rpartition('.')[2].lower() == 'html':
  2102. file_content = content_to_save
  2103. else:
  2104. file_content = txt_content
  2105. try:
  2106. with open(filename, "w") as f:
  2107. f.write(file_content)
  2108. except Exception:
  2109. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2110. return
  2111. self.inform.emit('[success] %s: %s' % (_("Exported file to"), filename))
  2112. def register_recent(self, kind, filename):
  2113. """
  2114. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  2115. dictionary.
  2116. :param kind: type of file that was opened
  2117. :param filename: the path and file name for the file that was opened
  2118. :return:
  2119. """
  2120. self.log.debug("register_recent()")
  2121. self.log.debug(" %s" % kind)
  2122. self.log.debug(" %s" % filename)
  2123. record = {'kind': str(kind), 'filename': str(filename)}
  2124. if record in self.recent:
  2125. return
  2126. if record in self.recent_projects:
  2127. return
  2128. if record['kind'] == 'project':
  2129. self.recent_projects.insert(0, record)
  2130. else:
  2131. self.recent.insert(0, record)
  2132. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2133. self.recent.pop()
  2134. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  2135. self.recent_projects.pop()
  2136. try:
  2137. f = open(self.data_path + '/recent.json', 'w')
  2138. except IOError:
  2139. App.log.error("Failed to open recent items file for writing.")
  2140. self.inform.emit('[ERROR_NOTCL] %s' %
  2141. _('Failed to open recent files file for writing.'))
  2142. return
  2143. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2144. f.close()
  2145. try:
  2146. fp = open(self.data_path + '/recent_projects.json', 'w')
  2147. except IOError:
  2148. App.log.error("Failed to open recent items file for writing.")
  2149. self.inform.emit('[ERROR_NOTCL] %s' %
  2150. _('Failed to open recent projects file for writing.'))
  2151. return
  2152. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  2153. fp.close()
  2154. # Re-build the recent items menu
  2155. self.setup_recent_items()
  2156. def on_about(self):
  2157. """
  2158. Displays the "about" dialog found in the Menu --> Help.
  2159. :return: None
  2160. """
  2161. self.defaults.report_usage("on_about")
  2162. version = self.version
  2163. version_date = self.version_date
  2164. beta = self.beta
  2165. class AboutDialog(QtWidgets.QDialog):
  2166. def __init__(self, app, parent=None):
  2167. QtWidgets.QDialog.__init__(self, parent)
  2168. self.app = app
  2169. # Icon and title
  2170. self.setWindowIcon(parent.app_icon)
  2171. self.setWindowTitle(_("About FlatCAM"))
  2172. self.resize(600, 200)
  2173. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  2174. # self.setStyleSheet(
  2175. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  2176. # "background-attachment: fixed"
  2177. # )
  2178. # bgimage = QtGui.QImage(self.resource_location + '/flatcam_icon256.png')
  2179. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  2180. # palette = QtGui.QPalette()
  2181. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  2182. # self.setPalette(palette)
  2183. logo = QtWidgets.QLabel()
  2184. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/flatcam_icon256.png'))
  2185. title = QtWidgets.QLabel(
  2186. "<font size=8><B>FlatCAM</B></font><BR>"
  2187. "{title}<BR>"
  2188. "<BR>"
  2189. "<BR>"
  2190. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  2191. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  2192. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  2193. "<B>{issue}</B></a><BR>".format(
  2194. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  2195. devel=_("Development"),
  2196. down=_("DOWNLOAD"),
  2197. issue=_("Issue tracker"))
  2198. )
  2199. title.setOpenExternalLinks(True)
  2200. closebtn = QtWidgets.QPushButton(_("Close"))
  2201. tab_widget = QtWidgets.QTabWidget()
  2202. description_label = QtWidgets.QLabel(
  2203. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  2204. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  2205. version=version,
  2206. beta=('BETA' if beta else ''),
  2207. date=version_date,
  2208. arch=platform.architecture()[0])
  2209. )
  2210. description_label.setOpenExternalLinks(True)
  2211. lic_lbl_header = QtWidgets.QLabel(
  2212. '%s:<br>%s<br>' % (
  2213. _('Licensed under the MIT license'),
  2214. "<a href = \"http://www.opensource.org/licenses/mit-license.php\">"
  2215. "http://www.opensource.org/licenses/mit-license.php</a>"
  2216. )
  2217. )
  2218. lic_lbl_header.setOpenExternalLinks(True)
  2219. lic_lbl_body = QtWidgets.QLabel(
  2220. _(
  2221. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  2222. 'of this software and associated documentation files (the "Software"), to deal\n'
  2223. 'in the Software without restriction, including without limitation the rights\n'
  2224. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  2225. 'copies of the Software, and to permit persons to whom the Software is\n'
  2226. 'furnished to do so, subject to the following conditions:\n\n'
  2227. 'The above copyright notice and this permission notice shall be included in\n'
  2228. 'all copies or substantial portions of the Software.\n\n'
  2229. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  2230. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  2231. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  2232. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  2233. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  2234. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  2235. 'THE SOFTWARE.'
  2236. )
  2237. )
  2238. attributions_label = QtWidgets.QLabel(
  2239. _(
  2240. 'Some of the icons used are from the following sources:<br>'
  2241. '<div>Icons by <a href="https://www.flaticon.com/authors/freepik" '
  2242. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  2243. 'title="Flaticon">www.flaticon.com</a></div>'
  2244. '<div>Icons by <a target="_blank" href="https://icons8.com">Icons8</a></div>'
  2245. 'Icons by <a href="http://www.onlinewebfonts.com">oNline Web Fonts</a>'
  2246. '<div>Icons by <a href="https://www.flaticon.com/authors/pixel-perfect" '
  2247. 'title="Pixel perfect">Pixel perfect</a> from <a href="https://www.flaticon.com/" '
  2248. 'title="Flaticon">www.flaticon.com</a></div>'
  2249. )
  2250. )
  2251. attributions_label.setOpenExternalLinks(True)
  2252. # layouts
  2253. layout1 = QtWidgets.QVBoxLayout()
  2254. layout1_1 = QtWidgets.QHBoxLayout()
  2255. layout1_2 = QtWidgets.QHBoxLayout()
  2256. layout2 = QtWidgets.QHBoxLayout()
  2257. layout3 = QtWidgets.QHBoxLayout()
  2258. self.setLayout(layout1)
  2259. layout1.addLayout(layout1_1)
  2260. layout1.addLayout(layout1_2)
  2261. layout1.addLayout(layout2)
  2262. layout1.addLayout(layout3)
  2263. layout1_1.addStretch()
  2264. layout1_1.addWidget(description_label)
  2265. layout1_2.addWidget(tab_widget)
  2266. self.splash_tab = QtWidgets.QWidget()
  2267. self.splash_tab.setObjectName("splash_about")
  2268. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  2269. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  2270. tab_widget.addTab(self.splash_tab, _("Splash"))
  2271. self.programmmers_tab = QtWidgets.QWidget()
  2272. self.programmmers_tab.setObjectName("programmers_about")
  2273. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  2274. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  2275. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  2276. self.translators_tab = QtWidgets.QWidget()
  2277. self.translators_tab.setObjectName("translators_about")
  2278. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  2279. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  2280. tab_widget.addTab(self.translators_tab, _("Translators"))
  2281. self.license_tab = QtWidgets.QWidget()
  2282. self.license_tab.setObjectName("license_about")
  2283. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  2284. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  2285. tab_widget.addTab(self.license_tab, _("License"))
  2286. self.attributions_tab = QtWidgets.QWidget()
  2287. self.attributions_tab.setObjectName("attributions_about")
  2288. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  2289. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  2290. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  2291. self.splash_tab_layout.addWidget(logo, stretch=0)
  2292. self.splash_tab_layout.addWidget(title, stretch=1)
  2293. pal = QtGui.QPalette()
  2294. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2295. self.prog_grid_lay = QtWidgets.QGridLayout()
  2296. self.prog_grid_lay.setHorizontalSpacing(20)
  2297. self.prog_grid_lay.setColumnStretch(0, 0)
  2298. self.prog_grid_lay.setColumnStretch(2, 1)
  2299. prog_widget = QtWidgets.QWidget()
  2300. prog_widget.setLayout(self.prog_grid_lay)
  2301. prog_scroll = QtWidgets.QScrollArea()
  2302. prog_scroll.setWidget(prog_widget)
  2303. prog_scroll.setWidgetResizable(True)
  2304. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2305. prog_scroll.setPalette(pal)
  2306. self.programmmers_tab_layout.addWidget(prog_scroll)
  2307. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  2308. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  2309. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  2310. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  2311. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("Program Author")), 1, 1)
  2312. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<>"), 1, 2)
  2313. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  2314. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  2315. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  2316. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("BETA Maintainer >= 2019")), 4, 1)
  2317. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 2)
  2318. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 5, 0)
  2319. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "David Robertson"), 6, 0)
  2320. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 7, 0)
  2321. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Evans"), 8, 0)
  2322. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Victor Benso"), 9, 0)
  2323. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 10, 0)
  2324. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"), 12, 0)
  2325. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lei Zheng"), 13, 0)
  2326. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Leandro Heck"), 14, 0)
  2327. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marco A Quezada"), 15, 0)
  2328. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 16, 0)
  2329. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Cedric Dussud"), 20, 0)
  2330. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Hemingway"), 22, 0)
  2331. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Damian Wrobel"), 24, 0)
  2332. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Daniel Sallin"), 28, 0)
  2333. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 32, 0)
  2334. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Bruno Vunderl"), 40, 0)
  2335. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Gonzalo Lopez"), 42, 0)
  2336. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jakob Staudt"), 45, 0)
  2337. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Smith"), 49, 0)
  2338. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 52, 0)
  2339. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Barnaby Walters"), 55, 0)
  2340. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Steve Martina"), 57, 0)
  2341. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Thomas Duffin"), 59, 0)
  2342. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 61, 0)
  2343. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 63, 0)
  2344. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Alex Lazar"), 64, 0)
  2345. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Breneman"), 65, 0)
  2346. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Eric Varsanyi"), 67, 0)
  2347. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lubos Medovarsky"), 69, 0)
  2348. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 74, 0)
  2349. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Idechix"), 100, 0)
  2350. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@SM"), 101, 0)
  2351. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@grbf"), 102, 0)
  2352. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Symonty"), 103, 0)
  2353. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@mgix"), 104, 0)
  2354. self.translator_grid_lay = QtWidgets.QGridLayout()
  2355. self.translator_grid_lay.setColumnStretch(0, 0)
  2356. self.translator_grid_lay.setColumnStretch(1, 0)
  2357. self.translator_grid_lay.setColumnStretch(2, 1)
  2358. self.translator_grid_lay.setColumnStretch(3, 0)
  2359. # trans_widget = QtWidgets.QWidget()
  2360. # trans_widget.setLayout(self.translator_grid_lay)
  2361. # self.translators_tab_layout.addWidget(trans_widget)
  2362. # self.translators_tab_layout.addStretch()
  2363. trans_widget = QtWidgets.QWidget()
  2364. trans_widget.setLayout(self.translator_grid_lay)
  2365. trans_scroll = QtWidgets.QScrollArea()
  2366. trans_scroll.setWidget(trans_widget)
  2367. trans_scroll.setWidgetResizable(True)
  2368. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2369. trans_scroll.setPalette(pal)
  2370. self.translators_tab_layout.addWidget(trans_scroll)
  2371. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  2372. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  2373. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Corrections")), 0, 2)
  2374. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 3)
  2375. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "BR - Portuguese"), 1, 0)
  2376. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  2377. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<carlos.stein@gmail.com>"), 1, 3)
  2378. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  2379. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Michel Maciejewski"), 2, 1)
  2380. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 2, 2)
  2381. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<micmac589@gmail.com>"), 2, 3)
  2382. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Hungarian"), 3, 0)
  2383. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 1)
  2384. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 2)
  2385. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 3)
  2386. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Italian"), 4, 0)
  2387. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Massimiliano Golfetto"), 4, 1)
  2388. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 4, 2)
  2389. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<golfetto.pcb@gmail.com>"), 4, 3)
  2390. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 5, 0)
  2391. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 5, 1)
  2392. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jens Karstedt, Detlef Eckardt"), 5, 2)
  2393. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 5, 3)
  2394. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 6, 0)
  2395. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 6, 1)
  2396. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 6, 3)
  2397. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 7, 0)
  2398. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 7, 1)
  2399. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 7, 3)
  2400. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 8, 0)
  2401. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 8, 1)
  2402. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 8, 2)
  2403. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 8, 3)
  2404. self.translator_grid_lay.setColumnStretch(0, 0)
  2405. self.translators_tab_layout.addStretch()
  2406. self.license_tab_layout.addWidget(lic_lbl_header)
  2407. self.license_tab_layout.addWidget(lic_lbl_body)
  2408. self.license_tab_layout.addStretch()
  2409. self.attributions_tab_layout.addWidget(attributions_label)
  2410. self.attributions_tab_layout.addStretch()
  2411. layout3.addStretch()
  2412. layout3.addWidget(closebtn)
  2413. closebtn.clicked.connect(self.accept)
  2414. AboutDialog(app=self, parent=self.ui).exec_()
  2415. def on_readme(self):
  2416. """
  2417. Displays the "about" dialog found in the Menu --> Help.
  2418. :return: None
  2419. """
  2420. class ReadmeDialog(QtWidgets.QDialog):
  2421. def __init__(self, app, parent=None):
  2422. QtWidgets.QDialog.__init__(self, parent)
  2423. self.app = app
  2424. open_source_link = "<a href = 'https://opensource.org/'<b>Open Source</b></a>"
  2425. new_features_link = "<a href = 'https://bitbucket.org/jpcgt/flatcam/pull-requests/'" \
  2426. "<b>click</b></a>"
  2427. bugs_link = "<a href = 'https://bitbucket.org/jpcgt/flatcam/issues/new'<b>click</b></a>"
  2428. donation_link = "<a href = 'https://www.paypal.com/cgi-bin/webscr?cmd=_" \
  2429. "donations&business=WLTJJ3Q77D98L&currency_code=USD&source=url'<b>click</b></a>"
  2430. # Icon and title
  2431. self.setWindowIcon(parent.app_icon)
  2432. self.setWindowTitle(_("Important Information's"))
  2433. self.resize(750, 375)
  2434. logo = QtWidgets.QLabel()
  2435. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/contribute256.png'))
  2436. # content = QtWidgets.QLabel(
  2437. # "%s<br>"
  2438. # "%s<br><br>"
  2439. # "%s,<br>"
  2440. # "%s<br>"
  2441. # "<ul>"
  2442. # "<li> &nbsp;%s %s</li>"
  2443. # "<li> &nbsp;%s %s</li>"
  2444. # "</ul>"
  2445. # "%s %s.<br>"
  2446. # "%s"
  2447. # "<ul>"
  2448. # "<li> &nbsp;%s &#128077;</li>"
  2449. # "<li> &nbsp;%s &#128513;</li>"
  2450. # "</ul>" %
  2451. # (
  2452. # _("This program is %s and free in a very wide meaning of the word.") % open_source_link,
  2453. # _("Yet it cannot evolve without <b>contributions</b>."),
  2454. # _("If you want to see this application grow and become better and better"),
  2455. # _("you can <b>contribute</b> to the development yourself by:"),
  2456. # _("Pull Requests on the Bitbucket repository, if you are a developer"),
  2457. # new_features_link,
  2458. # _("Bug Reports by providing the steps required to reproduce the bug"),
  2459. # bugs_link,
  2460. # _("If you like or use this program you can make a donation"),
  2461. # donation_link,
  2462. # _("You don't have to make a donation %s, and it is totally optional but:") % donation_link,
  2463. # _("it will be welcomed with joy"),
  2464. # _("it will give me a reason to continue")
  2465. # )
  2466. # )
  2467. content = QtWidgets.QLabel(
  2468. "%s<br>"
  2469. "%s<br><br>"
  2470. "%s,<br>"
  2471. "%s<br>"
  2472. "<ul>"
  2473. "<li> &nbsp;%s %s</li>"
  2474. "<li> &nbsp;%s %s</li>"
  2475. "</ul>" %
  2476. (
  2477. _("This program is %s and free in a very wide meaning of the word.") % open_source_link,
  2478. _("Yet it cannot evolve without <b>contributions</b>."),
  2479. _("If you want to see this application grow and become better and better"),
  2480. _("you can <b>contribute</b> to the development yourself by:"),
  2481. _("Pull Requests on the Bitbucket repository, if you are a developer"),
  2482. new_features_link,
  2483. _("Bug Reports by providing the steps required to reproduce the bug"),
  2484. bugs_link
  2485. )
  2486. )
  2487. content.setOpenExternalLinks(True)
  2488. # palette
  2489. pal = QtGui.QPalette()
  2490. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2491. # layouts
  2492. main_layout = QtWidgets.QVBoxLayout()
  2493. self.setLayout(main_layout)
  2494. tab_layout = QtWidgets.QHBoxLayout()
  2495. buttons_hlay = QtWidgets.QHBoxLayout()
  2496. main_layout.addLayout(tab_layout)
  2497. main_layout.addLayout(buttons_hlay)
  2498. tab_widget = QtWidgets.QTabWidget()
  2499. tab_layout.addWidget(tab_widget)
  2500. closebtn = QtWidgets.QPushButton(_("Close"))
  2501. buttons_hlay.addStretch()
  2502. buttons_hlay.addWidget(closebtn)
  2503. # CONTRIBUTE section
  2504. self.intro_tab = QtWidgets.QWidget()
  2505. self.intro_tab_layout = QtWidgets.QHBoxLayout(self.intro_tab)
  2506. self.intro_tab_layout.setContentsMargins(2, 2, 2, 2)
  2507. tab_widget.addTab(self.intro_tab, _("Contribute"))
  2508. self.grid_lay = QtWidgets.QGridLayout()
  2509. self.grid_lay.setHorizontalSpacing(20)
  2510. self.grid_lay.setColumnStretch(0, 0)
  2511. self.grid_lay.setColumnStretch(1, 1)
  2512. intro_wdg = QtWidgets.QWidget()
  2513. intro_wdg.setLayout(self.grid_lay)
  2514. intro_scroll_area = QtWidgets.QScrollArea()
  2515. intro_scroll_area.setWidget(intro_wdg)
  2516. intro_scroll_area.setWidgetResizable(True)
  2517. intro_scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2518. intro_scroll_area.setPalette(pal)
  2519. self.grid_lay.addWidget(logo, 0, 0)
  2520. self.grid_lay.addWidget(content, 0, 1)
  2521. self.intro_tab_layout.addWidget(intro_scroll_area)
  2522. # LINKS EXCHANGE section
  2523. self.links_tab = QtWidgets.QWidget()
  2524. self.links_tab_layout = QtWidgets.QVBoxLayout(self.links_tab)
  2525. self.links_tab_layout.setContentsMargins(2, 2, 2, 2)
  2526. tab_widget.addTab(self.links_tab, _("Links Exchange"))
  2527. self.links_lay = QtWidgets.QHBoxLayout()
  2528. links_wdg = QtWidgets.QWidget()
  2529. links_wdg.setLayout(self.links_lay)
  2530. links_scroll_area = QtWidgets.QScrollArea()
  2531. links_scroll_area.setWidget(links_wdg)
  2532. links_scroll_area.setWidgetResizable(True)
  2533. links_scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2534. links_scroll_area.setPalette(pal)
  2535. self.links_lay.addWidget(QtWidgets.QLabel('%s' % _("Soon ...")), alignment=QtCore.Qt.AlignCenter)
  2536. self.links_tab_layout.addWidget(links_scroll_area)
  2537. # HOW TO section
  2538. self.howto_tab = QtWidgets.QWidget()
  2539. self.howto_tab_layout = QtWidgets.QVBoxLayout(self.howto_tab)
  2540. self.howto_tab_layout.setContentsMargins(2, 2, 2, 2)
  2541. tab_widget.addTab(self.howto_tab, _("How To's"))
  2542. self.howto_lay = QtWidgets.QHBoxLayout()
  2543. howto_wdg = QtWidgets.QWidget()
  2544. howto_wdg.setLayout(self.howto_lay)
  2545. howto_scroll_area = QtWidgets.QScrollArea()
  2546. howto_scroll_area.setWidget(howto_wdg)
  2547. howto_scroll_area.setWidgetResizable(True)
  2548. howto_scroll_area.setFrameShape(QtWidgets.QFrame.NoFrame)
  2549. howto_scroll_area.setPalette(pal)
  2550. self.howto_lay.addWidget(QtWidgets.QLabel('%s' % _("Soon ...")), alignment=QtCore.Qt.AlignCenter)
  2551. self.howto_tab_layout.addWidget(howto_scroll_area)
  2552. # BUTTONS section
  2553. closebtn.clicked.connect(self.accept)
  2554. ReadmeDialog(app=self, parent=self.ui).exec_()
  2555. def install_bookmarks(self, book_dict=None):
  2556. """
  2557. Install the bookmarks actions in the Help menu -> Bookmarks
  2558. :param book_dict: a dict having the actions text as keys and the weblinks as the values
  2559. :return: None
  2560. """
  2561. if book_dict is None:
  2562. self.defaults["global_bookmarks"].update(
  2563. {
  2564. '1': ['FlatCAM', "http://flatcam.org"],
  2565. '2': ['Backup Site', ""]
  2566. }
  2567. )
  2568. else:
  2569. self.defaults["global_bookmarks"].clear()
  2570. self.defaults["global_bookmarks"].update(book_dict)
  2571. # first try to disconnect if somehow they get connected from elsewhere
  2572. for act in self.ui.menuhelp_bookmarks.actions():
  2573. try:
  2574. act.triggered.disconnect()
  2575. except TypeError:
  2576. pass
  2577. # clear all actions except the last one who is the Bookmark manager
  2578. if act is self.ui.menuhelp_bookmarks.actions()[-1]:
  2579. pass
  2580. else:
  2581. self.ui.menuhelp_bookmarks.removeAction(act)
  2582. bm_limit = int(self.defaults["global_bookmarks_limit"])
  2583. if self.defaults["global_bookmarks"]:
  2584. # order the self.defaults["global_bookmarks"] dict keys by the value as integer
  2585. # the whole convoluted things is because when serializing the self.defaults (on app close or save)
  2586. # the JSON is first making the keys as strings (therefore I have to use strings too
  2587. # or do the conversion :(
  2588. # )
  2589. # and it is ordering them (actually I want that to make the defaults easy to search within) but making
  2590. # the '10' entry jsut after '1' therefore ordering as strings
  2591. sorted_bookmarks = sorted(list(self.defaults["global_bookmarks"].items())[:bm_limit],
  2592. key=lambda x: int(x[0]))
  2593. for entry, bookmark in sorted_bookmarks:
  2594. title = bookmark[0]
  2595. weblink = bookmark[1]
  2596. act = QtWidgets.QAction(parent=self.ui.menuhelp_bookmarks)
  2597. act.setText(title)
  2598. act.setIcon(QtGui.QIcon(self.resource_location + '/link16.png'))
  2599. # from here: https://stackoverflow.com/questions/20390323/pyqt-dynamic-generate-qmenu-action-and-connect
  2600. if title == 'Backup Site' and weblink == "":
  2601. act.triggered.connect(self.on_backup_site)
  2602. else:
  2603. act.triggered.connect(lambda sig, link=weblink: webbrowser.open(link))
  2604. self.ui.menuhelp_bookmarks.insertAction(self.ui.menuhelp_bookmarks_manager, act)
  2605. self.ui.menuhelp_bookmarks_manager.triggered.connect(self.on_bookmarks_manager)
  2606. def on_bookmarks_manager(self):
  2607. """
  2608. Adds the bookmark manager in a Tab in Plot Area
  2609. :return:
  2610. """
  2611. for idx in range(self.ui.plot_tab_area.count()):
  2612. if self.ui.plot_tab_area.tabText(idx) == _("Bookmarks Manager"):
  2613. # there can be only one instance of Bookmark Manager at one time
  2614. return
  2615. # BookDialog(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui).exec_()
  2616. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui)
  2617. self.book_dialog_tab.setObjectName("bookmarks_tab")
  2618. # add the tab if it was closed
  2619. self.ui.plot_tab_area.addTab(self.book_dialog_tab, _("Bookmarks Manager"))
  2620. # delete the absolute and relative position and messages in the infobar
  2621. # self.ui.position_label.setText("")
  2622. # self.ui.rel_position_label.setText("")
  2623. # hide coordinates toolbars in the infobar while in DB
  2624. self.ui.coords_toolbar.hide()
  2625. self.ui.delta_coords_toolbar.hide()
  2626. # Switch plot_area to preferences page
  2627. self.ui.plot_tab_area.setCurrentWidget(self.book_dialog_tab)
  2628. def on_backup_site(self):
  2629. msgbox = QtWidgets.QMessageBox()
  2630. msgbox.setText(_("This entry will resolve to another website if:\n\n"
  2631. "1. FlatCAM.org website is down\n"
  2632. "2. Someone forked FlatCAM project and wants to point\n"
  2633. "to his own website\n\n"
  2634. "If you can't get any informations about FlatCAM beta\n"
  2635. "use the YouTube channel link from the Help menu."))
  2636. msgbox.setWindowTitle(_("Alternative website"))
  2637. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/globe16.png'))
  2638. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  2639. bt_yes = msgbox.addButton(_('Close'), QtWidgets.QMessageBox.YesRole)
  2640. msgbox.setDefaultButton(bt_yes)
  2641. msgbox.exec_()
  2642. # response = msgbox.clickedButton()
  2643. def on_file_savedefaults(self):
  2644. """
  2645. Callback for menu item File->Save Defaults. Saves application default options
  2646. ``self.defaults`` to current_defaults.FlatConfig.
  2647. :return: None
  2648. """
  2649. self.preferencesUiManager.save_defaults()
  2650. def final_save(self):
  2651. """
  2652. Callback for doing a preferences save to file whenever the application is about to quit.
  2653. If the project has changes, it will ask the user to save the project.
  2654. :return: None
  2655. """
  2656. if self.save_in_progress:
  2657. self.inform.emit('[WARNING_NOTCL] %s' % _("Application is saving the project. Please wait ..."))
  2658. return
  2659. if self.should_we_save and self.collection.get_list():
  2660. msgbox = QtWidgets.QMessageBox()
  2661. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  2662. "\n"
  2663. "Do you want to Save the project?"))
  2664. msgbox.setWindowTitle(_("Save changes"))
  2665. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  2666. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  2667. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2668. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2669. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2670. msgbox.setDefaultButton(bt_yes)
  2671. msgbox.exec_()
  2672. response = msgbox.clickedButton()
  2673. if response == bt_yes:
  2674. try:
  2675. self.trayIcon.hide()
  2676. except Exception:
  2677. pass
  2678. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  2679. elif response == bt_no:
  2680. try:
  2681. self.trayIcon.hide()
  2682. except Exception:
  2683. pass
  2684. self.quit_application()
  2685. elif response == bt_cancel:
  2686. return
  2687. else:
  2688. try:
  2689. self.trayIcon.hide()
  2690. except Exception:
  2691. pass
  2692. self.quit_application()
  2693. def quit_application(self):
  2694. """
  2695. Called (as a pyslot or not) when the application is quit.
  2696. :return: None
  2697. """
  2698. # close editors before quiting the app, if they are open
  2699. if self.geo_editor.editor_active is True:
  2700. self.geo_editor.deactivate()
  2701. try:
  2702. self.geo_editor.disconnect()
  2703. except TypeError:
  2704. pass
  2705. log.debug("App.quit_application() --> Geo Editor deactivated.")
  2706. if self.exc_editor.editor_active is True:
  2707. self.exc_editor.deactivate()
  2708. try:
  2709. self.grb_editor.disconnect()
  2710. except TypeError:
  2711. pass
  2712. log.debug("App.quit_application() --> Excellon Editor deactivated.")
  2713. if self.grb_editor.editor_active is True:
  2714. self.grb_editor.deactivate_grb_editor()
  2715. try:
  2716. self.exc_editor.disconnect()
  2717. except TypeError:
  2718. pass
  2719. log.debug("App.quit_application() --> Gerber Editor deactivated.")
  2720. # disconnect the mouse events
  2721. if self.is_legacy:
  2722. self.plotcanvas.graph_event_disconnect(self.mm)
  2723. self.plotcanvas.graph_event_disconnect(self.mp)
  2724. self.plotcanvas.graph_event_disconnect(self.mr)
  2725. self.plotcanvas.graph_event_disconnect(self.mdc)
  2726. self.plotcanvas.graph_event_disconnect(self.kp)
  2727. else:
  2728. self.mm = self.plotcanvas.graph_event_disconnect('mouse_move', self.on_mouse_move_over_plot)
  2729. self.mp = self.plotcanvas.graph_event_disconnect('mouse_press', self.on_mouse_click_over_plot)
  2730. self.mr = self.plotcanvas.graph_event_disconnect('mouse_release', self.on_mouse_click_release_over_plot)
  2731. self.mdc = self.plotcanvas.graph_event_disconnect('mouse_double_click',
  2732. self.on_mouse_double_click_over_plot)
  2733. self.kp = self.plotcanvas.graph_event_disconnect('key_press', self.ui.keyPressEvent)
  2734. self.preferencesUiManager.save_defaults(silent=True)
  2735. log.debug("App.quit_application() --> App Defaults saved.")
  2736. if self.cmd_line_headless != 1:
  2737. # save app state to file
  2738. stgs = QSettings("Open Source", "FlatCAM")
  2739. stgs.setValue('saved_gui_state', self.ui.saveState())
  2740. stgs.setValue('maximized_gui', self.ui.isMaximized())
  2741. stgs.setValue(
  2742. 'language',
  2743. self.ui.general_defaults_form.general_app_group.language_cb.get_value()
  2744. )
  2745. stgs.setValue(
  2746. 'notebook_font_size',
  2747. self.ui.general_defaults_form.general_app_set_group.notebook_font_size_spinner.get_value()
  2748. )
  2749. stgs.setValue(
  2750. 'axis_font_size',
  2751. self.ui.general_defaults_form.general_app_set_group.axis_font_size_spinner.get_value()
  2752. )
  2753. stgs.setValue(
  2754. 'textbox_font_size',
  2755. self.ui.general_defaults_form.general_app_set_group.textbox_font_size_spinner.get_value()
  2756. )
  2757. stgs.setValue(
  2758. 'hud_font_size',
  2759. self.ui.general_defaults_form.general_app_set_group.hud_font_size_spinner.get_value()
  2760. )
  2761. stgs.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  2762. stgs.setValue(
  2763. 'machinist',
  2764. 1 if self.ui.general_defaults_form.general_app_set_group.machinist_cb.get_value() else 0
  2765. )
  2766. # This will write the setting to the platform specific storage.
  2767. del stgs
  2768. log.debug("App.quit_application() --> App UI state saved.")
  2769. # try to quit the Socket opened by ArgsThread class
  2770. try:
  2771. # self.new_launch.thread_exit = True
  2772. # self.new_launch.listener.close()
  2773. self.new_launch.stop.emit()
  2774. except Exception as err:
  2775. log.debug("App.quit_application() --> %s" % str(err))
  2776. # try to quit the QThread that run ArgsThread class
  2777. try:
  2778. # del self.new_launch
  2779. self.listen_th.quit()
  2780. except Exception as e:
  2781. log.debug("App.quit_application() --> %s" % str(e))
  2782. # terminate workers
  2783. # self.workers.__del__()
  2784. self.clear_pool()
  2785. # quit app by signalling for self.kill_app() method
  2786. # self.close_app_signal.emit()
  2787. QtWidgets.qApp.quit()
  2788. # QtCore.QCoreApplication.quit()
  2789. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2790. # we use the following command
  2791. # minor_v = sys.version_info.minor
  2792. # if minor_v < 8:
  2793. # # make sure that the app closes
  2794. # sys.exit(0)
  2795. # else:
  2796. # os._exit(0) # fix to work with Python 3.8
  2797. @staticmethod
  2798. def kill_app():
  2799. QtWidgets.qApp.quit()
  2800. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2801. # we use the following command
  2802. sys.exit(0)
  2803. def on_portable_checked(self, state):
  2804. """
  2805. Callback called when the checkbox in Preferences GUI is checked.
  2806. It will set the application as portable by creating the preferences and recent files in the
  2807. 'config' folder found in the FlatCAM installation folder.
  2808. :param state: boolean, the state of the checkbox when clicked/checked
  2809. :return:
  2810. """
  2811. line_no = 0
  2812. data = None
  2813. if sys.platform != 'win32':
  2814. # this won't work in Linux or MacOS
  2815. return
  2816. # test if the app was frozen and choose the path for the configuration file
  2817. if getattr(sys, "frozen", False) is True:
  2818. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  2819. else:
  2820. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  2821. config_file = current_data_path + '\\configuration.txt'
  2822. try:
  2823. with open(config_file, 'r') as f:
  2824. try:
  2825. data = f.readlines()
  2826. except Exception as e:
  2827. log.debug('App.__init__() -->%s' % str(e))
  2828. return
  2829. except FileNotFoundError:
  2830. pass
  2831. for line in data:
  2832. line = line.strip('\n')
  2833. param = str(line).rpartition('=')
  2834. if param[0] == 'portable':
  2835. break
  2836. line_no += 1
  2837. if state:
  2838. data[line_no] = 'portable=True\n'
  2839. # create the new defauults files
  2840. # create current_defaults.FlatConfig file if there is none
  2841. try:
  2842. f = open(current_data_path + '/current_defaults.FlatConfig')
  2843. f.close()
  2844. except IOError:
  2845. App.log.debug('Creating empty current_defaults.FlatConfig')
  2846. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  2847. json.dump({}, f)
  2848. f.close()
  2849. # create factory_defaults.FlatConfig file if there is none
  2850. try:
  2851. f = open(current_data_path + '/factory_defaults.FlatConfig')
  2852. f.close()
  2853. except IOError:
  2854. App.log.debug('Creating empty factory_defaults.FlatConfig')
  2855. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  2856. json.dump({}, f)
  2857. f.close()
  2858. try:
  2859. f = open(current_data_path + '/recent.json')
  2860. f.close()
  2861. except IOError:
  2862. App.log.debug('Creating empty recent.json')
  2863. f = open(current_data_path + '/recent.json', 'w')
  2864. json.dump([], f)
  2865. f.close()
  2866. try:
  2867. fp = open(current_data_path + '/recent_projects.json')
  2868. fp.close()
  2869. except IOError:
  2870. App.log.debug('Creating empty recent_projects.json')
  2871. fp = open(current_data_path + '/recent_projects.json', 'w')
  2872. json.dump([], fp)
  2873. fp.close()
  2874. # save the current defaults to the new defaults file
  2875. self.preferencesUiManager.save_defaults(silent=True, data_path=current_data_path)
  2876. else:
  2877. data[line_no] = 'portable=False\n'
  2878. with open(config_file, 'w') as f:
  2879. f.writelines(data)
  2880. def on_register_files(self, obj_type=None):
  2881. """
  2882. Called whenever there is a need to register file extensions with FlatCAM.
  2883. Works only in Windows and should be called only when FlatCAM is run in Windows.
  2884. :param obj_type: the type of object to be register for.
  2885. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  2886. :return: None
  2887. """
  2888. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  2889. new_reg_path = 'Software\\Classes\\'
  2890. # find if the current user is admin
  2891. try:
  2892. is_admin = os.getuid() == 0
  2893. except AttributeError:
  2894. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  2895. if is_admin is True:
  2896. root_path = winreg.HKEY_LOCAL_MACHINE
  2897. else:
  2898. root_path = winreg.HKEY_CURRENT_USER
  2899. # create the keys
  2900. def set_reg(name, root_pth, new_reg_path, value):
  2901. try:
  2902. winreg.CreateKey(root_pth, new_reg_path)
  2903. with winreg.OpenKey(root_pth, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  2904. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  2905. return True
  2906. except WindowsError:
  2907. return False
  2908. # delete key in registry
  2909. def delete_reg(root_pth, reg_path, key_to_del):
  2910. key_to_del_path = reg_path + key_to_del
  2911. try:
  2912. winreg.DeleteKey(root_pth, key_to_del_path)
  2913. return True
  2914. except WindowsError:
  2915. return False
  2916. if obj_type is None or obj_type == 'excellon':
  2917. exc_list = \
  2918. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  2919. exc_list = [x for x in exc_list if x != '']
  2920. # register all keys in the Preferences window
  2921. for ext in exc_list:
  2922. new_k = new_reg_path + '.%s' % ext
  2923. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2924. # and unregister those that are no longer in the Preferences windows but are in the file
  2925. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  2926. if ext not in exc_list:
  2927. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2928. # now write the updated extensions to the self.defaults
  2929. # new_ext = ''
  2930. # for ext in exc_list:
  2931. # new_ext = new_ext + ext + ', '
  2932. # self.defaults["fa_excellon"] = new_ext
  2933. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  2934. if obj_type is None or obj_type == 'gcode':
  2935. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  2936. gco_list = [x for x in gco_list if x != '']
  2937. # register all keys in the Preferences window
  2938. for ext in gco_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_gcode"].replace(' ', '').split(','):
  2943. if ext not in gco_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 gco_list:
  2948. # new_ext = new_ext + ext + ', '
  2949. # self.defaults["fa_gcode"] = new_ext
  2950. self.inform.emit('[success] %s' %
  2951. _("Selected GCode file extensions registered with FlatCAM."))
  2952. if obj_type is None or obj_type == 'gerber':
  2953. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  2954. grb_list = [x for x in grb_list if x != '']
  2955. # register all keys in the Preferences window
  2956. for ext in grb_list:
  2957. new_k = new_reg_path + '.%s' % ext
  2958. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  2959. # and unregister those that are no longer in the Preferences windows but are in the file
  2960. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  2961. if ext not in grb_list:
  2962. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  2963. # now write the updated extensions to the self.defaults
  2964. # new_ext = ''
  2965. # for ext in grb_list:
  2966. # new_ext = new_ext + ext + ', '
  2967. # self.defaults["fa_gerber"] = new_ext
  2968. self.inform.emit('[success] %s' %
  2969. _("Selected Gerber file extensions registered with FlatCAM."))
  2970. def add_extension(self, ext_type):
  2971. """
  2972. Add a file extension to the list for a specific object
  2973. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  2974. :return:
  2975. """
  2976. if ext_type == 'excellon':
  2977. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  2978. if new_ext == '':
  2979. return
  2980. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  2981. if new_ext in old_val:
  2982. return
  2983. old_val.append(new_ext)
  2984. old_val.sort()
  2985. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  2986. if ext_type == 'gcode':
  2987. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  2988. if new_ext == '':
  2989. return
  2990. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  2991. if new_ext in old_val:
  2992. return
  2993. old_val.append(new_ext)
  2994. old_val.sort()
  2995. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  2996. if ext_type == 'gerber':
  2997. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  2998. if new_ext == '':
  2999. return
  3000. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3001. if new_ext in old_val:
  3002. return
  3003. old_val.append(new_ext)
  3004. old_val.sort()
  3005. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3006. if ext_type == 'keyword':
  3007. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3008. if new_kw == '':
  3009. return
  3010. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3011. if new_kw in old_val:
  3012. return
  3013. old_val.append(new_kw)
  3014. old_val.sort()
  3015. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3016. # update the self.myKeywords so the model is updated
  3017. self.autocomplete_kw_list = \
  3018. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3019. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3020. self.shell._edit.set_model_data(self.myKeywords)
  3021. def del_extension(self, ext_type):
  3022. """
  3023. Remove a file extension from the list for a specific object
  3024. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3025. :return:
  3026. """
  3027. if ext_type == 'excellon':
  3028. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3029. if new_ext == '':
  3030. return
  3031. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3032. if new_ext not in old_val:
  3033. return
  3034. old_val.remove(new_ext)
  3035. old_val.sort()
  3036. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3037. if ext_type == 'gcode':
  3038. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3039. if new_ext == '':
  3040. return
  3041. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3042. if new_ext not in old_val:
  3043. return
  3044. old_val.remove(new_ext)
  3045. old_val.sort()
  3046. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3047. if ext_type == 'gerber':
  3048. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3049. if new_ext == '':
  3050. return
  3051. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3052. if new_ext not in old_val:
  3053. return
  3054. old_val.remove(new_ext)
  3055. old_val.sort()
  3056. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3057. if ext_type == 'keyword':
  3058. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3059. if new_kw == '':
  3060. return
  3061. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3062. if new_kw not in old_val:
  3063. return
  3064. old_val.remove(new_kw)
  3065. old_val.sort()
  3066. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3067. # update the self.myKeywords so the model is updated
  3068. self.autocomplete_kw_list = \
  3069. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3070. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3071. self.shell._edit.set_model_data(self.myKeywords)
  3072. def restore_extensions(self, ext_type):
  3073. """
  3074. Restore all file extensions associations with FlatCAM, for a specific object
  3075. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3076. :return:
  3077. """
  3078. if ext_type == 'excellon':
  3079. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  3080. # for the ability to open Excellon files with .txt extension
  3081. new_exc_list = deepcopy(self.exc_list)
  3082. try:
  3083. new_exc_list.remove('txt')
  3084. except ValueError:
  3085. pass
  3086. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  3087. if ext_type == 'gcode':
  3088. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  3089. if ext_type == 'gerber':
  3090. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  3091. if ext_type == 'keyword':
  3092. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  3093. # update the self.myKeywords so the model is updated
  3094. self.autocomplete_kw_list = self.default_keywords
  3095. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3096. self.shell._edit.set_model_data(self.myKeywords)
  3097. def delete_all_extensions(self, ext_type):
  3098. """
  3099. Delete all file extensions associations with FlatCAM, for a specific object
  3100. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3101. :return:
  3102. """
  3103. if ext_type == 'excellon':
  3104. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  3105. if ext_type == 'gcode':
  3106. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  3107. if ext_type == 'gerber':
  3108. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  3109. if ext_type == 'keyword':
  3110. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  3111. # update the self.myKeywords so the model is updated
  3112. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  3113. self.shell._edit.set_model_data(self.myKeywords)
  3114. def on_edit_join(self, name=None):
  3115. """
  3116. Callback for Edit->Join. Joins the selected geometry objects into
  3117. a new one.
  3118. :return: None
  3119. """
  3120. self.defaults.report_usage("on_edit_join()")
  3121. obj_name_single = str(name) if name else "Combo_SingleGeo"
  3122. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  3123. geo_type_set = set()
  3124. objs = self.collection.get_selected()
  3125. if len(objs) < 2:
  3126. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3127. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3128. return 'fail'
  3129. for obj in objs:
  3130. geo_type_set.add(obj.multigeo)
  3131. # if len(geo_type_list) == 1 means that all list elements are the same
  3132. if len(geo_type_set) != 1:
  3133. self.inform.emit('[ERROR] %s' %
  3134. _("Failed join. The Geometry objects are of different types.\n"
  3135. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  3136. "convert from one to another and retry joining \n"
  3137. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  3138. "the result may not be what was expected. \n"
  3139. "Check the generated GCODE."))
  3140. return
  3141. fuse_tools = self.defaults["geometry_merge_fuse_tools"]
  3142. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  3143. if True in geo_type_set:
  3144. def initialize(geo_obj, app):
  3145. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=True, fuse_tools=fuse_tools)
  3146. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3147. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3148. for v in geo_obj.tools.values():
  3149. v['data']['name'] = obj_name_multi
  3150. self.app_obj.new_object("geometry", obj_name_multi, initialize)
  3151. else:
  3152. def initialize(geo_obj, app):
  3153. GeometryObject.merge(geo_list=objs, geo_final=geo_obj, multigeo=False, fuse_tools=fuse_tools)
  3154. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3155. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3156. for v in geo_obj.tools.values():
  3157. v['data']['name'] = obj_name_single
  3158. self.app_obj.new_object("geometry", obj_name_single, initialize)
  3159. self.should_we_save = True
  3160. def on_edit_join_exc(self):
  3161. """
  3162. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  3163. a new Excellon.
  3164. :return: None
  3165. """
  3166. self.defaults.report_usage("on_edit_join_exc()")
  3167. objs = self.collection.get_selected()
  3168. for obj in objs:
  3169. if not isinstance(obj, ExcellonObject):
  3170. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Excellon joining works only on Excellon objects."))
  3171. return
  3172. if len(objs) < 2:
  3173. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3174. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3175. return 'fail'
  3176. def initialize(exc_obj, app):
  3177. ExcellonObject.merge(exc_list=objs, exc_final=exc_obj, decimals=self.decimals)
  3178. app.inform.emit('[success] %s.' % _("Excellon merging finished"))
  3179. self.app_obj.new_object("excellon", 'Combo_Excellon', initialize)
  3180. self.should_we_save = True
  3181. def on_edit_join_grb(self):
  3182. """
  3183. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  3184. a new Gerber object.
  3185. :return: None
  3186. """
  3187. self.defaults.report_usage("on_edit_join_grb()")
  3188. objs = self.collection.get_selected()
  3189. for obj in objs:
  3190. if not isinstance(obj, GerberObject):
  3191. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Gerber joining works only on Gerber objects."))
  3192. return
  3193. if len(objs) < 2:
  3194. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3195. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3196. return 'fail'
  3197. def initialize(grb_obj, app):
  3198. GerberObject.merge(grb_list=objs, grb_final=grb_obj)
  3199. app.inform.emit('[success] %s.' % _("Gerber merging finished"))
  3200. self.app_obj.new_object("gerber", 'Combo_Gerber', initialize)
  3201. self.should_we_save = True
  3202. def on_convert_singlegeo_to_multigeo(self):
  3203. """
  3204. Called for converting a Geometry object from single-geo to multi-geo.
  3205. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3206. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3207. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3208. the solid-geometry of that tool.
  3209. :return: None
  3210. """
  3211. self.defaults.report_usage("on_convert_singlegeo_to_multigeo()")
  3212. obj = self.collection.get_active()
  3213. if obj is None:
  3214. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Select a Geometry Object and try again."))
  3215. return
  3216. if not isinstance(obj, GeometryObject):
  3217. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Expected a GeometryObject, got"), type(obj)))
  3218. return
  3219. obj.multigeo = True
  3220. for tooluid, dict_value in obj.tools.items():
  3221. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  3222. if not isinstance(obj.solid_geometry, list):
  3223. obj.solid_geometry = [obj.solid_geometry]
  3224. # obj.solid_geometry[:] = []
  3225. obj.plot()
  3226. self.should_we_save = True
  3227. self.inform.emit('[success] %s' % _("A Geometry object was converted to MultiGeo type."))
  3228. def on_convert_multigeo_to_singlegeo(self):
  3229. """
  3230. Called for converting a Geometry object from multi-geo to single-geo.
  3231. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3232. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3233. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3234. the solid-geometry of that tool.
  3235. :return: None
  3236. """
  3237. self.defaults.report_usage("on_convert_multigeo_to_singlegeo()")
  3238. obj = self.collection.get_active()
  3239. if obj is None:
  3240. self.inform.emit('[ERROR_NOTCL] %s' %
  3241. _("Failed. Select a Geometry Object and try again."))
  3242. return
  3243. if not isinstance(obj, GeometryObject):
  3244. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  3245. (_("Expected a GeometryObject, got"), type(obj)))
  3246. return
  3247. obj.multigeo = False
  3248. total_solid_geometry = []
  3249. for tooluid, dict_value in obj.tools.items():
  3250. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  3251. # clear the original geometry
  3252. dict_value['solid_geometry'][:] = []
  3253. obj.solid_geometry = deepcopy(total_solid_geometry)
  3254. obj.plot()
  3255. self.should_we_save = True
  3256. self.inform.emit('[success] %s' %
  3257. _("A Geometry object was converted to SingleGeo type."))
  3258. def on_defaults_dict_change(self, field):
  3259. """
  3260. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  3261. Edit -> Preferences tab window.
  3262. :param field: the key of the self.defaults dictionary that was changed.
  3263. :return: None
  3264. """
  3265. self.preferencesUiManager.defaults_write_form_field(field=field)
  3266. if field == "units":
  3267. self.set_screen_units(self.defaults['units'])
  3268. def set_screen_units(self, units):
  3269. """
  3270. Set the FlatCAM units on the status bar.
  3271. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  3272. :return: None
  3273. """
  3274. self.ui.units_label.setText("[" + units.lower() + "]")
  3275. def on_toggle_units_click(self):
  3276. try:
  3277. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  3278. except (TypeError, AttributeError):
  3279. pass
  3280. if self.defaults["units"] == 'MM':
  3281. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  3282. else:
  3283. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  3284. self.on_toggle_units(no_pref=True)
  3285. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  3286. lambda: self.on_toggle_units(no_pref=False))
  3287. def on_toggle_units(self, no_pref=False):
  3288. """
  3289. Callback for the Units radio-button change in the Preferences tab.
  3290. Changes the application's default units adn for the project too.
  3291. If changing the project's units, the change propagates to all of
  3292. the objects in the project.
  3293. :return: None
  3294. """
  3295. self.defaults.report_usage("on_toggle_units")
  3296. if self.toggle_units_ignore:
  3297. return
  3298. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3299. # If option is the same, then ignore
  3300. if new_units == self.defaults["units"].upper():
  3301. self.log.debug("on_toggle_units(): Same as previous, ignoring.")
  3302. return
  3303. # Keys in self.defaults for which to scale their values
  3304. dimensions = ['tools_iso_tooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin',
  3305. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f",
  3306. "tools_iso_tool_vtipdia",
  3307. "tools_iso_tool_cutz", "gerber_editor_newdim", "gerber_editor_ma_low",
  3308. "gerber_editor_ma_high",
  3309. 'excellon_cutz', 'excellon_travelz', "excellon_toolchangexy", 'excellon_offset',
  3310. 'excellon_feedrate_z', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  3311. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', 'excellon_endxy',
  3312. "excellon_feedrate_probe", "excellon_milling_dia",
  3313. "excellon_z_pdepth", "excellon_editor_newdia", "excellon_editor_lin_pitch",
  3314. "excellon_editor_slot_lin_pitch", "excellon_editor_slot_length",
  3315. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  3316. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  3317. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', 'geometry_endxy',
  3318. "geometry_extracut_length", "geometry_z_pdepth",
  3319. "geometry_feedrate_probe", "geometry_startz", "geometry_segx", "geometry_segy",
  3320. 'cncjob_tooldia',
  3321. 'tools_paintmargin', 'tools_painttooldia', "tools_paintcutz", "tools_painttipdia",
  3322. "tools_paintnewdia",
  3323. "tools_ncctools", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia",
  3324. "tools_nccnewdia", "tools_ncc_offset_value",
  3325. "tools_2sided_drilldia",
  3326. "tools_film_boundary", "tools_film_scale_stroke",
  3327. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize', "tools_cutout_z",
  3328. "tools_cutout_depthperpass",
  3329. "tools_panelize_constrainx", "tools_panelize_constrainy", "tools_panelize_spacing_columns",
  3330. "tools_panelize_spacing_rows",
  3331. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  3332. "tools_transform_offset_x", "tools_transform_offset_y", "tools_transform_mirror_point",
  3333. "tools_transform_buffer_dis",
  3334. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  3335. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  3336. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  3337. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  3338. "tools_cr_trace_size_val", "tools_cr_c2c_val", "tools_cr_c2o_val", "tools_cr_s2s_val",
  3339. "tools_cr_s2sm_val", "tools_cr_s2o_val", "tools_cr_sm2sm_val", "tools_cr_ri_val",
  3340. "tools_cr_h2h_val", "tools_cr_dh_val",
  3341. "tools_fiducials_dia", "tools_fiducials_margin", "tools_fiducials_line_thickness",
  3342. "tools_copper_thieving_clearance", "tools_copper_thieving_margin",
  3343. "tools_copper_thieving_dots_dia", "tools_copper_thieving_dots_spacing",
  3344. "tools_copper_thieving_squares_size", "tools_copper_thieving_squares_spacing",
  3345. "tools_copper_thieving_lines_size", "tools_copper_thieving_lines_spacing",
  3346. "tools_copper_thieving_rb_margin", "tools_copper_thieving_rb_thickness",
  3347. "tools_copper_thieving_mask_clearance",
  3348. "tools_cal_travelz", "tools_cal_verz", "tools_cal_toolchangez", "tools_cal_toolchange_xy",
  3349. "tools_edrills_hole_fixed_dia", "tools_edrills_circular_ring", "tools_edrills_oblong_ring",
  3350. "tools_edrills_square_ring", "tools_edrills_rectangular_ring", "tools_edrills_others_ring",
  3351. "tools_punch_hole_fixed_dia", "tools_punch_circular_ring", "tools_punch_oblong_ring",
  3352. "tools_punch_square_ring", "tools_punch_rectangular_ring", "tools_punch_others_ring",
  3353. "tools_invert_margin",
  3354. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance",
  3355. 'global_tpdf_bmargin', 'global_tpdf_tmargin', 'global_tpdf_rmargin', 'global_tpdf_lmargin']
  3356. def scale_defaults(sfactor):
  3357. for dim in dimensions:
  3358. if dim in [
  3359. 'gerber_editor_newdim', 'excellon_toolchangexy', 'geometry_toolchangexy', 'excellon_endxy',
  3360. 'geometry_endxy', 'tools_solderpaste_xy_toolchange', 'tools_cal_toolchange_xy',
  3361. 'tools_transform_mirror_point'
  3362. ]:
  3363. if self.defaults[dim] is None or self.defaults[dim] == '':
  3364. continue
  3365. try:
  3366. coordinates = self.defaults[dim].split(",")
  3367. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3368. coords_xy[0] *= sfactor
  3369. coords_xy[1] *= sfactor
  3370. self.defaults[dim] = "%.*f, %.*f" % (
  3371. self.decimals, coords_xy[0], self.decimals, coords_xy[1])
  3372. except Exception as e:
  3373. log.debug("App.on_toggle_units.scale_defaults() --> 'string tuples': %s" % str(e))
  3374. elif dim in [
  3375. 'geometry_cnctooldia', 'tools_ncctools', 'tools_solderpaste_tools'
  3376. ]:
  3377. if self.defaults[dim] is None or self.defaults[dim] == '':
  3378. continue
  3379. try:
  3380. self.defaults[dim] = float(self.defaults[dim])
  3381. tools_diameters = [self.defaults[dim]]
  3382. except ValueError:
  3383. try:
  3384. tools_string = self.defaults[dim].split(",")
  3385. tools_diameters = [eval(a) for a in tools_string if a != '']
  3386. except Exception as e:
  3387. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3388. continue
  3389. self.defaults[dim] = ''
  3390. td_len = len(tools_diameters)
  3391. if td_len > 1:
  3392. for t in range(td_len):
  3393. tools_diameters[t] *= sfactor
  3394. self.defaults[dim] += "%.*f," % (self.decimals, tools_diameters[t])
  3395. else:
  3396. tools_diameters[0] *= sfactor
  3397. self.defaults[dim] += "%.*f" % (self.decimals, tools_diameters[0])
  3398. elif dim in ['global_gridx', 'global_gridy']:
  3399. # format the number of decimals to the one specified in self.decimals
  3400. try:
  3401. val = float(self.defaults[dim]) * sfactor
  3402. except Exception as e:
  3403. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3404. continue
  3405. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  3406. else:
  3407. # the number of decimals for the rest is kept unchanged
  3408. if self.defaults[dim]:
  3409. try:
  3410. val = float(self.defaults[dim]) * sfactor
  3411. except Exception as e:
  3412. log.debug('App.on_toggle_units().scale_defaults() --> Value: %s %s' % (str(dim), str(e)))
  3413. continue
  3414. self.defaults[dim] = val
  3415. # The scaling factor depending on choice of units.
  3416. factor = 25.4 if new_units == 'MM' else 1 / 25.4
  3417. # Changing project units. Warn user.
  3418. msgbox = QtWidgets.QMessageBox()
  3419. msgbox.setWindowTitle(_("Toggle Units"))
  3420. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/toggle_units32.png'))
  3421. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  3422. msgbox.setText(_("Changing the units of the project\n"
  3423. "will scale all objects.\n\n"
  3424. "Do you want to continue?"))
  3425. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3426. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3427. msgbox.setDefaultButton(bt_ok)
  3428. msgbox.exec_()
  3429. response = msgbox.clickedButton()
  3430. if response == bt_ok:
  3431. if no_pref is False:
  3432. self.preferencesUiManager.defaults_read_form()
  3433. scale_defaults(factor)
  3434. self.preferencesUiManager.defaults_write_form(fl_units=new_units)
  3435. self.defaults["units"] = new_units
  3436. # update the defaults from form, some may assume that the conversion is enough and it's not
  3437. self.on_options_app2project()
  3438. # update the objects
  3439. for obj in self.collection.get_list():
  3440. obj.convert_units(new_units)
  3441. # make that the properties stored in the object are also updated
  3442. self.app_obj.object_changed.emit(obj)
  3443. # rebuild the object UI
  3444. obj.build_ui()
  3445. # change this only if the workspace is active
  3446. if self.defaults['global_workspace'] is True:
  3447. self.plotcanvas.draw_workspace(pagesize=self.defaults['global_workspaceT'])
  3448. # adjust the grid values on the main toolbar
  3449. val_x = float(self.defaults['global_gridx']) * factor
  3450. val_y = val_x if self.ui.grid_gap_link_cb.isChecked() else float(self.defaults['global_gridx']) * factor
  3451. current = self.collection.get_active()
  3452. if current is not None:
  3453. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  3454. if not isinstance(current, GeometryObject):
  3455. current.to_form()
  3456. # replot all objects
  3457. self.plot_all()
  3458. # set the status labels to reflect the current FlatCAM units
  3459. self.set_screen_units(new_units)
  3460. # signal to the app that we changed the object properties and it should save the project
  3461. self.should_we_save = True
  3462. self.inform.emit('[success] %s: %s' % (_("Converted units to"), new_units))
  3463. else:
  3464. # Undo toggling
  3465. self.toggle_units_ignore = True
  3466. if self.defaults['units'].upper() == 'MM':
  3467. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  3468. else:
  3469. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  3470. self.toggle_units_ignore = False
  3471. # store the grid values so they are not changed in the next step
  3472. val_x = float(self.defaults['global_gridx'])
  3473. val_y = float(self.defaults['global_gridy'])
  3474. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  3475. self.preferencesUiManager.defaults_read_form()
  3476. # the self.preferencesUiManager.defaults_read_form() will update all defaults values
  3477. # in self.defaults from the GUI elements but
  3478. # I don't want it for the grid values, so I update them here
  3479. self.defaults['global_gridx'] = val_x
  3480. self.defaults['global_gridy'] = val_y
  3481. self.ui.grid_gap_x_entry.set_value(val_x, decimals=self.decimals)
  3482. self.ui.grid_gap_y_entry.set_value(val_y, decimals=self.decimals)
  3483. def on_deselect_all(self):
  3484. self.collection.set_all_inactive()
  3485. self.delete_selection_shape()
  3486. def on_workspace_modified(self):
  3487. # self.save_defaults(silent=True)
  3488. self.plotcanvas.delete_workspace()
  3489. self.preferencesUiManager.defaults_read_form()
  3490. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3491. def on_workspace(self):
  3492. if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value():
  3493. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  3494. self.inform[str, bool].emit(_("Workspace enabled."), False)
  3495. else:
  3496. self.plotcanvas.delete_workspace()
  3497. self.inform[str, bool].emit(_("Workspace disabled."), False)
  3498. self.preferencesUiManager.defaults_read_form()
  3499. # self.save_defaults(silent=True)
  3500. def on_workspace_toggle(self):
  3501. state = False if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value() else True
  3502. try:
  3503. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.disconnect(self.on_workspace)
  3504. except TypeError:
  3505. pass
  3506. self.ui.general_defaults_form.general_app_set_group.workspace_cb.set_value(state)
  3507. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  3508. self.on_workspace()
  3509. def on_cursor_type(self, val):
  3510. """
  3511. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  3512. :return: None
  3513. """
  3514. self.app_cursor.enabled = False
  3515. if val == 'small':
  3516. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(False)
  3517. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(False)
  3518. self.app_cursor = self.plotcanvas.new_cursor()
  3519. else:
  3520. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(True)
  3521. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(True)
  3522. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  3523. if self.ui.grid_snap_btn.isChecked():
  3524. self.app_cursor.enabled = True
  3525. else:
  3526. self.app_cursor.enabled = False
  3527. def on_tool_add_keypress(self):
  3528. # ## Current application units in Upper Case
  3529. self.units = self.defaults['units'].upper()
  3530. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3531. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3532. if notebook_widget_name == 'selected_tab':
  3533. if self.collection.get_active().kind == 'geometry':
  3534. # Tool add works for Geometry only if Advanced is True in Preferences
  3535. if self.defaults["global_app_level"] == 'a':
  3536. tool_add_popup = FCInputDialog(title="New Tool ...",
  3537. text='Enter a Tool Diameter:',
  3538. min=0.0000, max=99.9999, decimals=4)
  3539. tool_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/letter_t_32.png'))
  3540. val, ok = tool_add_popup.get_value()
  3541. if ok:
  3542. if float(val) == 0:
  3543. self.inform.emit('[WARNING_NOTCL] %s' %
  3544. _("Please enter a tool diameter with non-zero value, in Float format."))
  3545. return
  3546. self.collection.get_active().on_tool_add(dia=float(val))
  3547. else:
  3548. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  3549. else:
  3550. msgbox = QtWidgets.QMessageBox()
  3551. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  3552. "Go to Preferences -> General - Show Advanced Options."))
  3553. msgbox.setWindowTitle("Tool adding ...")
  3554. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/warning.png'))
  3555. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  3556. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3557. msgbox.setDefaultButton(bt_ok)
  3558. msgbox.exec_()
  3559. # work only if the notebook tab on focus is the Tools_Tab
  3560. if notebook_widget_name == 'tool_tab':
  3561. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3562. # and only if the tool is NCC Tool
  3563. if tool_widget == self.ncclear_tool.toolName:
  3564. self.ncclear_tool.on_add_tool_by_key()
  3565. # and only if the tool is Paint Area Tool
  3566. elif tool_widget == self.paint_tool.toolName:
  3567. self.paint_tool.on_add_tool_by_key()
  3568. # and only if the tool is Solder Paste Dispensing Tool
  3569. elif tool_widget == self.paste_tool.toolName:
  3570. self.paste_tool.on_add_tool_by_key()
  3571. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  3572. # See description below.
  3573. def on_delete_keypress(self):
  3574. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3575. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3576. if notebook_widget_name == 'selected_tab':
  3577. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.GeometryObject'>":
  3578. self.collection.get_active().on_tool_delete()
  3579. # work only if the notebook tab on focus is the Tools_Tab
  3580. elif notebook_widget_name == 'tool_tab':
  3581. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3582. # and only if the tool is NCC Tool
  3583. if tool_widget == self.ncclear_tool.toolName:
  3584. self.ncclear_tool.on_tool_delete()
  3585. # and only if the tool is Paint Tool
  3586. elif tool_widget == self.paint_tool.toolName:
  3587. self.paint_tool.on_tool_delete()
  3588. # and only if the tool is Solder Paste Dispensing Tool
  3589. elif tool_widget == self.paste_tool.toolName:
  3590. self.paste_tool.on_tool_delete()
  3591. # and only if the tool is Isolation Tool
  3592. elif tool_widget == self.isolation_tool.toolName:
  3593. self.isolation_tool.on_tool_delete()
  3594. else:
  3595. self.on_delete()
  3596. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  3597. # some screens you have to be careful where you hover with your mouse.
  3598. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  3599. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  3600. # Complicated, I know :)
  3601. def on_delete(self, force_deletion=False):
  3602. """
  3603. Delete the currently selected FlatCAMObjs.
  3604. :param force_deletion: used by Tcl command
  3605. :return: None
  3606. """
  3607. self.defaults.report_usage("on_delete()")
  3608. response = None
  3609. bt_ok = None
  3610. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  3611. # a geometry object before we update it.
  3612. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  3613. and self.grb_editor.editor_active is False:
  3614. if self.defaults["global_delete_confirmation"] is True and force_deletion is False:
  3615. msgbox = QtWidgets.QMessageBox()
  3616. msgbox.setWindowTitle(_("Delete objects"))
  3617. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/deleteshape32.png'))
  3618. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  3619. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  3620. msgbox.setText(_("Are you sure you want to permanently delete\n"
  3621. "the selected objects?"))
  3622. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3623. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3624. msgbox.setDefaultButton(bt_ok)
  3625. msgbox.exec_()
  3626. response = msgbox.clickedButton()
  3627. if self.defaults["global_delete_confirmation"] is False or force_deletion is True:
  3628. response = bt_ok
  3629. if response == bt_ok:
  3630. if self.collection.get_active():
  3631. self.log.debug("App.on_delete()")
  3632. for obj_active in self.collection.get_selected():
  3633. # if the deleted object is GerberObject then make sure to delete the possible mark shapes
  3634. if obj_active.kind == 'gerber':
  3635. for el in obj_active.mark_shapes:
  3636. obj_active.mark_shapes[el].clear(update=True)
  3637. obj_active.mark_shapes[el].enabled = False
  3638. # obj_active.mark_shapes[el] = None
  3639. del el
  3640. elif obj_active.kind == 'cncjob':
  3641. try:
  3642. obj_active.text_col.enabled = False
  3643. del obj_active.text_col
  3644. obj_active.annotation.clear(update=True)
  3645. del obj_active.annotation
  3646. except AttributeError as e:
  3647. log.debug(
  3648. "App.on_delete() --> delete annotations on a FlatCAMCNCJob object. %s" % str(e)
  3649. )
  3650. while self.collection.get_selected():
  3651. self.delete_first_selected()
  3652. # make sure that the selection shape is deleted, too
  3653. self.delete_selection_shape()
  3654. # if there are no longer objects delete also the exclusion areas shapes
  3655. if not self.collection.get_list():
  3656. self.exc_areas.clear_shapes()
  3657. self.inform.emit('%s...' % _("Object(s) deleted"))
  3658. else:
  3659. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  3660. else:
  3661. self.inform.emit(_("Save the work in Editor and try again ..."))
  3662. def delete_first_selected(self):
  3663. # Keep this for later
  3664. try:
  3665. sel_obj = self.collection.get_active()
  3666. name = sel_obj.options["name"]
  3667. isPlotted = sel_obj.options["plot"]
  3668. except AttributeError:
  3669. self.log.debug("Nothing selected for deletion")
  3670. return
  3671. if self.is_legacy is True:
  3672. # Remove plot only if the object was plotted otherwise delaxes will fail
  3673. if isPlotted:
  3674. try:
  3675. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  3676. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  3677. except Exception as e:
  3678. log.debug("App.delete_first_selected() --> %s" % str(e))
  3679. self.plotcanvas.auto_adjust_axes()
  3680. # Remove from dictionary
  3681. self.collection.delete_active()
  3682. # Clear form
  3683. self.setup_component_editor()
  3684. self.inform.emit('%s: %s' % (_("Object deleted"), name))
  3685. def on_set_origin(self):
  3686. """
  3687. Set the origin to the left mouse click position
  3688. :return: None
  3689. """
  3690. # display the message for the user
  3691. # and ask him to click on the desired position
  3692. self.defaults.report_usage("on_set_origin()")
  3693. def origin_replot():
  3694. def worker_task():
  3695. with self.proc_container.new('%s...' % _("Plotting")):
  3696. for obj in self.collection.get_list():
  3697. obj.plot()
  3698. self.plotcanvas.fit_view()
  3699. if self.is_legacy:
  3700. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  3701. else:
  3702. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  3703. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3704. self.inform.emit(_('Click to set the origin ...'))
  3705. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  3706. # first disconnect it as it may have been used by something else
  3707. try:
  3708. self.replot_signal.disconnect()
  3709. except TypeError:
  3710. pass
  3711. self.replot_signal[list].connect(origin_replot)
  3712. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  3713. """
  3714. :param event:
  3715. :param location:
  3716. :param noplot:
  3717. :param use_thread:
  3718. :return:
  3719. """
  3720. noplot_sig = noplot
  3721. def worker_task():
  3722. with self.proc_container.new(_("Setting Origin...")):
  3723. obj_list = self.collection.get_list()
  3724. for obj in obj_list:
  3725. obj.offset((x, y))
  3726. self.app_obj.object_changed.emit(obj)
  3727. # Update the object bounding box options
  3728. a, b, c, d = obj.bounds()
  3729. obj.options['xmin'] = a
  3730. obj.options['ymin'] = b
  3731. obj.options['xmax'] = c
  3732. obj.options['ymax'] = d
  3733. self.inform.emit('[success] %s...' % _('Origin set'))
  3734. for obj in obj_list:
  3735. out_name = obj.options["name"]
  3736. if obj.kind == 'gerber':
  3737. obj.source_file = self.export_gerber(
  3738. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3739. elif obj.kind == 'excellon':
  3740. obj.source_file = self.export_excellon(
  3741. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3742. if noplot_sig is False:
  3743. self.replot_signal.emit([])
  3744. if location is not None:
  3745. if len(location) != 2:
  3746. self.inform.emit('[ERROR_NOTCL] %s...' % _("Origin coordinates specified but incomplete."))
  3747. return 'fail'
  3748. x, y = location
  3749. if use_thread is True:
  3750. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3751. else:
  3752. worker_task()
  3753. self.should_we_save = True
  3754. return
  3755. if event is not None and event.button == 1:
  3756. if self.is_legacy is False:
  3757. event_pos = event.pos
  3758. else:
  3759. event_pos = (event.xdata, event.ydata)
  3760. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  3761. if self.grid_status():
  3762. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3763. else:
  3764. pos = pos_canvas
  3765. x = 0 - pos[0]
  3766. y = 0 - pos[1]
  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. def on_move2origin(self, use_thread=True):
  3773. """
  3774. Move selected objects to origin.
  3775. :param use_thread: Control if to use threaded operation. Boolean.
  3776. :return:
  3777. """
  3778. def worker_task():
  3779. with self.proc_container.new(_("Moving to Origin...")):
  3780. obj_list = self.collection.get_selected()
  3781. if not obj_list:
  3782. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  3783. return
  3784. xminlist = []
  3785. yminlist = []
  3786. # first get a bounding box to fit all
  3787. for obj in obj_list:
  3788. xmin, ymin, xmax, ymax = obj.bounds()
  3789. xminlist.append(xmin)
  3790. yminlist.append(ymin)
  3791. # get the minimum x,y for all objects selected
  3792. x = min(xminlist)
  3793. y = min(yminlist)
  3794. for obj in obj_list:
  3795. obj.offset((-x, -y))
  3796. self.app_obj.object_changed.emit(obj)
  3797. # Update the object bounding box options
  3798. a, b, c, d = obj.bounds()
  3799. obj.options['xmin'] = a
  3800. obj.options['ymin'] = b
  3801. obj.options['xmax'] = c
  3802. obj.options['ymax'] = d
  3803. for obj in obj_list:
  3804. obj.plot()
  3805. for obj in obj_list:
  3806. out_name = obj.options["name"]
  3807. if obj.kind == 'gerber':
  3808. obj.source_file = self.export_gerber(
  3809. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3810. elif obj.kind == 'excellon':
  3811. obj.source_file = self.export_excellon(
  3812. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  3813. self.inform.emit('[success] %s...' % _('Origin set'))
  3814. if use_thread is True:
  3815. self.worker_task.emit({'fcn': worker_task, 'params': []})
  3816. else:
  3817. worker_task()
  3818. self.should_we_save = True
  3819. def on_jump_to(self, custom_location=None, fit_center=True):
  3820. """
  3821. Jump to a location by setting the mouse cursor location.
  3822. :param custom_location: Jump to a specified point. (x, y) tuple.
  3823. :param fit_center: If to fit view. Boolean.
  3824. :return:
  3825. """
  3826. self.defaults.report_usage("on_jump_to()")
  3827. if not custom_location:
  3828. dia_box_location = None
  3829. try:
  3830. dia_box_location = eval(self.clipboard.text())
  3831. except Exception:
  3832. pass
  3833. if type(dia_box_location) == tuple:
  3834. dia_box_location = str(dia_box_location)
  3835. else:
  3836. dia_box_location = None
  3837. # dia_box = Dialog_box(title=_("Jump to ..."),
  3838. # label=_("Enter the coordinates in format X,Y:"),
  3839. # icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  3840. # initial_text=dia_box_location)
  3841. dia_box = DialogBoxRadio(title=_("Jump to ..."),
  3842. label=_("Enter the coordinates in format X,Y:"),
  3843. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  3844. initial_text=dia_box_location,
  3845. reference=self.defaults['global_jump_ref'])
  3846. if dia_box.ok is True:
  3847. try:
  3848. location = eval(dia_box.location)
  3849. if not isinstance(location, tuple):
  3850. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  3851. return
  3852. if dia_box.reference == 'rel':
  3853. rel_x = self.mouse[0] + location[0]
  3854. rel_y = self.mouse[1] + location[1]
  3855. location = (rel_x, rel_y)
  3856. self.defaults['global_jump_ref'] = dia_box.reference
  3857. except Exception:
  3858. return
  3859. else:
  3860. return
  3861. else:
  3862. location = custom_location
  3863. self.jump_signal.emit(location)
  3864. if fit_center:
  3865. self.plotcanvas.fit_center(loc=location)
  3866. cursor = QtGui.QCursor()
  3867. if self.is_legacy is False:
  3868. # I don't know where those differences come from but they are constant for the current
  3869. # execution of the application and they are multiples of a value around 0.0263mm.
  3870. # In a random way sometimes they are more sometimes they are less
  3871. # if units == 'MM':
  3872. # cal_factor = 0.0263
  3873. # else:
  3874. # cal_factor = 0.0263 / 25.4
  3875. cal_location = (location[0], location[1])
  3876. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3877. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  3878. j_pos = (
  3879. int(canvas_origin.x() + round(jump_loc[0])),
  3880. int(canvas_origin.y() + round(jump_loc[1]))
  3881. )
  3882. cursor.setPos(j_pos[0], j_pos[1])
  3883. else:
  3884. # find the canvas origin which is in the top left corner
  3885. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3886. # determine the coordinates for the lowest left point of the canvas
  3887. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  3888. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  3889. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  3890. # canvas) and the point (width, height) is in the top-right location
  3891. loc = self.plotcanvas.axes.transData.transform_point(location)
  3892. j_pos = (
  3893. int(x0 + loc[0]),
  3894. int(y0 - loc[1])
  3895. )
  3896. cursor.setPos(j_pos[0], j_pos[1])
  3897. self.plotcanvas.mouse = [location[0], location[1]]
  3898. if self.defaults["global_cursor_color_enabled"] is True:
  3899. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  3900. else:
  3901. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  3902. if self.grid_status():
  3903. # Update cursor
  3904. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  3905. symbol='++', edge_color=self.cursor_color_3D,
  3906. edge_width=self.defaults["global_cursor_width"],
  3907. size=self.defaults["global_cursor_size"])
  3908. # Set the relative position label
  3909. dx = location[0] - float(self.rel_point1[0])
  3910. dy = location[1] - float(self.rel_point1[1])
  3911. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  3912. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  3913. # Set the position label
  3914. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3915. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  3916. units = self.defaults["units"].lower()
  3917. self.plotcanvas.text_hud.text = \
  3918. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  3919. dx, units, dy, units, location[0], units, location[1], units)
  3920. self.inform.emit('[success] %s' % _("Done."))
  3921. return location
  3922. def on_locate(self, obj, fit_center=True):
  3923. """
  3924. Jump to one of the corners (or center) of an object by setting the mouse cursor location
  3925. :param obj: The object on which to locate certain points
  3926. :param fit_center: If to fit view. Boolean.
  3927. :return: A point location. (x, y) tuple.
  3928. """
  3929. self.defaults.report_usage("on_locate()")
  3930. if obj is None:
  3931. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  3932. return 'fail'
  3933. class DialogBoxChoice(QtWidgets.QDialog):
  3934. def __init__(self, title=None, icon=None, choice='bl'):
  3935. """
  3936. :param title: string with the window title
  3937. """
  3938. super(DialogBoxChoice, self).__init__()
  3939. self.ok = False
  3940. self.setWindowIcon(icon)
  3941. self.setWindowTitle(str(title))
  3942. self.form = QtWidgets.QFormLayout(self)
  3943. self.ref_radio = RadioSet([
  3944. {"label": _("Bottom-Left"), "value": "bl"},
  3945. {"label": _("Top-Left"), "value": "tl"},
  3946. {"label": _("Bottom-Right"), "value": "br"},
  3947. {"label": _("Top-Right"), "value": "tr"},
  3948. {"label": _("Center"), "value": "c"}
  3949. ], orientation='vertical', stretch=False)
  3950. self.ref_radio.set_value(choice)
  3951. self.form.addRow(self.ref_radio)
  3952. self.button_box = QtWidgets.QDialogButtonBox(
  3953. QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,
  3954. Qt.Horizontal, parent=self)
  3955. self.form.addRow(self.button_box)
  3956. self.button_box.accepted.connect(self.accept)
  3957. self.button_box.rejected.connect(self.reject)
  3958. if self.exec_() == QtWidgets.QDialog.Accepted:
  3959. self.ok = True
  3960. self.location_point = self.ref_radio.get_value()
  3961. else:
  3962. self.ok = False
  3963. self.location_point = None
  3964. dia_box = DialogBoxChoice(title=_("Locate ..."),
  3965. icon=QtGui.QIcon(self.resource_location + '/locate16.png'),
  3966. choice=self.defaults['global_locate_pt'])
  3967. if dia_box.ok is True:
  3968. try:
  3969. location_point = dia_box.location_point
  3970. self.defaults['global_locate_pt'] = dia_box.location_point
  3971. except Exception:
  3972. return
  3973. else:
  3974. return
  3975. loc_b = obj.bounds()
  3976. if location_point == 'bl':
  3977. location = (loc_b[0], loc_b[1])
  3978. elif location_point == 'tl':
  3979. location = (loc_b[0], loc_b[3])
  3980. elif location_point == 'br':
  3981. location = (loc_b[2], loc_b[1])
  3982. elif location_point == 'tr':
  3983. location = (loc_b[2], loc_b[3])
  3984. else:
  3985. # center
  3986. cx = loc_b[0] + ((loc_b[2] - loc_b[0]) / 2)
  3987. cy = loc_b[1] + ((loc_b[3] - loc_b[1]) / 2)
  3988. location = (cx, cy)
  3989. self.locate_signal.emit(location, location_point)
  3990. if fit_center:
  3991. self.plotcanvas.fit_center(loc=location)
  3992. cursor = QtGui.QCursor()
  3993. if self.is_legacy is False:
  3994. # I don't know where those differences come from but they are constant for the current
  3995. # execution of the application and they are multiples of a value around 0.0263mm.
  3996. # In a random way sometimes they are more sometimes they are less
  3997. # if units == 'MM':
  3998. # cal_factor = 0.0263
  3999. # else:
  4000. # cal_factor = 0.0263 / 25.4
  4001. cal_location = (location[0], location[1])
  4002. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4003. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  4004. j_pos = (
  4005. int(canvas_origin.x() + round(jump_loc[0])),
  4006. int(canvas_origin.y() + round(jump_loc[1]))
  4007. )
  4008. cursor.setPos(j_pos[0], j_pos[1])
  4009. else:
  4010. # find the canvas origin which is in the top left corner
  4011. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4012. # determine the coordinates for the lowest left point of the canvas
  4013. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  4014. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  4015. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  4016. # canvas) and the point (width, height) is in the top-right location
  4017. loc = self.plotcanvas.axes.transData.transform_point(location)
  4018. j_pos = (
  4019. int(x0 + loc[0]),
  4020. int(y0 - loc[1])
  4021. )
  4022. cursor.setPos(j_pos[0], j_pos[1])
  4023. self.plotcanvas.mouse = [location[0], location[1]]
  4024. if self.defaults["global_cursor_color_enabled"] is True:
  4025. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  4026. else:
  4027. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  4028. if self.grid_status():
  4029. # Update cursor
  4030. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  4031. symbol='++', edge_color=self.cursor_color_3D,
  4032. edge_width=self.defaults["global_cursor_width"],
  4033. size=self.defaults["global_cursor_size"])
  4034. # Set the relative position label
  4035. self.dx = location[0] - float(self.rel_point1[0])
  4036. self.dy = location[1] - float(self.rel_point1[1])
  4037. # Set the position label
  4038. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4039. "<b>Y</b>: %.4f&nbsp;" % (location[0], location[1]))
  4040. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4041. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  4042. units = self.defaults["units"].lower()
  4043. self.plotcanvas.text_hud.text = \
  4044. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  4045. self.dx, units, self.dy, units, location[0], units, location[1], units)
  4046. self.inform.emit('[success] %s' % _("Done."))
  4047. return location
  4048. def on_copy_command(self):
  4049. """
  4050. Will copy a selection of objects, creating new objects.
  4051. :return:
  4052. """
  4053. self.defaults.report_usage("on_copy_command()")
  4054. def initialize(obj_init, app):
  4055. """
  4056. :param obj_init: the new object
  4057. :type obj_init: class
  4058. :param app: An instance of the App class
  4059. :type app: App
  4060. :return: None
  4061. :rtype:
  4062. """
  4063. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4064. try:
  4065. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4066. except AttributeError:
  4067. pass
  4068. try:
  4069. obj_init.apertures = deepcopy(obj.apertures)
  4070. except AttributeError:
  4071. pass
  4072. try:
  4073. if obj.tools:
  4074. obj_init.tools = deepcopy(obj.tools)
  4075. except Exception as err:
  4076. log.debug("App.on_copy_command() --> %s" % str(err))
  4077. try:
  4078. obj_init.source_file = deepcopy(obj.source_file)
  4079. except (AttributeError, TypeError):
  4080. pass
  4081. def initialize_excellon(obj_init, app):
  4082. obj_init.source_file = deepcopy(obj.source_file)
  4083. obj_init.tools = deepcopy(obj.tools)
  4084. # drills are offset, so they need to be deep copied
  4085. obj_init.drills = deepcopy(obj.drills)
  4086. # slots are offset, so they need to be deep copied
  4087. obj_init.slots = deepcopy(obj.slots)
  4088. obj_init.create_geometry()
  4089. def initialize_script(obj_init, app_obj):
  4090. obj_init.source_file = deepcopy(obj.source_file)
  4091. def initialize_document(obj_init, app_obj):
  4092. obj_init.source_file = deepcopy(obj.source_file)
  4093. for obj in self.collection.get_selected():
  4094. obj_name = obj.options["name"]
  4095. try:
  4096. if isinstance(obj, ExcellonObject):
  4097. self.app_obj.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  4098. elif isinstance(obj, GerberObject):
  4099. self.app_obj.new_object("gerber", str(obj_name) + "_copy", initialize)
  4100. elif isinstance(obj, GeometryObject):
  4101. self.app_obj.new_object("geometry", str(obj_name) + "_copy", initialize)
  4102. elif isinstance(obj, ScriptObject):
  4103. self.app_obj.new_object("script", str(obj_name) + "_copy", initialize_script)
  4104. elif isinstance(obj, DocumentObject):
  4105. self.app_obj.new_object("document", str(obj_name) + "_copy", initialize_document)
  4106. except Exception as e:
  4107. return "Operation failed: %s" % str(e)
  4108. def on_copy_object2(self, custom_name):
  4109. def initialize_geometry(obj_init, app):
  4110. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4111. try:
  4112. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4113. except AttributeError:
  4114. pass
  4115. try:
  4116. obj_init.apertures = deepcopy(obj.apertures)
  4117. except AttributeError:
  4118. pass
  4119. try:
  4120. if obj.tools:
  4121. obj_init.tools = deepcopy(obj.tools)
  4122. except Exception as ee:
  4123. log.debug("on_copy_object2() --> %s" % str(ee))
  4124. def initialize_gerber(obj_init, app):
  4125. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4126. obj_init.apertures = deepcopy(obj.apertures)
  4127. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  4128. def initialize_excellon(obj_init, app):
  4129. obj_init.tools = deepcopy(obj.tools)
  4130. # drills are offset, so they need to be deep copied
  4131. obj_init.drills = deepcopy(obj.drills)
  4132. # slots are offset, so they need to be deep copied
  4133. obj_init.slots = deepcopy(obj.slots)
  4134. obj_init.create_geometry()
  4135. for obj in self.collection.get_selected():
  4136. obj_name = obj.options["name"]
  4137. try:
  4138. if isinstance(obj, ExcellonObject):
  4139. self.app_obj.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  4140. elif isinstance(obj, GerberObject):
  4141. self.app_obj.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  4142. elif isinstance(obj, GeometryObject):
  4143. self.app_obj.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  4144. except Exception as er:
  4145. return "Operation failed: %s" % str(er)
  4146. def on_rename_object(self, text):
  4147. """
  4148. Will rename an object.
  4149. :param text: New name for the object.
  4150. :return:
  4151. """
  4152. self.defaults.report_usage("on_rename_object()")
  4153. named_obj = self.collection.get_active()
  4154. for obj in named_obj:
  4155. if obj is list:
  4156. self.on_rename_object(text)
  4157. else:
  4158. try:
  4159. obj.options['name'] = text
  4160. except Exception as e:
  4161. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  4162. def convert_any2geo(self):
  4163. """
  4164. Will convert any object out of Gerber, Excellon, Geometry to Geometry object.
  4165. :return:
  4166. """
  4167. self.defaults.report_usage("convert_any2geo()")
  4168. def initialize(obj_init, app):
  4169. obj_init.solid_geometry = obj.solid_geometry
  4170. try:
  4171. obj_init.follow_geometry = obj.follow_geometry
  4172. except AttributeError:
  4173. pass
  4174. try:
  4175. obj_init.apertures = obj.apertures
  4176. except AttributeError:
  4177. pass
  4178. try:
  4179. if obj.tools:
  4180. obj_init.tools = obj.tools
  4181. except AttributeError:
  4182. pass
  4183. def initialize_excellon(obj_init, app):
  4184. # objs = self.collection.get_selected()
  4185. # GeometryObject.merge(objs, obj)
  4186. solid_geo = []
  4187. for tool in obj.tools:
  4188. for geo in obj.tools[tool]['solid_geometry']:
  4189. solid_geo.append(geo)
  4190. obj_init.solid_geometry = deepcopy(solid_geo)
  4191. if not self.collection.get_selected():
  4192. log.warning("App.convert_any2geo --> No object selected")
  4193. self.inform.emit('[WARNING_NOTCL] %s' %
  4194. _("No object is selected. Select an object and try again."))
  4195. return
  4196. for obj in self.collection.get_selected():
  4197. obj_name = obj.options["name"]
  4198. try:
  4199. if isinstance(obj, ExcellonObject):
  4200. self.app_obj.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  4201. else:
  4202. self.app_obj.new_object("geometry", str(obj_name) + "_conv", initialize)
  4203. except Exception as e:
  4204. return "Operation failed: %s" % str(e)
  4205. def convert_any2gerber(self):
  4206. """
  4207. Will convert any object out of Gerber, Excellon, Geometry to Gerber object.
  4208. :return:
  4209. """
  4210. self.defaults.report_usage("convert_any2gerber()")
  4211. def initialize_geometry(obj_init, app):
  4212. apertures = {}
  4213. apid = 0
  4214. apertures[str(apid)] = {}
  4215. apertures[str(apid)]['geometry'] = []
  4216. for obj_orig in obj.solid_geometry:
  4217. new_elem = {}
  4218. new_elem['solid'] = obj_orig
  4219. try:
  4220. new_elem['follow'] = obj_orig.exterior
  4221. except AttributeError:
  4222. pass
  4223. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  4224. apertures[str(apid)]['size'] = 0.0
  4225. apertures[str(apid)]['type'] = 'C'
  4226. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4227. obj_init.apertures = deepcopy(apertures)
  4228. def initialize_excellon(obj_init, app):
  4229. apertures = {}
  4230. apid = 10
  4231. for tool in obj.tools:
  4232. apertures[str(apid)] = {}
  4233. apertures[str(apid)]['geometry'] = []
  4234. for geo in obj.tools[tool]['solid_geometry']:
  4235. new_el = {}
  4236. new_el['solid'] = geo
  4237. new_el['follow'] = geo.exterior
  4238. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  4239. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  4240. apertures[str(apid)]['type'] = 'C'
  4241. apid += 1
  4242. # create solid_geometry
  4243. solid_geometry = []
  4244. for apid in apertures:
  4245. for geo_el in apertures[apid]['geometry']:
  4246. solid_geometry.append(geo_el['solid'])
  4247. solid_geometry = MultiPolygon(solid_geometry)
  4248. solid_geometry = solid_geometry.buffer(0.0000001)
  4249. obj_init.solid_geometry = deepcopy(solid_geometry)
  4250. obj_init.apertures = deepcopy(apertures)
  4251. # clear the working objects (perhaps not necessary due of Python GC)
  4252. apertures.clear()
  4253. if not self.collection.get_selected():
  4254. log.warning("App.convert_any2gerber --> No object selected")
  4255. self.inform.emit('[WARNING_NOTCL] %s' %
  4256. _("No object is selected. Select an object and try again."))
  4257. return
  4258. for obj in self.collection.get_selected():
  4259. obj_name = obj.options["name"]
  4260. try:
  4261. if isinstance(obj, ExcellonObject):
  4262. self.app_obj.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  4263. elif isinstance(obj, GeometryObject):
  4264. self.app_obj.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  4265. else:
  4266. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  4267. except Exception as e:
  4268. return "Operation failed: %s" % str(e)
  4269. def abort_all_tasks(self):
  4270. """
  4271. Executed when a certain key combo is pressed (Ctrl+Alt+X). Will abort current task
  4272. on the first possible occasion.
  4273. :return:
  4274. """
  4275. if self.abort_flag is False:
  4276. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  4277. self.abort_flag = True
  4278. self.cleanup.emit()
  4279. def app_is_idle(self):
  4280. if self.abort_flag:
  4281. self.inform.emit('[WARNING_NOTCL] %s' % _("The current task was gracefully closed on user request..."))
  4282. self.abort_flag = False
  4283. def on_selectall(self):
  4284. """
  4285. Will draw a selection box shape around the selected objects.
  4286. :return:
  4287. """
  4288. self.defaults.report_usage("on_selectall()")
  4289. # delete the possible selection box around a possible selected object
  4290. self.delete_selection_shape()
  4291. for name in self.collection.get_names():
  4292. self.collection.set_active(name)
  4293. curr_sel_obj = self.collection.get_by_name(name)
  4294. # create the selection box around the selected object
  4295. if self.defaults['global_selection_shape'] is True:
  4296. self.draw_selection_shape(curr_sel_obj)
  4297. def on_toggle_preferences(self):
  4298. pref_open = False
  4299. for idx in range(self.ui.plot_tab_area.count()):
  4300. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  4301. pref_open = True
  4302. if pref_open:
  4303. for idx in range(self.ui.plot_tab_area.count()):
  4304. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  4305. self.ui.plot_tab_area.removeTab(idx)
  4306. break
  4307. self.ui.pref_status_label.setStyleSheet("")
  4308. else:
  4309. self.on_preferences()
  4310. def on_preferences(self):
  4311. """
  4312. Adds the Preferences in a Tab in Plot Area
  4313. :return:
  4314. """
  4315. # add the tab if it was closed
  4316. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  4317. # delete the absolute and relative position and messages in the infobar
  4318. # self.ui.position_label.setText("")
  4319. # self.ui.rel_position_label.setText("")
  4320. # hide coordinates toolbars in the infobar while in DB
  4321. self.ui.coords_toolbar.hide()
  4322. self.ui.delta_coords_toolbar.hide()
  4323. # Switch plot_area to preferences page
  4324. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  4325. # self.ui.show()
  4326. self.ui.pref_status_label.setStyleSheet("""
  4327. QLabel
  4328. {
  4329. color: black;
  4330. background-color: lightseagreen;
  4331. }
  4332. """
  4333. )
  4334. # detect changes in the preferences
  4335. for idx in range(self.ui.pref_tab_area.count()):
  4336. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  4337. try:
  4338. try:
  4339. tb.textEdited.disconnect(self.preferencesUiManager.on_preferences_edited)
  4340. except (TypeError, AttributeError):
  4341. pass
  4342. tb.textEdited.connect(self.preferencesUiManager.on_preferences_edited)
  4343. except AttributeError:
  4344. pass
  4345. try:
  4346. try:
  4347. tb.modificationChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4348. except (TypeError, AttributeError):
  4349. pass
  4350. tb.modificationChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4351. except AttributeError:
  4352. pass
  4353. try:
  4354. try:
  4355. tb.toggled.disconnect(self.preferencesUiManager.on_preferences_edited)
  4356. except (TypeError, AttributeError):
  4357. pass
  4358. tb.toggled.connect(self.preferencesUiManager.on_preferences_edited)
  4359. except AttributeError:
  4360. pass
  4361. try:
  4362. try:
  4363. tb.valueChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4364. except (TypeError, AttributeError):
  4365. pass
  4366. tb.valueChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4367. except AttributeError:
  4368. pass
  4369. try:
  4370. try:
  4371. tb.currentIndexChanged.disconnect(self.preferencesUiManager.on_preferences_edited)
  4372. except (TypeError, AttributeError):
  4373. pass
  4374. tb.currentIndexChanged.connect(self.preferencesUiManager.on_preferences_edited)
  4375. except AttributeError:
  4376. pass
  4377. def on_tools_database(self, source='app'):
  4378. """
  4379. Adds the Tools Database in a Tab in Plot Area.
  4380. :return:
  4381. """
  4382. for idx in range(self.ui.plot_tab_area.count()):
  4383. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4384. # there can be only one instance of Tools Database at one time
  4385. return
  4386. if source == 'app':
  4387. self.tools_db_tab = ToolsDB2(
  4388. app=self,
  4389. parent=self.ui,
  4390. callback_on_edited=self.on_tools_db_edited,
  4391. callback_on_tool_request=self.on_geometry_tool_add_from_db_executed
  4392. )
  4393. elif source == 'ncc':
  4394. self.tools_db_tab = ToolsDB2(
  4395. app=self,
  4396. parent=self.ui,
  4397. callback_on_edited=self.on_tools_db_edited,
  4398. callback_on_tool_request=self.ncclear_tool.on_ncc_tool_add_from_db_executed
  4399. )
  4400. elif source == 'paint':
  4401. self.tools_db_tab = ToolsDB2(
  4402. app=self,
  4403. parent=self.ui,
  4404. callback_on_edited=self.on_tools_db_edited,
  4405. callback_on_tool_request=self.paint_tool.on_paint_tool_add_from_db_executed
  4406. )
  4407. elif source == 'iso':
  4408. self.tools_db_tab = ToolsDB2(
  4409. app=self,
  4410. parent=self.ui,
  4411. callback_on_edited=self.on_tools_db_edited,
  4412. callback_on_tool_request=self.isolation_tool.on_iso_tool_add_from_db_executed
  4413. )
  4414. # add the tab if it was closed
  4415. try:
  4416. self.ui.plot_tab_area.addTab(self.tools_db_tab, _("Tools Database"))
  4417. self.tools_db_tab.setObjectName("database_tab")
  4418. except Exception as e:
  4419. log.debug("App.on_tools_database() --> %s" % str(e))
  4420. return
  4421. # delete the absolute and relative position and messages in the infobar
  4422. # self.ui.position_label.setText("")
  4423. # self.ui.rel_position_label.setText("")
  4424. # hide coordinates toolbars in the infobar while in DB
  4425. self.ui.coords_toolbar.hide()
  4426. self.ui.delta_coords_toolbar.hide()
  4427. # Switch plot_area to preferences page
  4428. self.ui.plot_tab_area.setCurrentWidget(self.tools_db_tab)
  4429. # detect changes in the Tools in Tools DB, connect signals from table widget in tab
  4430. self.tools_db_tab.ui_connect()
  4431. def on_tools_db_edited(self):
  4432. """
  4433. Executed whenever a tool is edited in Tools Database.
  4434. Will color the text of the Tools Database tab to Red color.
  4435. :return:
  4436. """
  4437. self.inform[str, bool].emit('[WARNING_NOTCL] %s' % _("Tools in Tools Database edited but not saved."), False)
  4438. for idx in range(self.ui.plot_tab_area.count()):
  4439. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4440. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  4441. self.tools_db_tab.save_db_btn.setStyleSheet("QPushButton {color: red;}")
  4442. self.tools_db_changed_flag = True
  4443. def on_geometry_tool_add_from_db_executed(self, tool):
  4444. """
  4445. Here add the tool from DB in the selected geometry object.
  4446. :return:
  4447. """
  4448. tool_from_db = deepcopy(tool)
  4449. obj = self.collection.get_active()
  4450. if obj.kind == 'geometry':
  4451. obj.on_tool_from_db_inserted(tool=tool_from_db)
  4452. # close the tab and delete it
  4453. for idx in range(self.ui.plot_tab_area.count()):
  4454. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4455. wdg = self.ui.plot_tab_area.widget(idx)
  4456. wdg.deleteLater()
  4457. self.ui.plot_tab_area.removeTab(idx)
  4458. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4459. elif obj.kind == 'gerber':
  4460. self.isolation_tool.on_tool_from_db_inserted(tool=tool_from_db)
  4461. # close the tab and delete it
  4462. for idx in range(self.ui.plot_tab_area.count()):
  4463. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4464. wdg = self.ui.plot_tab_area.widget(idx)
  4465. wdg.deleteLater()
  4466. self.ui.plot_tab_area.removeTab(idx)
  4467. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4468. else:
  4469. self.inform.emit('[ERROR_NOTCL] %s' % _("Adding tool from DB is not allowed for this object."))
  4470. def on_plot_area_tab_closed(self, tab_obj_name):
  4471. """
  4472. Executed whenever a QTab is closed in the Plot Area.
  4473. :param tab_obj_name: The objectName of the Tab that was closed. This objectName is assigned on Tab creation
  4474. :return:
  4475. """
  4476. if tab_obj_name == "preferences_tab":
  4477. self.preferencesUiManager.on_close_preferences_tab()
  4478. elif tab_obj_name == "database_tab":
  4479. # disconnect the signals from the table widget in tab
  4480. self.tools_db_tab.ui_disconnect()
  4481. if self.tools_db_changed_flag is True:
  4482. msgbox = QtWidgets.QMessageBox()
  4483. msgbox.setText(_("One or more Tools are edited.\n"
  4484. "Do you want to update the Tools Database?"))
  4485. msgbox.setWindowTitle(_("Save Tools Database"))
  4486. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  4487. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  4488. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4489. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4490. msgbox.setDefaultButton(bt_yes)
  4491. msgbox.exec_()
  4492. response = msgbox.clickedButton()
  4493. if response == bt_yes:
  4494. self.tools_db_tab.on_save_tools_db()
  4495. self.inform.emit('[success] %s' % "Tools DB saved to file.")
  4496. else:
  4497. self.tools_db_changed_flag = False
  4498. self.inform.emit('')
  4499. return
  4500. self.tools_db_tab.deleteLater()
  4501. elif tab_obj_name == "text_editor_tab":
  4502. self.toggle_codeeditor = False
  4503. elif tab_obj_name == "bookmarks_tab":
  4504. self.book_dialog_tab.rebuild_actions()
  4505. self.book_dialog_tab.deleteLater()
  4506. else:
  4507. pass
  4508. # restore the coords toolbars
  4509. self.ui.toggle_coords(checked=self.defaults["global_coords_show"])
  4510. self.ui.toggle_delta_coords(checked=self.defaults["global_delta_coords_show"])
  4511. def on_flipy(self):
  4512. """
  4513. Executed when the menu entry in Options -> Flip on Y axis is clicked.
  4514. :return:
  4515. """
  4516. self.defaults.report_usage("on_flipy()")
  4517. obj_list = self.collection.get_selected()
  4518. xminlist = []
  4519. yminlist = []
  4520. xmaxlist = []
  4521. ymaxlist = []
  4522. if not obj_list:
  4523. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Flip on Y axis."))
  4524. else:
  4525. try:
  4526. # first get a bounding box to fit all
  4527. for obj in obj_list:
  4528. xmin, ymin, xmax, ymax = obj.bounds()
  4529. xminlist.append(xmin)
  4530. yminlist.append(ymin)
  4531. xmaxlist.append(xmax)
  4532. ymaxlist.append(ymax)
  4533. # get the minimum x,y and maximum x,y for all objects selected
  4534. xminimal = min(xminlist)
  4535. yminimal = min(yminlist)
  4536. xmaximal = max(xmaxlist)
  4537. ymaximal = max(ymaxlist)
  4538. px = 0.5 * (xminimal + xmaximal)
  4539. py = 0.5 * (yminimal + ymaximal)
  4540. # execute mirroring
  4541. for obj in obj_list:
  4542. obj.mirror('X', [px, py])
  4543. obj.plot()
  4544. self.app_obj.object_changed.emit(obj)
  4545. self.inform.emit('[success] %s' %
  4546. _("Flip on Y axis done."))
  4547. except Exception as e:
  4548. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4549. return
  4550. def on_flipx(self):
  4551. """
  4552. Executed when the menu entry in Options -> Flip on X axis is clicked.
  4553. :return:
  4554. """
  4555. self.defaults.report_usage("on_flipx()")
  4556. obj_list = self.collection.get_selected()
  4557. xminlist = []
  4558. yminlist = []
  4559. xmaxlist = []
  4560. ymaxlist = []
  4561. if not obj_list:
  4562. self.inform.emit('[WARNING_NOTCL] %s' %
  4563. _("No object selected to Flip on X axis."))
  4564. else:
  4565. try:
  4566. # first get a bounding box to fit all
  4567. for obj in obj_list:
  4568. xmin, ymin, xmax, ymax = obj.bounds()
  4569. xminlist.append(xmin)
  4570. yminlist.append(ymin)
  4571. xmaxlist.append(xmax)
  4572. ymaxlist.append(ymax)
  4573. # get the minimum x,y and maximum x,y for all objects selected
  4574. xminimal = min(xminlist)
  4575. yminimal = min(yminlist)
  4576. xmaximal = max(xmaxlist)
  4577. ymaximal = max(ymaxlist)
  4578. px = 0.5 * (xminimal + xmaximal)
  4579. py = 0.5 * (yminimal + ymaximal)
  4580. # execute mirroring
  4581. for obj in obj_list:
  4582. obj.mirror('Y', [px, py])
  4583. obj.plot()
  4584. self.app_obj.object_changed.emit(obj)
  4585. self.inform.emit('[success] %s' %
  4586. _("Flip on X axis done."))
  4587. except Exception as e:
  4588. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  4589. return
  4590. def on_rotate(self, silent=False, preset=None):
  4591. """
  4592. Executed when Options -> Rotate Selection menu entry is clicked.
  4593. :param silent: If silent is True then use the preset value for the angle of the rotation.
  4594. :param preset: A value to be used as predefined angle for rotation.
  4595. :return:
  4596. """
  4597. self.defaults.report_usage("on_rotate()")
  4598. obj_list = self.collection.get_selected()
  4599. xminlist = []
  4600. yminlist = []
  4601. xmaxlist = []
  4602. ymaxlist = []
  4603. if not obj_list:
  4604. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Rotate."))
  4605. else:
  4606. if silent is False:
  4607. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4608. min=-360, max=360, decimals=4,
  4609. init_val=float(self.defaults['tools_transform_rotate']))
  4610. num, ok = rotatebox.get_value()
  4611. else:
  4612. num = preset
  4613. ok = True
  4614. if ok:
  4615. try:
  4616. # first get a bounding box to fit all
  4617. for obj in obj_list:
  4618. xmin, ymin, xmax, ymax = obj.bounds()
  4619. xminlist.append(xmin)
  4620. yminlist.append(ymin)
  4621. xmaxlist.append(xmax)
  4622. ymaxlist.append(ymax)
  4623. # get the minimum x,y and maximum x,y for all objects selected
  4624. xminimal = min(xminlist)
  4625. yminimal = min(yminlist)
  4626. xmaximal = max(xmaxlist)
  4627. ymaximal = max(ymaxlist)
  4628. px = 0.5 * (xminimal + xmaximal)
  4629. py = 0.5 * (yminimal + ymaximal)
  4630. for sel_obj in obj_list:
  4631. sel_obj.rotate(-float(num), point=(px, py))
  4632. sel_obj.plot()
  4633. self.app_obj.object_changed.emit(sel_obj)
  4634. self.inform.emit('[success] %s' % _("Rotation done."))
  4635. except Exception as e:
  4636. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Rotation movement was not executed."), str(e)))
  4637. return
  4638. def on_skewx(self):
  4639. """
  4640. Executed when the menu entry in Options -> Skew on X axis is clicked.
  4641. :return:
  4642. """
  4643. self.defaults.report_usage("on_skewx()")
  4644. obj_list = self.collection.get_selected()
  4645. xminlist = []
  4646. yminlist = []
  4647. if not obj_list:
  4648. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Skew/Shear on X axis."))
  4649. else:
  4650. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4651. min=-360, max=360, decimals=4,
  4652. init_val=float(self.defaults['tools_transform_skew_x']))
  4653. num, ok = skewxbox.get_value()
  4654. if ok:
  4655. # first get a bounding box to fit all
  4656. for obj in obj_list:
  4657. xmin, ymin, xmax, ymax = obj.bounds()
  4658. xminlist.append(xmin)
  4659. yminlist.append(ymin)
  4660. # get the minimum x,y and maximum x,y for all objects selected
  4661. xminimal = min(xminlist)
  4662. yminimal = min(yminlist)
  4663. for obj in obj_list:
  4664. obj.skew(num, 0, point=(xminimal, yminimal))
  4665. obj.plot()
  4666. self.app_obj.object_changed.emit(obj)
  4667. self.inform.emit('[success] %s' % _("Skew on X axis done."))
  4668. def on_skewy(self):
  4669. """
  4670. Executed when the menu entry in Options -> Skew on Y axis is clicked.
  4671. :return:
  4672. """
  4673. self.defaults.report_usage("on_skewy()")
  4674. obj_list = self.collection.get_selected()
  4675. xminlist = []
  4676. yminlist = []
  4677. if not obj_list:
  4678. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Skew/Shear on Y axis."))
  4679. else:
  4680. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  4681. min=-360, max=360, decimals=4,
  4682. init_val=float(self.defaults['tools_transform_skew_y']))
  4683. num, ok = skewybox.get_value()
  4684. if ok:
  4685. # first get a bounding box to fit all
  4686. for obj in obj_list:
  4687. xmin, ymin, xmax, ymax = obj.bounds()
  4688. xminlist.append(xmin)
  4689. yminlist.append(ymin)
  4690. # get the minimum x,y and maximum x,y for all objects selected
  4691. xminimal = min(xminlist)
  4692. yminimal = min(yminlist)
  4693. for obj in obj_list:
  4694. obj.skew(0, num, point=(xminimal, yminimal))
  4695. obj.plot()
  4696. self.app_obj.object_changed.emit(obj)
  4697. self.inform.emit('[success] %s' % _("Skew on Y axis done."))
  4698. def on_plots_updated(self):
  4699. """
  4700. Callback used to report when the plots have changed.
  4701. Adjust axes and zooms to fit.
  4702. :return: None
  4703. """
  4704. if self.is_legacy is False:
  4705. self.plotcanvas.update()
  4706. else:
  4707. self.plotcanvas.auto_adjust_axes()
  4708. self.on_zoom_fit()
  4709. self.collection.update_view()
  4710. # self.inform.emit(_("Plots updated ..."))
  4711. def on_toolbar_replot(self):
  4712. """
  4713. Callback for toolbar button. Re-plots all objects.
  4714. :return: None
  4715. """
  4716. self.log.debug("on_toolbar_replot()")
  4717. try:
  4718. obj = self.collection.get_active()
  4719. if obj:
  4720. obj.read_form()
  4721. else:
  4722. self.on_zoom_fit()
  4723. except AttributeError as e:
  4724. log.debug("on_toolbar_replot() -> %s" % str(e))
  4725. pass
  4726. self.plot_all()
  4727. def grid_status(self):
  4728. return True if self.ui.grid_snap_btn.isChecked() else False
  4729. def populate_cmenu_grids(self):
  4730. units = self.defaults['units'].lower()
  4731. # for act in self.ui.cmenu_gridmenu.actions():
  4732. # act.triggered.disconnect()
  4733. self.ui.cmenu_gridmenu.clear()
  4734. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  4735. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  4736. _("Grid On/Off"))
  4737. grid_toggle.setCheckable(True)
  4738. grid_toggle.setChecked(True) if self.grid_status() else grid_toggle.setChecked(False)
  4739. self.ui.cmenu_gridmenu.addSeparator()
  4740. for grid in sorted_list:
  4741. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  4742. "%s" % str(grid))
  4743. action.triggered.connect(self.set_grid)
  4744. self.ui.cmenu_gridmenu.addSeparator()
  4745. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/plus32.png'),
  4746. _("Add"))
  4747. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/delete32.png'),
  4748. _("Delete"))
  4749. grid_add.triggered.connect(self.on_grid_add)
  4750. grid_delete.triggered.connect(self.on_grid_delete)
  4751. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  4752. def set_grid(self):
  4753. menu_action = self.sender()
  4754. assert isinstance(menu_action, QtWidgets.QAction), "Expected QAction got %s" % type(menu_action)
  4755. self.ui.grid_gap_x_entry.setText(menu_action.text())
  4756. self.ui.grid_gap_y_entry.setText(menu_action.text())
  4757. def on_grid_add(self):
  4758. # ## Current application units in lower Case
  4759. units = self.defaults['units'].lower()
  4760. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  4761. text=_('Enter a Grid Value:'),
  4762. min=0.0000, max=99.9999, decimals=4)
  4763. grid_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/plus32.png'))
  4764. val, ok = grid_add_popup.get_value()
  4765. if ok:
  4766. if float(val) == 0:
  4767. self.inform.emit('[WARNING_NOTCL] %s' %
  4768. _("Please enter a grid value with non-zero value, in Float format."))
  4769. return
  4770. else:
  4771. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  4772. self.defaults["global_grid_context_menu"][str(units)].append(val)
  4773. self.inform.emit('[success] %s...' % _("New Grid added"))
  4774. else:
  4775. self.inform.emit('[WARNING_NOTCL] %s...' % _("Grid already exists"))
  4776. else:
  4777. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding New Grid cancelled"))
  4778. def on_grid_delete(self):
  4779. # ## Current application units in lower Case
  4780. units = self.defaults['units'].lower()
  4781. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  4782. text='Enter a Grid Value:',
  4783. min=0.0000, max=99.9999, decimals=4)
  4784. grid_del_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/delete32.png'))
  4785. val, ok = grid_del_popup.get_value()
  4786. if ok:
  4787. if float(val) == 0:
  4788. self.inform.emit('[WARNING_NOTCL] %s' %
  4789. _("Please enter a grid value with non-zero value, in Float format."))
  4790. return
  4791. else:
  4792. try:
  4793. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  4794. except ValueError:
  4795. self.inform.emit('[ERROR_NOTCL]%s...' % _(" Grid Value does not exist"))
  4796. return
  4797. self.inform.emit('[success] %s...' % _("Grid Value deleted"))
  4798. else:
  4799. self.inform.emit('[WARNING_NOTCL] %s...' % _("Delete Grid value cancelled"))
  4800. def on_shortcut_list(self):
  4801. self.defaults.report_usage("on_shortcut_list()")
  4802. # add the tab if it was closed
  4803. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  4804. # delete the absolute and relative position and messages in the infobar
  4805. # self.ui.position_label.setText("")
  4806. # self.ui.rel_position_label.setText("")
  4807. # hide coordinates toolbars in the infobar while in DB
  4808. self.ui.coords_toolbar.hide()
  4809. self.ui.delta_coords_toolbar.hide()
  4810. # Switch plot_area to preferences page
  4811. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  4812. # self.ui.show()
  4813. def on_select_tab(self, name):
  4814. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  4815. if self.ui.splitter.sizes()[0] == 0:
  4816. self.ui.splitter.setSizes([1, 1])
  4817. else:
  4818. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  4819. self.ui.splitter.setSizes([0, 1])
  4820. if name == 'project':
  4821. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  4822. elif name == 'selected':
  4823. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  4824. elif name == 'tool':
  4825. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  4826. def on_copy_name(self):
  4827. self.defaults.report_usage("on_copy_name()")
  4828. obj = self.collection.get_active()
  4829. try:
  4830. name = obj.options["name"]
  4831. except AttributeError:
  4832. log.debug("on_copy_name() --> No object selected to copy it's name")
  4833. self.inform.emit('[WARNING_NOTCL] %s' %
  4834. _(" No object selected to copy it's name"))
  4835. return
  4836. self.clipboard.setText(name)
  4837. self.inform.emit(_("Name copied on clipboard ..."))
  4838. def on_mouse_click_over_plot(self, event):
  4839. """
  4840. Default actions are:
  4841. :param event: Contains information about the event, like which button
  4842. was clicked, the pixel coordinates and the axes coordinates.
  4843. :return: None
  4844. """
  4845. self.pos = []
  4846. if self.is_legacy is False:
  4847. event_pos = event.pos
  4848. # pan_button = 2 if self.defaults["global_pan_button"] == '2'else 3
  4849. # # Set the mouse button for panning
  4850. # self.plotcanvas.view.camera.pan_button_setting = pan_button
  4851. else:
  4852. event_pos = (event.xdata, event.ydata)
  4853. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  4854. # pan_button = 3 if self.defaults["global_pan_button"] == '2' else 2
  4855. # So it can receive key presses
  4856. self.plotcanvas.native.setFocus()
  4857. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  4858. if self.grid_status():
  4859. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  4860. else:
  4861. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  4862. try:
  4863. if event.button == 1:
  4864. # Reset here the relative coordinates so there is a new reference on the click position
  4865. if self.rel_point1 is None:
  4866. self.rel_point1 = self.pos
  4867. else:
  4868. self.rel_point2 = copy(self.rel_point1)
  4869. self.rel_point1 = self.pos
  4870. self.on_mouse_move_over_plot(event, origin_click=True)
  4871. except Exception as e:
  4872. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  4873. def on_mouse_double_click_over_plot(self, event):
  4874. if event.button == 1:
  4875. self.doubleclick = True
  4876. def on_mouse_move_over_plot(self, event, origin_click=None):
  4877. """
  4878. Callback for the mouse motion event over the plot.
  4879. :param event: Contains information about the event.
  4880. :param origin_click
  4881. :return: None
  4882. """
  4883. if self.is_legacy is False:
  4884. event_pos = event.pos
  4885. if self.defaults["global_pan_button"] == '2':
  4886. pan_button = 2
  4887. else:
  4888. pan_button = 3
  4889. self.event_is_dragging = event.is_dragging
  4890. else:
  4891. event_pos = (event.xdata, event.ydata)
  4892. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  4893. if self.defaults["global_pan_button"] == '2':
  4894. pan_button = 3
  4895. else:
  4896. pan_button = 2
  4897. self.event_is_dragging = self.plotcanvas.is_dragging
  4898. # So it can receive key presses but not when the Tcl Shell is active
  4899. if not self.ui.shell_dock.isVisible():
  4900. if not self.plotcanvas.native.hasFocus():
  4901. self.plotcanvas.native.setFocus()
  4902. self.pos_jump = event_pos
  4903. self.ui.popMenu.mouse_is_panning = False
  4904. if origin_click is None:
  4905. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  4906. if event.button == pan_button and self.event_is_dragging == 1:
  4907. # if a popup menu is active don't change mouse_is_panning variable because is not True
  4908. if self.ui.popMenu.popup_active:
  4909. self.ui.popMenu.popup_active = False
  4910. return
  4911. self.ui.popMenu.mouse_is_panning = True
  4912. return
  4913. if self.rel_point1 is not None:
  4914. try: # May fail in case mouse not within axes
  4915. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  4916. if pos_canvas[0] is None or pos_canvas[1] is None:
  4917. return
  4918. if self.grid_status():
  4919. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4920. # Update cursor
  4921. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  4922. symbol='++', edge_color=self.cursor_color_3D,
  4923. edge_width=self.defaults["global_cursor_width"],
  4924. size=self.defaults["global_cursor_size"])
  4925. else:
  4926. pos = (pos_canvas[0], pos_canvas[1])
  4927. self.dx = pos[0] - float(self.rel_point1[0])
  4928. self.dy = pos[1] - float(self.rel_point1[1])
  4929. self.ui.position_label.setText("&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4930. "<b>Y</b>: %.4f&nbsp;" % (pos[0], pos[1]))
  4931. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4932. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  4933. units = self.defaults["units"].lower()
  4934. self.plotcanvas.text_hud.text = \
  4935. 'Dx:\t{:<.4f} [{:s}]\nDy:\t{:<.4f} [{:s}]\n\nX: \t{:<.4f} [{:s}]\nY: \t{:<.4f} [{:s}]'.format(
  4936. self.dx, units, self.dy, units, pos[0], units, pos[1], units)
  4937. self.mouse = [pos[0], pos[1]]
  4938. # if the mouse is moved and the LMB is clicked then the action is a selection
  4939. if self.event_is_dragging == 1 and event.button == 1:
  4940. self.delete_selection_shape()
  4941. if self.dx < 0:
  4942. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  4943. face_color=self.defaults['global_alt_sel_fill'])
  4944. self.selection_type = False
  4945. elif self.dx >= 0:
  4946. self.draw_moving_selection_shape(self.pos, pos)
  4947. self.selection_type = True
  4948. else:
  4949. self.selection_type = None
  4950. else:
  4951. self.selection_type = None
  4952. # hover effect - enabled in Preferences -> General -> appGUI Settings
  4953. if self.defaults['global_hover']:
  4954. for obj in self.collection.get_list():
  4955. try:
  4956. # select the object(s) only if it is enabled (plotted)
  4957. if obj.options['plot']:
  4958. if obj not in self.collection.get_selected():
  4959. poly_obj = Polygon(
  4960. [(obj.options['xmin'], obj.options['ymin']),
  4961. (obj.options['xmax'], obj.options['ymin']),
  4962. (obj.options['xmax'], obj.options['ymax']),
  4963. (obj.options['xmin'], obj.options['ymax'])]
  4964. )
  4965. if Point(pos).within(poly_obj):
  4966. if obj.isHovering is False:
  4967. obj.isHovering = True
  4968. obj.notHovering = True
  4969. # create the selection box around the selected object
  4970. self.draw_hover_shape(obj, color='#d1e0e0FF')
  4971. else:
  4972. if obj.notHovering is True:
  4973. obj.notHovering = False
  4974. obj.isHovering = False
  4975. self.delete_hover_shape()
  4976. except Exception:
  4977. # the Exception here will happen if we try to select on screen and we have an
  4978. # newly (and empty) just created Geometry or Excellon object that do not have the
  4979. # xmin, xmax, ymin, ymax options.
  4980. # In this case poly_obj creation (see above) will fail
  4981. pass
  4982. except Exception as e:
  4983. log.debug("App.on_mouse_move_over_plot() - rel_point1 is not None -> %s" % str(e))
  4984. self.ui.position_label.setText("")
  4985. self.ui.rel_position_label.setText("")
  4986. self.mouse = None
  4987. def on_mouse_click_release_over_plot(self, event):
  4988. """
  4989. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  4990. and has been registered in ''self.__init__()''.
  4991. :param event: contains information about the event.
  4992. :return:
  4993. """
  4994. if self.is_legacy is False:
  4995. event_pos = event.pos
  4996. right_button = 2
  4997. else:
  4998. event_pos = (event.xdata, event.ydata)
  4999. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5000. right_button = 3
  5001. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5002. if self.grid_status():
  5003. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5004. else:
  5005. pos = (pos_canvas[0], pos_canvas[1])
  5006. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  5007. # canvas menu
  5008. if event.button == right_button and self.ui.popMenu.mouse_is_panning is False: # right click
  5009. self.ui.popMenu.mouse_is_panning = False
  5010. self.cursor = QtGui.QCursor()
  5011. self.populate_cmenu_grids()
  5012. self.ui.popMenu.popup(self.cursor.pos())
  5013. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  5014. # selection and then select a type of selection ("enclosing" or "touching")
  5015. if event.button == 1: # left click
  5016. modifiers = QtWidgets.QApplication.keyboardModifiers()
  5017. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  5018. if modifiers == QtCore.Qt.ShiftModifier:
  5019. # do not auto open the Project Tab
  5020. self.click_noproject = True
  5021. self.clipboard.setText(
  5022. self.defaults["global_point_clipboard_format"] %
  5023. (self.decimals, self.pos[0], self.decimals, self.pos[1])
  5024. )
  5025. self.inform.emit('[success] %s' % _("Coordinates copied to clipboard."))
  5026. return
  5027. if self.doubleclick is True:
  5028. self.doubleclick = False
  5029. if self.collection.get_selected():
  5030. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5031. if self.ui.splitter.sizes()[0] == 0:
  5032. self.ui.splitter.setSizes([1, 1])
  5033. try:
  5034. # delete the selection shape(S) as it may be in the way
  5035. self.delete_selection_shape()
  5036. self.delete_hover_shape()
  5037. except Exception as e:
  5038. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() double click --> Error: %s" % str(e))
  5039. return
  5040. else:
  5041. # WORKAROUND for LEGACY MODE
  5042. if self.is_legacy is True:
  5043. # if there is no move on canvas then we have no dragging selection
  5044. if self.dx == 0 or self.dy == 0:
  5045. self.selection_type = None
  5046. if self.selection_type is not None:
  5047. try:
  5048. self.selection_area_handler(self.pos, pos, self.selection_type)
  5049. self.selection_type = None
  5050. except Exception as e:
  5051. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select area --> Error: %s" % str(e))
  5052. return
  5053. else:
  5054. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  5055. if key_modifier == QtCore.Qt.ShiftModifier:
  5056. mod_key = 'Shift'
  5057. elif key_modifier == QtCore.Qt.ControlModifier:
  5058. mod_key = 'Control'
  5059. else:
  5060. mod_key = None
  5061. try:
  5062. if self.command_active is None:
  5063. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  5064. # deselect, and if it's not selected then it will be selected
  5065. # If there is no active command (self.command_active is None) then we check if we clicked
  5066. # on a object by checking the bounding limits against mouse click position
  5067. if mod_key == self.defaults["global_mselect_key"]:
  5068. self.select_objects(key='multisel')
  5069. else:
  5070. # If there is no active command (self.command_active is None) then we check if
  5071. # we clicked on a object by checking the bounding limits against mouse click position
  5072. self.select_objects()
  5073. self.delete_hover_shape()
  5074. except Exception as e:
  5075. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select click --> Error: %s" % str(e))
  5076. return
  5077. def selection_area_handler(self, start_pos, end_pos, sel_type):
  5078. """
  5079. :param start_pos: mouse position when the selection LMB click was done
  5080. :param end_pos: mouse position when the left mouse button is released
  5081. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  5082. :return:
  5083. """
  5084. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  5085. # delete previous selection shape
  5086. self.delete_selection_shape()
  5087. # make all objects inactive
  5088. self.collection.set_all_inactive()
  5089. for obj in self.collection.get_list():
  5090. try:
  5091. # select the object(s) only if it is enabled (plotted)
  5092. if obj.options['plot']:
  5093. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  5094. (obj.options['xmax'], obj.options['ymin']),
  5095. (obj.options['xmax'], obj.options['ymax']),
  5096. (obj.options['xmin'], obj.options['ymax'])])
  5097. if sel_type is True:
  5098. if poly_obj.within(poly_selection):
  5099. # create the selection box around the selected object
  5100. if self.defaults['global_selection_shape'] is True:
  5101. self.draw_selection_shape(obj)
  5102. self.collection.set_active(obj.options['name'])
  5103. else:
  5104. if poly_selection.intersects(poly_obj):
  5105. # create the selection box around the selected object
  5106. if self.defaults['global_selection_shape'] is True:
  5107. self.draw_selection_shape(obj)
  5108. self.collection.set_active(obj.options['name'])
  5109. obj.selection_shape_drawn = True
  5110. except Exception as e:
  5111. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  5112. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  5113. # In this case poly_obj creation (see above) will fail
  5114. log.debug("App.selection_area_handler() --> %s" % str(e))
  5115. def select_objects(self, key=None):
  5116. """
  5117. Will select objects clicked on canvas
  5118. :param key: for future use in cumulative selection
  5119. :return:
  5120. """
  5121. # list where we store the overlapped objects under our mouse left click position
  5122. if key is None:
  5123. self.objects_under_the_click_list = []
  5124. # Populate the list with the overlapped objects on the click position
  5125. curr_x, curr_y = self.pos
  5126. for obj in self.all_objects_list:
  5127. # ScriptObject and DocumentObject objects can't be selected
  5128. if obj.kind == 'script' or obj.kind == 'document':
  5129. continue
  5130. if key == 'multisel' and obj.options['name'] in self.objects_under_the_click_list:
  5131. continue
  5132. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  5133. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  5134. if obj.options['name'] not in self.objects_under_the_click_list:
  5135. if obj.options['plot']:
  5136. # add objects to the objects_under_the_click list only if the object is plotted
  5137. # (active and not disabled)
  5138. self.objects_under_the_click_list.append(obj.options['name'])
  5139. try:
  5140. if self.objects_under_the_click_list:
  5141. curr_sel_obj = self.collection.get_active()
  5142. # case when there is only an object under the click and we toggle it
  5143. if len(self.objects_under_the_click_list) == 1:
  5144. if curr_sel_obj is None:
  5145. self.collection.set_active(self.objects_under_the_click_list[0])
  5146. curr_sel_obj = self.collection.get_active()
  5147. # create the selection box around the selected object
  5148. if self.defaults['global_selection_shape'] is True:
  5149. self.draw_selection_shape(curr_sel_obj)
  5150. curr_sel_obj.selection_shape_drawn = True
  5151. elif curr_sel_obj.options['name'] not in self.objects_under_the_click_list:
  5152. self.collection.on_objects_selection(False)
  5153. self.delete_selection_shape()
  5154. curr_sel_obj.selection_shape_drawn = False
  5155. self.collection.set_active(self.objects_under_the_click_list[0])
  5156. curr_sel_obj = self.collection.get_active()
  5157. # create the selection box around the selected object
  5158. if self.defaults['global_selection_shape'] is True:
  5159. self.draw_selection_shape(curr_sel_obj)
  5160. curr_sel_obj.selection_shape_drawn = True
  5161. self.selected_message(curr_sel_obj=curr_sel_obj)
  5162. elif curr_sel_obj.selection_shape_drawn is False:
  5163. if self.defaults['global_selection_shape'] is True:
  5164. self.draw_selection_shape(curr_sel_obj)
  5165. curr_sel_obj.selection_shape_drawn = True
  5166. else:
  5167. self.collection.on_objects_selection(False)
  5168. self.delete_selection_shape()
  5169. if self.call_source != 'app':
  5170. self.call_source = 'app'
  5171. self.selected_message(curr_sel_obj=curr_sel_obj)
  5172. else:
  5173. # If there is no selected object
  5174. # make active the first element of the overlapped objects list
  5175. if self.collection.get_active() is None:
  5176. self.collection.set_active(self.objects_under_the_click_list[0])
  5177. self.collection.get_by_name(self.objects_under_the_click_list[0]).selection_shape_drawn = True
  5178. name_sel_obj = self.collection.get_active().options['name']
  5179. # In case that there is a selected object but it is not in the overlapped object list
  5180. # make that object inactive and activate the first element in the overlapped object list
  5181. if name_sel_obj not in self.objects_under_the_click_list:
  5182. self.collection.set_inactive(name_sel_obj)
  5183. name_sel_obj = self.objects_under_the_click_list[0]
  5184. self.collection.set_active(name_sel_obj)
  5185. else:
  5186. sel_idx = self.objects_under_the_click_list.index(name_sel_obj)
  5187. self.collection.set_all_inactive()
  5188. self.collection.set_active(
  5189. self.objects_under_the_click_list[(sel_idx + 1) % len(self.objects_under_the_click_list)])
  5190. curr_sel_obj = self.collection.get_active()
  5191. # delete the possible selection box around a possible selected object
  5192. self.delete_selection_shape()
  5193. curr_sel_obj.selection_shape_drawn = False
  5194. # create the selection box around the selected object
  5195. if self.defaults['global_selection_shape'] is True:
  5196. self.draw_selection_shape(curr_sel_obj)
  5197. curr_sel_obj.selection_shape_drawn = True
  5198. self.selected_message(curr_sel_obj=curr_sel_obj)
  5199. else:
  5200. # deselect everything
  5201. self.collection.on_objects_selection(False)
  5202. # delete the possible selection box around a possible selected object
  5203. self.delete_selection_shape()
  5204. for o in self.collection.get_list():
  5205. o.selection_shape_drawn = False
  5206. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  5207. # only when working on App
  5208. if self.call_source == 'app':
  5209. if self.click_noproject is False:
  5210. # if the Tool Tab is in focus don't change focus to Project Tab
  5211. if not self.ui.notebook.currentWidget() is self.ui.tool_tab:
  5212. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5213. else:
  5214. # restore auto open the Project Tab
  5215. self.click_noproject = False
  5216. # delete any text in the status bar, implicitly the last object name that was selected
  5217. # self.inform.emit("")
  5218. else:
  5219. self.call_source = 'app'
  5220. except Exception as e:
  5221. log.error("[ERROR] Something went bad in App.select_objects(). %s" % str(e))
  5222. def selected_message(self, curr_sel_obj):
  5223. if curr_sel_obj:
  5224. if curr_sel_obj.kind == 'gerber':
  5225. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5226. color='green',
  5227. name=str(curr_sel_obj.options['name']),
  5228. tx=_("selected"))
  5229. )
  5230. elif curr_sel_obj.kind == 'excellon':
  5231. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5232. color='brown',
  5233. name=str(curr_sel_obj.options['name']),
  5234. tx=_("selected"))
  5235. )
  5236. elif curr_sel_obj.kind == 'cncjob':
  5237. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5238. color='blue',
  5239. name=str(curr_sel_obj.options['name']),
  5240. tx=_("selected"))
  5241. )
  5242. elif curr_sel_obj.kind == 'geometry':
  5243. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5244. color='red',
  5245. name=str(curr_sel_obj.options['name']),
  5246. tx=_("selected"))
  5247. )
  5248. def delete_hover_shape(self):
  5249. self.hover_shapes.clear()
  5250. self.hover_shapes.redraw()
  5251. def draw_hover_shape(self, sel_obj, color=None):
  5252. """
  5253. :param sel_obj: The object for which the hover shape must be drawn
  5254. :param color: The color of the hover shape
  5255. :return: None
  5256. """
  5257. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5258. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5259. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5260. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5261. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  5262. if self.defaults['units'].upper() == 'MM':
  5263. hover_rect = hover_rect.buffer(-0.1)
  5264. hover_rect = hover_rect.buffer(0.2)
  5265. else:
  5266. hover_rect = hover_rect.buffer(-0.00393)
  5267. hover_rect = hover_rect.buffer(0.00787)
  5268. # if color:
  5269. # face = Color(color)
  5270. # face.alpha = 0.2
  5271. # outline = Color(color, alpha=0.8)
  5272. # else:
  5273. # face = Color(self.defaults['global_sel_fill'])
  5274. # face.alpha = 0.2
  5275. # outline = self.defaults['global_sel_line']
  5276. if color:
  5277. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5278. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5279. else:
  5280. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5281. outline = self.defaults['global_sel_line']
  5282. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  5283. if self.is_legacy is True:
  5284. self.hover_shapes.redraw()
  5285. def delete_selection_shape(self):
  5286. self.move_tool.sel_shapes.clear()
  5287. self.move_tool.sel_shapes.redraw()
  5288. def draw_selection_shape(self, sel_obj, color=None):
  5289. """
  5290. Will draw a selection shape around the selected object.
  5291. :param sel_obj: The object for which the selection shape must be drawn
  5292. :param color: The color for the selection shape.
  5293. :return: None
  5294. """
  5295. if sel_obj is None:
  5296. return
  5297. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5298. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5299. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5300. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5301. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5302. if self.defaults['units'].upper() == 'MM':
  5303. sel_rect = sel_rect.buffer(-0.1)
  5304. sel_rect = sel_rect.buffer(0.2)
  5305. else:
  5306. sel_rect = sel_rect.buffer(-0.00393)
  5307. sel_rect = sel_rect.buffer(0.00787)
  5308. if color:
  5309. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5310. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5311. else:
  5312. if self.is_legacy is False:
  5313. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5314. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  5315. else:
  5316. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  5317. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  5318. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  5319. color=outline,
  5320. face_color=face,
  5321. update=True,
  5322. layer=0,
  5323. tolerance=None))
  5324. if self.is_legacy is True:
  5325. self.move_tool.sel_shapes.redraw()
  5326. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  5327. """
  5328. Will draw a selection shape when dragging mouse on canvas.
  5329. :param old_coords: Old coordinates
  5330. :param coords: New coordinates
  5331. :param kwargs: Keyword arguments
  5332. :return:
  5333. """
  5334. if 'color' in kwargs:
  5335. color = kwargs['color']
  5336. else:
  5337. color = self.defaults['global_sel_line']
  5338. if 'face_color' in kwargs:
  5339. face_color = kwargs['face_color']
  5340. else:
  5341. face_color = self.defaults['global_sel_fill']
  5342. if 'face_alpha' in kwargs:
  5343. face_alpha = kwargs['face_alpha']
  5344. else:
  5345. face_alpha = 0.3
  5346. x0, y0 = old_coords
  5347. x1, y1 = coords
  5348. pt1 = (x0, y0)
  5349. pt2 = (x1, y0)
  5350. pt3 = (x1, y1)
  5351. pt4 = (x0, y1)
  5352. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  5353. # color_t = Color(face_color)
  5354. # color_t.alpha = face_alpha
  5355. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  5356. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  5357. layer=0, tolerance=None)
  5358. if self.is_legacy is True:
  5359. self.move_tool.sel_shapes.redraw()
  5360. def on_file_new_click(self):
  5361. """
  5362. Callback for menu item File -> New.
  5363. Executed on clicking the Menu -> File -> New Project
  5364. :return:
  5365. """
  5366. if self.collection.get_list() and self.should_we_save:
  5367. msgbox = QtWidgets.QMessageBox()
  5368. # msgbox.setText("<B>Save changes ...</B>")
  5369. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  5370. "Creating a New project will delete them.\n"
  5371. "Do you want to Save the project?"))
  5372. msgbox.setWindowTitle(_("Save changes"))
  5373. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  5374. msgbox.setIcon(QtWidgets.QMessageBox.Question)
  5375. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  5376. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  5377. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  5378. msgbox.setDefaultButton(bt_yes)
  5379. msgbox.exec_()
  5380. response = msgbox.clickedButton()
  5381. if response == bt_yes:
  5382. self.on_file_saveprojectas()
  5383. elif response == bt_cancel:
  5384. return
  5385. elif response == bt_no:
  5386. self.on_file_new()
  5387. else:
  5388. self.on_file_new()
  5389. self.inform.emit('[success] %s...' % _("New Project created"))
  5390. def on_file_new(self, cli=None):
  5391. """
  5392. Returns the application to its startup state. This method is thread-safe.
  5393. :param cli: Boolean. If True this method was run from command line
  5394. :return: None
  5395. """
  5396. self.defaults.report_usage("on_file_new")
  5397. # Remove everything from memory
  5398. App.log.debug("on_file_new()")
  5399. # close any editor that might be open
  5400. if self.call_source != 'app':
  5401. self.editor2object(cleanup=True)
  5402. # ## EDITOR section
  5403. self.geo_editor = AppGeoEditor(self)
  5404. self.exc_editor = AppExcEditor(self)
  5405. self.grb_editor = AppGerberEditor(self)
  5406. # Clear pool
  5407. self.clear_pool()
  5408. for obj in self.collection.get_list():
  5409. # delete shapes left drawn from mark shape_collections, if any
  5410. if isinstance(obj, GerberObject):
  5411. try:
  5412. for el in obj.mark_shapes:
  5413. obj.mark_shapes[el].clear(update=True)
  5414. obj.mark_shapes[el].enabled = False
  5415. del el
  5416. except AttributeError:
  5417. pass
  5418. # also delete annotation shapes, if any
  5419. elif isinstance(obj, CNCJobObject):
  5420. try:
  5421. obj.text_col.enabled = False
  5422. del obj.text_col
  5423. obj.annotation.clear(update=True)
  5424. del obj.annotation
  5425. except AttributeError:
  5426. pass
  5427. # delete the exclusion areas
  5428. self.exc_areas.clear_shapes()
  5429. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  5430. self.shell.init_tcl()
  5431. # delete any selection shape on canvas
  5432. self.delete_selection_shape()
  5433. # delete all FlatCAM objects
  5434. self.collection.delete_all()
  5435. # add in Selected tab an initial text that describe the flow of work in FlatCAm
  5436. self.setup_component_editor()
  5437. # Clear project filename
  5438. self.project_filename = None
  5439. # Load the application defaults
  5440. self.defaults.load(filename=os.path.join(self.data_path, 'current_defaults.FlatConfig'))
  5441. # Re-fresh project options
  5442. self.on_options_app2project()
  5443. # Init FlatCAMTools
  5444. self.init_tools()
  5445. # Try to close all tabs in the PlotArea but only if the appGUI is active (CLI is None)
  5446. if cli is None:
  5447. # we need to go in reverse because once we remove a tab then the index changes
  5448. # meaning that removing the first tab (idx = 0) then the tab at former idx = 1 will assume idx = 0
  5449. # and so on. Therefore the deletion should be done in reverse
  5450. wdg_count = self.ui.plot_tab_area.tabBar.count() - 1
  5451. for index in range(wdg_count, -1, -1):
  5452. try:
  5453. self.ui.plot_tab_area.closeTab(index)
  5454. except Exception as e:
  5455. log.debug("App.on_file_new() --> %s" % str(e))
  5456. # # And then add again the Plot Area
  5457. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  5458. self.ui.plot_tab_area.protectTab(0)
  5459. # take the focus of the Notebook on Project Tab.
  5460. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5461. self.set_ui_title(name=_("New Project - Not saved"))
  5462. def obj_properties(self):
  5463. """
  5464. Will launch the object Properties Tool
  5465. :return:
  5466. """
  5467. self.defaults.report_usage("obj_properties()")
  5468. self.properties_tool.run(toggle=False)
  5469. def on_project_context_save(self):
  5470. """
  5471. Wrapper, will save the object function of it's type
  5472. :return:
  5473. """
  5474. obj = self.collection.get_active()
  5475. if type(obj) == GeometryObject:
  5476. self.on_file_exportdxf()
  5477. elif type(obj) == ExcellonObject:
  5478. self.on_file_saveexcellon()
  5479. elif type(obj) == CNCJobObject:
  5480. obj.on_exportgcode_button_click()
  5481. elif type(obj) == GerberObject:
  5482. self.on_file_savegerber()
  5483. elif type(obj) == ScriptObject:
  5484. self.on_file_savescript()
  5485. elif type(obj) == DocumentObject:
  5486. self.on_file_savedocument()
  5487. def obj_move(self):
  5488. """
  5489. Callback for the Move menu entry in various Context Menu's.
  5490. :return:
  5491. """
  5492. self.defaults.report_usage("obj_move()")
  5493. self.move_tool.run(toggle=False)
  5494. def on_fileopengerber(self, signal, name=None):
  5495. """
  5496. File menu callback for opening a Gerber.
  5497. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5498. :param name:
  5499. :return: None
  5500. """
  5501. self.defaults.report_usage("on_fileopengerber")
  5502. App.log.debug("on_fileopengerber()")
  5503. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 " \
  5504. "*.gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb " \
  5505. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd *.outline);;" \
  5506. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko " \
  5507. "*.outline);;" \
  5508. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  5509. "*.mil);;" \
  5510. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  5511. "Allegro Files (*.art);;" \
  5512. "Mentor Files (*.pho *.gdo);;" \
  5513. "All Files (*.*)"
  5514. if name is None:
  5515. try:
  5516. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  5517. directory=self.get_last_folder(),
  5518. filter=_filter_,
  5519. initialFilter=self.last_op_gerber_filter)
  5520. except TypeError:
  5521. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  5522. filenames = [str(filename) for filename in filenames]
  5523. self.last_op_gerber_filter = _f
  5524. else:
  5525. filenames = [name]
  5526. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5527. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5528. _("Opening Gerber file.")),
  5529. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5530. color=QtGui.QColor("gray"))
  5531. if len(filenames) == 0:
  5532. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5533. else:
  5534. for filename in filenames:
  5535. if filename != '':
  5536. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  5537. def on_fileopenexcellon(self, signal, name=None):
  5538. """
  5539. File menu callback for opening an Excellon file.
  5540. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5541. :param name:
  5542. :return: None
  5543. """
  5544. self.defaults.report_usage("on_fileopenexcellon")
  5545. App.log.debug("on_fileopenexcellon()")
  5546. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  5547. "All Files (*.*)"
  5548. if name is None:
  5549. try:
  5550. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  5551. directory=self.get_last_folder(),
  5552. filter=_filter_,
  5553. initialFilter=self.last_op_excellon_filter)
  5554. except TypeError:
  5555. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  5556. filenames = [str(filename) for filename in filenames]
  5557. self.last_op_excellon_filter = _f
  5558. else:
  5559. filenames = [str(name)]
  5560. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5561. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5562. _("Opening Excellon file.")),
  5563. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5564. color=QtGui.QColor("gray"))
  5565. if len(filenames) == 0:
  5566. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5567. else:
  5568. for filename in filenames:
  5569. if filename != '':
  5570. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  5571. def on_fileopengcode(self, signal, name=None):
  5572. """
  5573. File menu call back for opening gcode.
  5574. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5575. :param name:
  5576. :return:
  5577. """
  5578. self.defaults.report_usage("on_fileopengcode")
  5579. App.log.debug("on_fileopengcode()")
  5580. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  5581. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  5582. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.sbp *.mpf);;" \
  5583. "All Files (*.*)"
  5584. if name is None:
  5585. try:
  5586. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  5587. directory=self.get_last_folder(),
  5588. filter=_filter_,
  5589. initialFilter=self.last_op_gcode_filter)
  5590. except TypeError:
  5591. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  5592. filenames = [str(filename) for filename in filenames]
  5593. self.last_op_gcode_filter = _f
  5594. else:
  5595. filenames = [name]
  5596. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5597. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5598. _("Opening G-Code file.")),
  5599. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5600. color=QtGui.QColor("gray"))
  5601. if len(filenames) == 0:
  5602. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5603. else:
  5604. for filename in filenames:
  5605. if filename != '':
  5606. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename, None, True]})
  5607. def on_file_openproject(self, signal):
  5608. """
  5609. File menu callback for opening a project.
  5610. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5611. :return: None
  5612. """
  5613. self.defaults.report_usage("on_file_openproject")
  5614. App.log.debug("on_file_openproject()")
  5615. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  5616. try:
  5617. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  5618. directory=self.get_last_folder(), filter=_filter_)
  5619. except TypeError:
  5620. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  5621. # The Qt methods above will return a QString which can cause problems later.
  5622. # So far json.dump() will fail to serialize it.
  5623. # TODO: Improve the serialization methods and remove this fix.
  5624. filename = str(filename)
  5625. if filename == "":
  5626. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5627. else:
  5628. # self.worker_task.emit({'fcn': self.open_project,
  5629. # 'params': [filename]})
  5630. # The above was failing because open_project() is not
  5631. # thread safe. The new_project()
  5632. self.open_project(filename)
  5633. def on_fileopenhpgl2(self, signal, name=None):
  5634. """
  5635. File menu callback for opening a HPGL2.
  5636. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5637. :param name:
  5638. :return: None
  5639. """
  5640. self.defaults.report_usage("on_fileopenhpgl2")
  5641. App.log.debug("on_fileopenhpgl2()")
  5642. _filter_ = "HPGL2 Files (*.plt);;" \
  5643. "All Files (*.*)"
  5644. if name is None:
  5645. try:
  5646. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"),
  5647. directory=self.get_last_folder(),
  5648. filter=_filter_)
  5649. except TypeError:
  5650. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"), filter=_filter_)
  5651. filenames = [str(filename) for filename in filenames]
  5652. else:
  5653. filenames = [name]
  5654. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  5655. "Canvas initialization finished in"), '%.2f' % self.used_time,
  5656. _("Opening HPGL2 file.")),
  5657. alignment=Qt.AlignBottom | Qt.AlignLeft,
  5658. color=QtGui.QColor("gray"))
  5659. if len(filenames) == 0:
  5660. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5661. else:
  5662. for filename in filenames:
  5663. if filename != '':
  5664. self.worker_task.emit({'fcn': self.open_hpgl2, 'params': [filename]})
  5665. def on_file_openconfig(self, signal):
  5666. """
  5667. File menu callback for opening a config file.
  5668. :param signal: required because clicking the entry will generate a checked signal which needs a container
  5669. :return: None
  5670. """
  5671. self.defaults.report_usage("on_file_openconfig")
  5672. App.log.debug("on_file_openconfig()")
  5673. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  5674. try:
  5675. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  5676. directory=self.data_path, filter=_filter_)
  5677. except TypeError:
  5678. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  5679. filter=_filter_)
  5680. if filename == "":
  5681. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5682. else:
  5683. self.open_config_file(filename)
  5684. def on_file_exportsvg(self):
  5685. """
  5686. Callback for menu item File->Export SVG.
  5687. :return: None
  5688. """
  5689. self.defaults.report_usage("on_file_exportsvg")
  5690. App.log.debug("on_file_exportsvg()")
  5691. obj = self.collection.get_active()
  5692. if obj is None:
  5693. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5694. msg = _("Please Select a Geometry object to export")
  5695. msgbox = QtWidgets.QMessageBox()
  5696. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  5697. msgbox.setInformativeText(msg)
  5698. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5699. msgbox.setDefaultButton(bt_ok)
  5700. msgbox.exec_()
  5701. return
  5702. # Check for more compatible types and add as required
  5703. if (not isinstance(obj, GeometryObject)
  5704. and not isinstance(obj, GerberObject)
  5705. and not isinstance(obj, CNCJobObject)
  5706. and not isinstance(obj, ExcellonObject)):
  5707. msg = '[ERROR_NOTCL] %s' % \
  5708. _("Only Geometry, Gerber and CNCJob objects can be used.")
  5709. msgbox = QtWidgets.QMessageBox()
  5710. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  5711. msgbox.setInformativeText(msg)
  5712. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5713. msgbox.setDefaultButton(bt_ok)
  5714. msgbox.exec_()
  5715. return
  5716. name = obj.options["name"]
  5717. _filter = "SVG File (*.svg);;All Files (*.*)"
  5718. try:
  5719. filename, _f = FCFileSaveDialog.get_saved_filename(
  5720. caption=_("Export SVG"),
  5721. directory=self.get_last_save_folder() + '/' + str(name) + '_svg',
  5722. ext_filter=_filter)
  5723. except TypeError:
  5724. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export SVG"), ext_filter=_filter)
  5725. filename = str(filename)
  5726. if filename == "":
  5727. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5728. return
  5729. else:
  5730. self.export_svg(name, filename)
  5731. if self.defaults["global_open_style"] is False:
  5732. self.file_opened.emit("SVG", filename)
  5733. self.file_saved.emit("SVG", filename)
  5734. def on_file_exportpng(self):
  5735. self.defaults.report_usage("on_file_exportpng")
  5736. App.log.debug("on_file_exportpng()")
  5737. self.date = str(datetime.today()).rpartition('.')[0]
  5738. self.date = ''.join(c for c in self.date if c not in ':-')
  5739. self.date = self.date.replace(' ', '_')
  5740. data = None
  5741. if self.is_legacy is False:
  5742. image = _screenshot(alpha=False)
  5743. data = np.asarray(image)
  5744. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  5745. self.inform.emit('[[WARNING_NOTCL]] %s' % _('Data must be a 3D array with last dimension 3 or 4'))
  5746. return
  5747. filter_ = "PNG File (*.png);;All Files (*.*)"
  5748. try:
  5749. filename, _f = FCFileSaveDialog.get_saved_filename(
  5750. caption=_("Export PNG Image"),
  5751. directory=self.get_last_save_folder() + '/png_' + self.date,
  5752. ext_filter=filter_)
  5753. except TypeError:
  5754. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export PNG Image"), ext_filter=filter_)
  5755. filename = str(filename)
  5756. if filename == "":
  5757. self.inform.emit(_("Cancelled."))
  5758. return
  5759. else:
  5760. if self.is_legacy is False:
  5761. write_png(filename, data)
  5762. else:
  5763. self.plotcanvas.figure.savefig(filename)
  5764. if self.defaults["global_open_style"] is False:
  5765. self.file_opened.emit("png", filename)
  5766. self.file_saved.emit("png", filename)
  5767. def on_file_savegerber(self):
  5768. """
  5769. Callback for menu item in Project context menu.
  5770. :return: None
  5771. """
  5772. self.defaults.report_usage("on_file_savegerber")
  5773. App.log.debug("on_file_savegerber()")
  5774. obj = self.collection.get_active()
  5775. if obj is None:
  5776. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5777. return
  5778. # Check for more compatible types and add as required
  5779. if not isinstance(obj, GerberObject):
  5780. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  5781. return
  5782. name = self.collection.get_active().options["name"]
  5783. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  5784. try:
  5785. filename, _f = FCFileSaveDialog.get_saved_filename(
  5786. caption="Save Gerber source file",
  5787. directory=self.get_last_save_folder() + '/' + name,
  5788. ext_filter=_filter)
  5789. except TypeError:
  5790. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Gerber source file"), ext_filter=_filter)
  5791. filename = str(filename)
  5792. if filename == "":
  5793. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5794. return
  5795. else:
  5796. self.save_source_file(name, filename)
  5797. if self.defaults["global_open_style"] is False:
  5798. self.file_opened.emit("Gerber", filename)
  5799. self.file_saved.emit("Gerber", filename)
  5800. def on_file_savescript(self):
  5801. """
  5802. Callback for menu item in Project context menu.
  5803. :return: None
  5804. """
  5805. self.defaults.report_usage("on_file_savescript")
  5806. App.log.debug("on_file_savescript()")
  5807. obj = self.collection.get_active()
  5808. if obj is None:
  5809. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5810. return
  5811. # Check for more compatible types and add as required
  5812. if not isinstance(obj, ScriptObject):
  5813. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Script objects can be saved as TCL Script files..."))
  5814. return
  5815. name = self.collection.get_active().options["name"]
  5816. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  5817. try:
  5818. filename, _f = FCFileSaveDialog.get_saved_filename(
  5819. caption="Save Script source file",
  5820. directory=self.get_last_save_folder() + '/' + name,
  5821. ext_filter=_filter)
  5822. except TypeError:
  5823. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Script source file"), ext_filter=_filter)
  5824. filename = str(filename)
  5825. if filename == "":
  5826. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5827. return
  5828. else:
  5829. self.save_source_file(name, filename)
  5830. if self.defaults["global_open_style"] is False:
  5831. self.file_opened.emit("Script", filename)
  5832. self.file_saved.emit("Script", filename)
  5833. def on_file_savedocument(self):
  5834. """
  5835. Callback for menu item in Project context menu.
  5836. :return: None
  5837. """
  5838. self.defaults.report_usage("on_file_savedocument")
  5839. App.log.debug("on_file_savedocument()")
  5840. obj = self.collection.get_active()
  5841. if obj is None:
  5842. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5843. return
  5844. # Check for more compatible types and add as required
  5845. if not isinstance(obj, ScriptObject):
  5846. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Document objects can be saved as Document files..."))
  5847. return
  5848. name = self.collection.get_active().options["name"]
  5849. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  5850. try:
  5851. filename, _f = FCFileSaveDialog.get_saved_filename(
  5852. caption="Save Document source file",
  5853. directory=self.get_last_save_folder() + '/' + name,
  5854. ext_filter=_filter)
  5855. except TypeError:
  5856. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Document source file"),
  5857. ext_filter=_filter)
  5858. filename = str(filename)
  5859. if filename == "":
  5860. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5861. return
  5862. else:
  5863. self.save_source_file(name, filename)
  5864. if self.defaults["global_open_style"] is False:
  5865. self.file_opened.emit("Document", filename)
  5866. self.file_saved.emit("Document", filename)
  5867. def on_file_saveexcellon(self):
  5868. """
  5869. Callback for menu item in project context menu.
  5870. :return: None
  5871. """
  5872. self.defaults.report_usage("on_file_saveexcellon")
  5873. App.log.debug("on_file_saveexcellon()")
  5874. obj = self.collection.get_active()
  5875. if obj is None:
  5876. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5877. return
  5878. # Check for more compatible types and add as required
  5879. if not isinstance(obj, ExcellonObject):
  5880. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  5881. return
  5882. name = self.collection.get_active().options["name"]
  5883. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  5884. try:
  5885. filename, _f = FCFileSaveDialog.get_saved_filename(
  5886. caption=_("Save Excellon source file"),
  5887. directory=self.get_last_save_folder() + '/' + name,
  5888. ext_filter=_filter)
  5889. except TypeError:
  5890. filename, _f = FCFileSaveDialog.get_saved_filename(
  5891. caption=_("Save Excellon source file"), ext_filter=_filter)
  5892. filename = str(filename)
  5893. if filename == "":
  5894. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5895. return
  5896. else:
  5897. self.save_source_file(name, filename)
  5898. if self.defaults["global_open_style"] is False:
  5899. self.file_opened.emit("Excellon", filename)
  5900. self.file_saved.emit("Excellon", filename)
  5901. def on_file_exportexcellon(self):
  5902. """
  5903. Callback for menu item File->Export->Excellon.
  5904. :return: None
  5905. """
  5906. self.defaults.report_usage("on_file_exportexcellon")
  5907. App.log.debug("on_file_exportexcellon()")
  5908. obj = self.collection.get_active()
  5909. if obj is None:
  5910. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5911. return
  5912. # Check for more compatible types and add as required
  5913. if not isinstance(obj, ExcellonObject):
  5914. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  5915. return
  5916. name = self.collection.get_active().options["name"]
  5917. _filter = self.defaults["excellon_save_filters"]
  5918. try:
  5919. filename, _f = FCFileSaveDialog.get_saved_filename(
  5920. caption=_("Export Excellon"),
  5921. directory=self.get_last_save_folder() + '/' + name,
  5922. ext_filter=_filter)
  5923. except TypeError:
  5924. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Excellon"), ext_filter=_filter)
  5925. filename = str(filename)
  5926. if filename == "":
  5927. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5928. return
  5929. else:
  5930. used_extension = filename.rpartition('.')[2]
  5931. obj.update_filters(last_ext=used_extension, filter_string='excellon_save_filters')
  5932. self.export_excellon(name, filename)
  5933. if self.defaults["global_open_style"] is False:
  5934. self.file_opened.emit("Excellon", filename)
  5935. self.file_saved.emit("Excellon", filename)
  5936. def on_file_exportgerber(self):
  5937. """
  5938. Callback for menu item File->Export->Gerber.
  5939. :return: None
  5940. """
  5941. self.defaults.report_usage("on_file_exportgerber")
  5942. App.log.debug("on_file_exportgerber()")
  5943. obj = self.collection.get_active()
  5944. if obj is None:
  5945. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5946. return
  5947. # Check for more compatible types and add as required
  5948. if not isinstance(obj, GerberObject):
  5949. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  5950. return
  5951. name = self.collection.get_active().options["name"]
  5952. _filter_ = self.defaults['gerber_save_filters']
  5953. try:
  5954. filename, _f = FCFileSaveDialog.get_saved_filename(
  5955. caption=_("Export Gerber"),
  5956. directory=self.get_last_save_folder() + '/' + name,
  5957. ext_filter=_filter_)
  5958. except TypeError:
  5959. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Gerber"), ext_filter=_filter_)
  5960. filename = str(filename)
  5961. if filename == "":
  5962. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  5963. return
  5964. else:
  5965. used_extension = filename.rpartition('.')[2]
  5966. obj.update_filters(last_ext=used_extension, filter_string='gerber_save_filters')
  5967. self.export_gerber(name, filename)
  5968. if self.defaults["global_open_style"] is False:
  5969. self.file_opened.emit("Gerber", filename)
  5970. self.file_saved.emit("Gerber", filename)
  5971. def on_file_exportdxf(self):
  5972. """
  5973. Callback for menu item File->Export DXF.
  5974. :return: None
  5975. """
  5976. self.defaults.report_usage("on_file_exportdxf")
  5977. App.log.debug("on_file_exportdxf()")
  5978. obj = self.collection.get_active()
  5979. if obj is None:
  5980. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  5981. msg = _("Please Select a Geometry object to export")
  5982. msgbox = QtWidgets.QMessageBox()
  5983. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  5984. msgbox.setInformativeText(msg)
  5985. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5986. msgbox.setDefaultButton(bt_ok)
  5987. msgbox.exec_()
  5988. return
  5989. # Check for more compatible types and add as required
  5990. if not isinstance(obj, GeometryObject):
  5991. msg = '[ERROR_NOTCL] %s' % _("Only Geometry objects can be used.")
  5992. msgbox = QtWidgets.QMessageBox()
  5993. msgbox.setIcon(QtWidgets.QMessageBox.Warning)
  5994. msgbox.setInformativeText(msg)
  5995. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5996. msgbox.setDefaultButton(bt_ok)
  5997. msgbox.exec_()
  5998. return
  5999. name = self.collection.get_active().options["name"]
  6000. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  6001. try:
  6002. filename, _f = FCFileSaveDialog.get_saved_filename(
  6003. caption=_("Export DXF"),
  6004. directory=self.get_last_save_folder() + '/' + name,
  6005. ext_filter=_filter_)
  6006. except TypeError:
  6007. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export DXF"), ext_filter=_filter_)
  6008. filename = str(filename)
  6009. if filename == "":
  6010. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6011. return
  6012. else:
  6013. self.export_dxf(name, filename)
  6014. if self.defaults["global_open_style"] is False:
  6015. self.file_opened.emit("DXF", filename)
  6016. self.file_saved.emit("DXF", filename)
  6017. def on_file_importsvg(self, type_of_obj):
  6018. """
  6019. Callback for menu item File->Import SVG.
  6020. :param type_of_obj: to import the SVG as Geometry or as Gerber
  6021. :type type_of_obj: str
  6022. :return: None
  6023. """
  6024. self.defaults.report_usage("on_file_importsvg")
  6025. App.log.debug("on_file_importsvg()")
  6026. _filter_ = "SVG File .svg (*.svg);;All Files (*.*)"
  6027. try:
  6028. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6029. directory=self.get_last_folder(), filter=_filter_)
  6030. except TypeError:
  6031. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6032. filter=_filter_)
  6033. if type_of_obj != "geometry" and type_of_obj != "gerber":
  6034. type_of_obj = "geometry"
  6035. filenames = [str(filename) for filename in filenames]
  6036. if len(filenames) == 0:
  6037. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6038. else:
  6039. for filename in filenames:
  6040. if filename != '':
  6041. self.worker_task.emit({'fcn': self.import_svg,
  6042. 'params': [filename, type_of_obj]})
  6043. def on_file_importdxf(self, type_of_obj):
  6044. """
  6045. Callback for menu item File->Import DXF.
  6046. :param type_of_obj: to import the DXF as Geometry or as Gerber
  6047. :type type_of_obj: str
  6048. :return: None
  6049. """
  6050. self.defaults.report_usage("on_file_importdxf")
  6051. App.log.debug("on_file_importdxf()")
  6052. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  6053. try:
  6054. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6055. directory=self.get_last_folder(),
  6056. filter=_filter_)
  6057. except TypeError:
  6058. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6059. filter=_filter_)
  6060. if type_of_obj != "geometry" and type_of_obj != "gerber":
  6061. type_of_obj = "geometry"
  6062. filenames = [str(filename) for filename in filenames]
  6063. if len(filenames) == 0:
  6064. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6065. else:
  6066. for filename in filenames:
  6067. if filename != '':
  6068. self.worker_task.emit({'fcn': self.import_dxf,
  6069. 'params': [filename, type_of_obj]})
  6070. # ###############################################################################################################
  6071. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  6072. # ###############################################################################################################
  6073. def init_code_editor(self, name):
  6074. self.text_editor_tab = AppTextEditor(app=self, plain_text=True)
  6075. # add the tab if it was closed
  6076. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  6077. self.text_editor_tab.setObjectName('text_editor_tab')
  6078. # delete the absolute and relative position and messages in the infobar
  6079. # self.ui.position_label.setText("")
  6080. # self.ui.rel_position_label.setText("")
  6081. # hide coordinates toolbars in the infobar while in DB
  6082. self.ui.coords_toolbar.hide()
  6083. self.ui.delta_coords_toolbar.hide()
  6084. # first clear previous text in text editor (if any)
  6085. self.text_editor_tab.code_editor.clear()
  6086. self.text_editor_tab.code_editor.setReadOnly(False)
  6087. self.toggle_codeeditor = True
  6088. self.text_editor_tab.code_editor.completer_enable = False
  6089. self.text_editor_tab.buttonRun.hide()
  6090. # make sure to keep a reference to the code editor
  6091. self.reference_code_editor = self.text_editor_tab.code_editor
  6092. # Switch plot_area to CNCJob tab
  6093. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  6094. def on_view_source(self):
  6095. """
  6096. Called when the user wants to see the source file of the selected object
  6097. :return:
  6098. """
  6099. self.inform.emit('%s' % _("Viewing the source code of the selected object."))
  6100. self.proc_container.view.set_busy(_("Loading..."))
  6101. try:
  6102. obj = self.collection.get_active()
  6103. except Exception as e:
  6104. log.debug("App.on_view_source() --> %s" % str(e))
  6105. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  6106. return 'fail'
  6107. if obj is None:
  6108. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  6109. return 'fail'
  6110. flt = "All Files (*.*)"
  6111. if obj.kind == 'gerber':
  6112. flt = "Gerber Files .gbr (*.GBR);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6113. elif obj.kind == 'excellon':
  6114. flt = "Excellon Files .drl (*.DRL);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6115. elif obj.kind == 'cncjob':
  6116. flt = "GCode Files .nc (*.NC);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6117. self.source_editor_tab = AppTextEditor(app=self, plain_text=True)
  6118. # add the tab if it was closed
  6119. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  6120. self.source_editor_tab.setObjectName('source_editor_tab')
  6121. # delete the absolute and relative position and messages in the infobar
  6122. # self.ui.position_label.setText("")
  6123. # self.ui.rel_position_label.setText("")
  6124. # hide coordinates toolbars in the infobar while in DB
  6125. self.ui.coords_toolbar.hide()
  6126. self.ui.delta_coords_toolbar.hide()
  6127. # first clear previous text in text editor (if any)
  6128. self.source_editor_tab.code_editor.clear()
  6129. self.source_editor_tab.code_editor.setReadOnly(False)
  6130. self.source_editor_tab.code_editor.completer_enable = False
  6131. self.source_editor_tab.buttonRun.hide()
  6132. # Switch plot_area to CNCJob tab
  6133. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  6134. try:
  6135. self.source_editor_tab.buttonOpen.clicked.disconnect()
  6136. except TypeError:
  6137. pass
  6138. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  6139. try:
  6140. self.source_editor_tab.buttonSave.clicked.disconnect()
  6141. except TypeError:
  6142. pass
  6143. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  6144. # then append the text from GCode to the text editor
  6145. if obj.kind == 'cncjob':
  6146. try:
  6147. file = obj.export_gcode(
  6148. preamble=self.defaults["cncjob_prepend"],
  6149. postamble=self.defaults["cncjob_append"],
  6150. to_file=True)
  6151. if file == 'fail':
  6152. return 'fail'
  6153. except AttributeError:
  6154. self.inform.emit('[WARNING_NOTCL] %s' %
  6155. _("There is no selected object for which to see it's source file code."))
  6156. return 'fail'
  6157. else:
  6158. try:
  6159. file = StringIO(obj.source_file)
  6160. except (AttributeError, TypeError):
  6161. self.inform.emit('[WARNING_NOTCL] %s' %
  6162. _("There is no selected object for which to see it's source file code."))
  6163. return 'fail'
  6164. self.source_editor_tab.t_frame.hide()
  6165. try:
  6166. self.source_editor_tab.code_editor.setPlainText(file.getvalue())
  6167. # for line in file:
  6168. # QtWidgets.QApplication.processEvents()
  6169. # proc_line = str(line).strip('\n')
  6170. # self.source_editor_tab.code_editor.append(proc_line)
  6171. except Exception as e:
  6172. log.debug('App.on_view_source() -->%s' % str(e))
  6173. self.inform.emit('[ERROR] %s: %s' % (_('Failed to load the source code for the selected object'), str(e)))
  6174. return
  6175. self.source_editor_tab.handleTextChanged()
  6176. self.source_editor_tab.t_frame.show()
  6177. self.source_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.Start)
  6178. self.proc_container.view.set_idle()
  6179. # self.ui.show()
  6180. def on_toggle_code_editor(self):
  6181. self.defaults.report_usage("on_toggle_code_editor()")
  6182. if self.toggle_codeeditor is False:
  6183. self.init_code_editor(name=_("Code Editor"))
  6184. self.text_editor_tab.buttonOpen.clicked.disconnect()
  6185. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  6186. self.text_editor_tab.buttonSave.clicked.disconnect()
  6187. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  6188. else:
  6189. for idx in range(self.ui.plot_tab_area.count()):
  6190. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  6191. self.ui.plot_tab_area.closeTab(idx)
  6192. break
  6193. self.toggle_codeeditor = False
  6194. def on_code_editor_close(self):
  6195. self.toggle_codeeditor = False
  6196. def goto_text_line(self):
  6197. """
  6198. Will scroll a text to the specified text line.
  6199. :return: None
  6200. """
  6201. dia_box = Dialog_box(title=_("Go to Line ..."),
  6202. label=_("Line:"),
  6203. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  6204. initial_text='')
  6205. try:
  6206. line = int(dia_box.location) - 1
  6207. except (ValueError, TypeError):
  6208. line = 0
  6209. if dia_box.ok:
  6210. # make sure to move first the cursor at the end so after finding the line the line will be positioned
  6211. # at the top of the window
  6212. self.ui.plot_tab_area.currentWidget().code_editor.moveCursor(QTextCursor.End)
  6213. # get the document() of the AppTextEditor
  6214. doc = self.ui.plot_tab_area.currentWidget().code_editor.document()
  6215. # create a Text Cursor based on the searched line
  6216. cursor = QTextCursor(doc.findBlockByLineNumber(line))
  6217. # set cursor of the code editor with the cursor at the searcehd line
  6218. self.ui.plot_tab_area.currentWidget().code_editor.setTextCursor(cursor)
  6219. def on_filenewscript(self, silent=False):
  6220. """
  6221. Will create a new script file and open it in the Code Editor
  6222. :param silent: if True will not display status messages
  6223. :return: None
  6224. """
  6225. if silent is False:
  6226. self.inform.emit('[success] %s' % _("New TCL script file created in Code Editor."))
  6227. # delete the absolute and relative position and messages in the infobar
  6228. # self.ui.position_label.setText("")
  6229. # self.ui.rel_position_label.setText("")
  6230. # hide coordinates toolbars in the infobar while in DB
  6231. self.ui.coords_toolbar.hide()
  6232. self.ui.delta_coords_toolbar.hide()
  6233. self.app_obj.new_script_object()
  6234. # script_text = script_obj.source_file
  6235. #
  6236. # self.proc_container.view.set_busy(_("Loading..."))
  6237. # script_obj.script_editor_tab.t_frame.hide()
  6238. #
  6239. # script_obj.script_editor_tab.t_frame.show()
  6240. # self.proc_container.view.set_idle()
  6241. def on_fileopenscript(self, name=None, silent=False):
  6242. """
  6243. Will open a Tcl script file into the Code Editor
  6244. :param silent: if True will not display status messages
  6245. :param name: name of a Tcl script file to open
  6246. :return: None
  6247. """
  6248. self.defaults.report_usage("on_fileopenscript")
  6249. App.log.debug("on_fileopenscript()")
  6250. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6251. "All Files (*.*)"
  6252. if name:
  6253. filenames = [name]
  6254. else:
  6255. try:
  6256. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6257. caption=_("Open TCL script"), directory=self.get_last_folder(), filter=_filter_)
  6258. except TypeError:
  6259. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6260. if len(filenames) == 0:
  6261. if silent is False:
  6262. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6263. else:
  6264. for filename in filenames:
  6265. if filename != '':
  6266. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6267. def on_fileopenscript_example(self, name=None, silent=False):
  6268. """
  6269. Will open a Tcl script file into the Code Editor
  6270. :param silent: if True will not display status messages
  6271. :param name: name of a Tcl script file to open
  6272. :return:
  6273. """
  6274. self.defaults.report_usage("on_fileopenscript_example")
  6275. log.debug("on_fileopenscript_example()")
  6276. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6277. "All Files (*.*)"
  6278. # test if the app was frozen and choose the path for the configuration file
  6279. if getattr(sys, "frozen", False) is True:
  6280. example_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\assets\\examples'
  6281. else:
  6282. example_path = os.path.dirname(os.path.realpath(__file__)) + '\\assets\\examples'
  6283. if name:
  6284. filenames = [name]
  6285. else:
  6286. try:
  6287. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6288. caption=_("Open TCL script"), directory=example_path, filter=_filter_)
  6289. except TypeError:
  6290. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6291. if len(filenames) == 0:
  6292. if silent is False:
  6293. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6294. else:
  6295. for filename in filenames:
  6296. if filename != '':
  6297. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6298. def on_filerunscript(self, name=None, silent=False):
  6299. """
  6300. File menu callback for loading and running a TCL script.
  6301. :param silent: if True will not display status messages
  6302. :param name: name of a Tcl script file to be run by FlatCAM
  6303. :return: None
  6304. """
  6305. self.defaults.report_usage("on_filerunscript")
  6306. App.log.debug("on_file_runscript()")
  6307. if name:
  6308. filename = name
  6309. if self.cmd_line_headless != 1:
  6310. self.splash.showMessage('%s: %ssec\n%s' %
  6311. (_("Canvas initialization started.\n"
  6312. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6313. _("Executing ScriptObject file.")
  6314. ),
  6315. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6316. color=QtGui.QColor("gray"))
  6317. else:
  6318. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6319. "All Files (*.*)"
  6320. try:
  6321. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  6322. directory=self.get_last_folder(), filter=_filter_)
  6323. except TypeError:
  6324. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  6325. # The Qt methods above will return a QString which can cause problems later.
  6326. # So far json.dump() will fail to serialize it.
  6327. filename = str(filename)
  6328. if filename == "":
  6329. if silent is False:
  6330. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6331. else:
  6332. if self.cmd_line_headless != 1:
  6333. if self.ui.shell_dock.isHidden():
  6334. self.ui.shell_dock.show()
  6335. try:
  6336. with open(filename, "r") as tcl_script:
  6337. cmd_line_shellfile_content = tcl_script.read()
  6338. if self.cmd_line_headless != 1:
  6339. self.shell.exec_command(cmd_line_shellfile_content)
  6340. else:
  6341. self.shell.exec_command(cmd_line_shellfile_content, no_echo=True)
  6342. if silent is False:
  6343. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor and executed."))
  6344. except Exception as e:
  6345. log.debug("App.on_filerunscript() -> %s" % str(e))
  6346. sys.exit(2)
  6347. def on_file_saveproject(self, silent=False):
  6348. """
  6349. Callback for menu item File->Save Project. Saves the project to
  6350. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  6351. if set to None. The project is saved by calling ``self.save_project()``.
  6352. :param silent: if True will not display status messages
  6353. :return: None
  6354. """
  6355. self.defaults.report_usage("on_file_saveproject")
  6356. if self.project_filename is None:
  6357. self.on_file_saveprojectas()
  6358. else:
  6359. self.worker_task.emit({'fcn': self.save_project,
  6360. 'params': [self.project_filename, silent]})
  6361. if self.defaults["global_open_style"] is False:
  6362. self.file_opened.emit("project", self.project_filename)
  6363. self.file_saved.emit("project", self.project_filename)
  6364. self.set_ui_title(name=self.project_filename)
  6365. self.should_we_save = False
  6366. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  6367. """
  6368. Callback for menu item File->Save Project As... Opens a file
  6369. chooser and saves the project to the given file via
  6370. ``self.save_project()``.
  6371. :param make_copy if to be create a copy of the project; boolean
  6372. :param use_thread: if to be run in a separate thread; boolean
  6373. :param quit_action: if to be followed by quiting the application; boolean
  6374. :return: None
  6375. """
  6376. self.defaults.report_usage("on_file_saveprojectas")
  6377. self.date = str(datetime.today()).rpartition('.')[0]
  6378. self.date = ''.join(c for c in self.date if c not in ':-')
  6379. self.date = self.date.replace(' ', '_')
  6380. filter_ = "FlatCAM Project .FlatPrj (*.FlatPrj);; All Files (*.*)"
  6381. try:
  6382. filename, _f = FCFileSaveDialog.get_saved_filename(
  6383. caption=_("Save Project As ..."),
  6384. directory='{l_save}/{proj}_{date}'.format(l_save=str(self.get_last_save_folder()), date=self.date,
  6385. proj=_("Project")),
  6386. ext_filter=filter_
  6387. )
  6388. except TypeError:
  6389. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Project As ..."), ext_filter=filter_)
  6390. filename = str(filename)
  6391. if filename == '':
  6392. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6393. return
  6394. if use_thread is True:
  6395. self.worker_task.emit({'fcn': self.save_project,
  6396. 'params': [filename, quit_action]})
  6397. else:
  6398. self.save_project(filename, quit_action)
  6399. # self.save_project(filename)
  6400. if self.defaults["global_open_style"] is False:
  6401. self.file_opened.emit("project", filename)
  6402. self.file_saved.emit("project", filename)
  6403. if not make_copy:
  6404. self.project_filename = filename
  6405. self.set_ui_title(name=self.project_filename)
  6406. self.should_we_save = False
  6407. def on_file_save_objects_pdf(self, use_thread=True):
  6408. self.date = str(datetime.today()).rpartition('.')[0]
  6409. self.date = ''.join(c for c in self.date if c not in ':-')
  6410. self.date = self.date.replace(' ', '_')
  6411. try:
  6412. obj_selection = self.collection.get_selected()
  6413. if len(obj_selection) == 1:
  6414. obj_name = str(obj_selection[0].options['name'])
  6415. else:
  6416. obj_name = _("FlatCAM objects print")
  6417. except AttributeError as err:
  6418. log.debug("App.on_file_save_object_pdf() --> %s" % str(err))
  6419. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  6420. return
  6421. if not obj_selection:
  6422. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  6423. return
  6424. filter_ = "PDF File .pdf (*.PDF);; All Files (*.*)"
  6425. try:
  6426. filename, _f = FCFileSaveDialog.get_saved_filename(
  6427. caption=_("Save Object as PDF ..."),
  6428. directory='{l_save}/{obj_name}_{date}'.format(l_save=str(self.get_last_save_folder()),
  6429. obj_name=obj_name,
  6430. date=self.date),
  6431. ext_filter=filter_
  6432. )
  6433. except TypeError:
  6434. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Object as PDF ..."), ext_filter=filter_)
  6435. filename = str(filename)
  6436. if filename == '':
  6437. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6438. return
  6439. if use_thread is True:
  6440. self.proc_container.new(_("Printing PDF ... Please wait."))
  6441. self.worker_task.emit({'fcn': self.save_pdf, 'params': [filename, obj_selection]})
  6442. else:
  6443. self.save_pdf(filename, obj_selection)
  6444. # self.save_project(filename)
  6445. if self.defaults["global_open_style"] is False:
  6446. self.file_opened.emit("pdf", filename)
  6447. self.file_saved.emit("pdf", filename)
  6448. def save_pdf(self, file_name, obj_selection):
  6449. p_size = self.defaults['global_workspaceT']
  6450. orientation = self.defaults['global_workspace_orientation']
  6451. color = 'black'
  6452. transparency_level = 1.0
  6453. self.pagesize = {}
  6454. self.pagesize.update(
  6455. {
  6456. 'Bounds': None,
  6457. 'A0': (841 * mm, 1189 * mm),
  6458. 'A1': (594 * mm, 841 * mm),
  6459. 'A2': (420 * mm, 594 * mm),
  6460. 'A3': (297 * mm, 420 * mm),
  6461. 'A4': (210 * mm, 297 * mm),
  6462. 'A5': (148 * mm, 210 * mm),
  6463. 'A6': (105 * mm, 148 * mm),
  6464. 'A7': (74 * mm, 105 * mm),
  6465. 'A8': (52 * mm, 74 * mm),
  6466. 'A9': (37 * mm, 52 * mm),
  6467. 'A10': (26 * mm, 37 * mm),
  6468. 'B0': (1000 * mm, 1414 * mm),
  6469. 'B1': (707 * mm, 1000 * mm),
  6470. 'B2': (500 * mm, 707 * mm),
  6471. 'B3': (353 * mm, 500 * mm),
  6472. 'B4': (250 * mm, 353 * mm),
  6473. 'B5': (176 * mm, 250 * mm),
  6474. 'B6': (125 * mm, 176 * mm),
  6475. 'B7': (88 * mm, 125 * mm),
  6476. 'B8': (62 * mm, 88 * mm),
  6477. 'B9': (44 * mm, 62 * mm),
  6478. 'B10': (31 * mm, 44 * mm),
  6479. 'C0': (917 * mm, 1297 * mm),
  6480. 'C1': (648 * mm, 917 * mm),
  6481. 'C2': (458 * mm, 648 * mm),
  6482. 'C3': (324 * mm, 458 * mm),
  6483. 'C4': (229 * mm, 324 * mm),
  6484. 'C5': (162 * mm, 229 * mm),
  6485. 'C6': (114 * mm, 162 * mm),
  6486. 'C7': (81 * mm, 114 * mm),
  6487. 'C8': (57 * mm, 81 * mm),
  6488. 'C9': (40 * mm, 57 * mm),
  6489. 'C10': (28 * mm, 40 * mm),
  6490. # American paper sizes
  6491. 'LETTER': (8.5 * inch, 11 * inch),
  6492. 'LEGAL': (8.5 * inch, 14 * inch),
  6493. 'ELEVENSEVENTEEN': (11 * inch, 17 * inch),
  6494. # From https://en.wikipedia.org/wiki/Paper_size
  6495. 'JUNIOR_LEGAL': (5 * inch, 8 * inch),
  6496. 'HALF_LETTER': (5.5 * inch, 8 * inch),
  6497. 'GOV_LETTER': (8 * inch, 10.5 * inch),
  6498. 'GOV_LEGAL': (8.5 * inch, 13 * inch),
  6499. 'LEDGER': (17 * inch, 11 * inch),
  6500. }
  6501. )
  6502. exported_svg = []
  6503. for obj in obj_selection:
  6504. svg_obj = obj.export_svg(scale_stroke_factor=0.0,
  6505. scale_factor_x=None, scale_factor_y=None,
  6506. skew_factor_x=None, skew_factor_y=None,
  6507. mirror=None)
  6508. if obj.kind.lower() == 'gerber':
  6509. # color = self.defaults["gerber_plot_fill"][:-2]
  6510. color = obj.fill_color[:-2]
  6511. elif obj.kind.lower() == 'excellon':
  6512. color = '#C40000'
  6513. elif obj.kind.lower() == 'geometry':
  6514. color = self.defaults["global_draw_color"]
  6515. # Change the attributes of the exported SVG
  6516. # We don't need stroke-width
  6517. # We set opacity to maximum
  6518. # We set the colour to WHITE
  6519. root = ET.fromstring(svg_obj)
  6520. for child in root:
  6521. child.set('fill', str(color))
  6522. child.set('opacity', str(transparency_level))
  6523. child.set('stroke', str(color))
  6524. exported_svg.append(ET.tostring(root))
  6525. xmin = Inf
  6526. ymin = Inf
  6527. xmax = -Inf
  6528. ymax = -Inf
  6529. for obj in obj_selection:
  6530. try:
  6531. gxmin, gymin, gxmax, gymax = obj.bounds()
  6532. xmin = min([xmin, gxmin])
  6533. ymin = min([ymin, gymin])
  6534. xmax = max([xmax, gxmax])
  6535. ymax = max([ymax, gymax])
  6536. except Exception as e:
  6537. log.warning("DEV WARNING: Tried to get bounds of empty geometry in App.save_pdf(). %s" % str(e))
  6538. # Determine bounding area for svg export
  6539. bounds = [xmin, ymin, xmax, ymax]
  6540. size = bounds[2] - bounds[0], bounds[3] - bounds[1]
  6541. # This contain the measure units
  6542. uom = obj_selection[0].units.lower()
  6543. # Define a boundary around SVG of about 1.0mm (~39mils)
  6544. if uom in "mm":
  6545. boundary = 1.0
  6546. else:
  6547. boundary = 0.0393701
  6548. # Convert everything to strings for use in the xml doc
  6549. svgwidth = str(size[0] + (2 * boundary))
  6550. svgheight = str(size[1] + (2 * boundary))
  6551. minx = str(bounds[0] - boundary)
  6552. miny = str(bounds[1] + boundary + size[1])
  6553. # Add a SVG Header and footer to the svg output from shapely
  6554. # The transform flips the Y Axis so that everything renders
  6555. # properly within svg apps such as inkscape
  6556. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  6557. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  6558. svg_header += 'width="' + svgwidth + uom + '" '
  6559. svg_header += 'height="' + svgheight + uom + '" '
  6560. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  6561. svg_header += '>'
  6562. svg_header += '<g transform="scale(1,-1)">'
  6563. svg_footer = '</g> </svg>'
  6564. svg_elem = str(svg_header)
  6565. for svg_item in exported_svg:
  6566. svg_elem += str(svg_item)
  6567. svg_elem += str(svg_footer)
  6568. # Parse the xml through a xml parser just to add line feeds
  6569. # and to make it look more pretty for the output
  6570. doc = parse_xml_string(svg_elem)
  6571. doc_final = doc.toprettyxml()
  6572. try:
  6573. if self.defaults['units'].upper() == 'IN':
  6574. unit = inch
  6575. else:
  6576. unit = mm
  6577. doc_final = StringIO(doc_final)
  6578. drawing = svg2rlg(doc_final)
  6579. if p_size == 'Bounds':
  6580. renderPDF.drawToFile(drawing, file_name)
  6581. else:
  6582. if orientation == 'p':
  6583. page_size = portrait(self.pagesize[p_size])
  6584. else:
  6585. page_size = landscape(self.pagesize[p_size])
  6586. my_canvas = canvas.Canvas(file_name, pagesize=page_size)
  6587. my_canvas.translate(bounds[0] * unit, bounds[1] * unit)
  6588. renderPDF.draw(drawing, my_canvas, 0, 0)
  6589. my_canvas.save()
  6590. except Exception as e:
  6591. log.debug("App.save_pdf() --> PDF output --> %s" % str(e))
  6592. return 'fail'
  6593. self.inform.emit('[success] %s: %s' % (_("PDF file saved to"), file_name))
  6594. def export_svg(self, obj_name, filename, scale_stroke_factor=0.00):
  6595. """
  6596. Exports a Geometry Object to an SVG file.
  6597. :param obj_name: the name of the FlatCAM object to be saved as SVG
  6598. :param filename: Path to the SVG file to save to.
  6599. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  6600. :return:
  6601. """
  6602. self.defaults.report_usage("export_svg()")
  6603. if filename is None:
  6604. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6605. is not None else self.defaults["global_last_folder"]
  6606. self.log.debug("export_svg()")
  6607. try:
  6608. obj = self.collection.get_by_name(str(obj_name))
  6609. except Exception:
  6610. # TODO: The return behavior has not been established... should raise exception?
  6611. return "Could not retrieve object: %s" % obj_name
  6612. with self.proc_container.new(_("Exporting SVG")) as proc:
  6613. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor)
  6614. # Determine bounding area for svg export
  6615. bounds = obj.bounds()
  6616. size = obj.size()
  6617. # Convert everything to strings for use in the xml doc
  6618. svgwidth = str(size[0])
  6619. svgheight = str(size[1])
  6620. minx = str(bounds[0])
  6621. miny = str(bounds[1] - size[1])
  6622. uom = obj.units.lower()
  6623. # Add a SVG Header and footer to the svg output from shapely
  6624. # The transform flips the Y Axis so that everything renders
  6625. # properly within svg apps such as inkscape
  6626. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  6627. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  6628. svg_header += 'width="' + svgwidth + uom + '" '
  6629. svg_header += 'height="' + svgheight + uom + '" '
  6630. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  6631. svg_header += '<g transform="scale(1,-1)">'
  6632. svg_footer = '</g> </svg>'
  6633. svg_elem = svg_header + exported_svg + svg_footer
  6634. # Parse the xml through a xml parser just to add line feeds
  6635. # and to make it look more pretty for the output
  6636. svgcode = parse_xml_string(svg_elem)
  6637. svgcode = svgcode.toprettyxml()
  6638. try:
  6639. with open(filename, 'w') as fp:
  6640. fp.write(svgcode)
  6641. except PermissionError:
  6642. self.inform.emit('[WARNING] %s' %
  6643. _("Permission denied, saving not possible.\n"
  6644. "Most likely another app is holding the file open and not accessible."))
  6645. return 'fail'
  6646. if self.defaults["global_open_style"] is False:
  6647. self.file_opened.emit("SVG", filename)
  6648. self.file_saved.emit("SVG", filename)
  6649. self.inform.emit('[success] %s: %s' % (_("SVG file exported to"), filename))
  6650. def save_source_file(self, obj_name, filename, use_thread=True):
  6651. """
  6652. Exports a FlatCAM Object to an Gerber/Excellon file.
  6653. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  6654. :param filename: Path to the Gerber file to save to.
  6655. :param use_thread: if to be run in a separate thread
  6656. :return:
  6657. """
  6658. self.defaults.report_usage("save source file()")
  6659. if filename is None:
  6660. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6661. is not None else self.defaults["global_last_folder"]
  6662. self.log.debug("save source file()")
  6663. obj = self.collection.get_by_name(obj_name)
  6664. file_string = StringIO(obj.source_file)
  6665. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6666. if file_string.getvalue() == '':
  6667. self.inform.emit('[ERROR_NOTCL] %s' %
  6668. _("Save cancelled because source file is empty. Try to export the Gerber file."))
  6669. return 'fail'
  6670. try:
  6671. with open(filename, 'w') as file:
  6672. file.writelines('G04*\n')
  6673. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  6674. (obj.kind.upper(), str(self.version), str(self.version_date)))
  6675. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  6676. file.writelines('G04 Created on : %s*\n' % time_string)
  6677. for line in file_string:
  6678. file.writelines(line)
  6679. except PermissionError:
  6680. self.inform.emit('[WARNING] %s' %
  6681. _("Permission denied, saving not possible.\n"
  6682. "Most likely another app is holding the file open and not accessible."))
  6683. return 'fail'
  6684. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  6685. """
  6686. Exports a Excellon Object to an Excellon file.
  6687. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  6688. :param filename: Path to the Excellon file to save to.
  6689. :param local_use:
  6690. :param use_thread: if to be run in a separate thread
  6691. :return:
  6692. """
  6693. self.defaults.report_usage("export_excellon()")
  6694. if filename is None:
  6695. if self.defaults["global_last_save_folder"]:
  6696. filename = self.defaults["global_last_save_folder"] + '/' + 'exported_excellon'
  6697. else:
  6698. filename = self.defaults["global_last_folder"] + '/' + 'exported_excellon'
  6699. self.log.debug("export_excellon()")
  6700. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  6701. self.defaults["excellon_exp_decimals"]
  6702. )
  6703. if local_use is None:
  6704. try:
  6705. obj = self.collection.get_by_name(str(obj_name))
  6706. except Exception:
  6707. return "Could not retrieve object: %s" % obj_name
  6708. else:
  6709. obj = local_use
  6710. if not isinstance(obj, ExcellonObject):
  6711. self.inform.emit('[ERROR_NOTCL] %s' %
  6712. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6713. return
  6714. # updated units
  6715. eunits = self.defaults["excellon_exp_units"]
  6716. ewhole = self.defaults["excellon_exp_integer"]
  6717. efract = self.defaults["excellon_exp_decimals"]
  6718. ezeros = self.defaults["excellon_exp_zeros"]
  6719. eformat = self.defaults["excellon_exp_format"]
  6720. slot_type = self.defaults["excellon_exp_slot_type"]
  6721. fc_units = self.defaults['units'].upper()
  6722. if fc_units == 'MM':
  6723. factor = 1 if eunits == 'METRIC' else 0.03937
  6724. else:
  6725. factor = 25.4 if eunits == 'METRIC' else 1
  6726. def make_excellon():
  6727. try:
  6728. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6729. header = 'M48\n'
  6730. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  6731. (str(self.version), str(self.version_date))
  6732. header += ';Filename: %s' % str(obj_name) + '\n'
  6733. header += ';Created on : %s' % time_str + '\n'
  6734. if eformat == 'dec':
  6735. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  6736. header += eunits + '\n'
  6737. for tool in obj.tools:
  6738. if eunits == 'METRIC':
  6739. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6740. tool=str(tool),
  6741. dec=2)
  6742. else:
  6743. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6744. tool=str(tool),
  6745. dec=4)
  6746. else:
  6747. if ezeros == 'LZ':
  6748. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  6749. form='ndec', e_zeros='LZ', factor=factor,
  6750. slot_type=slot_type)
  6751. header += '%s,%s\n' % (eunits, 'LZ')
  6752. header += format_exc
  6753. for tool in obj.tools:
  6754. if eunits == 'METRIC':
  6755. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6756. tool=str(tool),
  6757. dec=2)
  6758. else:
  6759. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6760. tool=str(tool),
  6761. dec=4)
  6762. else:
  6763. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  6764. form='ndec', e_zeros='TZ', factor=factor,
  6765. slot_type=slot_type)
  6766. header += '%s,%s\n' % (eunits, 'TZ')
  6767. header += format_exc
  6768. for tool in obj.tools:
  6769. if eunits == 'METRIC':
  6770. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6771. tool=str(tool),
  6772. dec=2)
  6773. else:
  6774. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  6775. tool=str(tool),
  6776. dec=4)
  6777. header += '%\n'
  6778. footer = 'M30\n'
  6779. exported_excellon = header
  6780. exported_excellon += excellon_code
  6781. exported_excellon += footer
  6782. if local_use is None:
  6783. try:
  6784. with open(filename, 'w') as fp:
  6785. fp.write(exported_excellon)
  6786. except PermissionError:
  6787. self.inform.emit('[WARNING] %s' %
  6788. _("Permission denied, saving not possible.\n"
  6789. "Most likely another app is holding the file open and not accessible."))
  6790. return 'fail'
  6791. if self.defaults["global_open_style"] is False:
  6792. self.file_opened.emit("Excellon", filename)
  6793. self.file_saved.emit("Excellon", filename)
  6794. self.inform.emit('[success] %s: %s' % (_("Excellon file exported to"), filename))
  6795. else:
  6796. return exported_excellon
  6797. except Exception as e:
  6798. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  6799. return 'fail'
  6800. if use_thread is True:
  6801. with self.proc_container.new(_("Exporting Excellon")) as proc:
  6802. def job_thread_exc(app_obj):
  6803. ret = make_excellon()
  6804. if ret == 'fail':
  6805. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  6806. return
  6807. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  6808. else:
  6809. eret = make_excellon()
  6810. if eret == 'fail':
  6811. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  6812. return 'fail'
  6813. if local_use is not None:
  6814. return eret
  6815. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  6816. """
  6817. Exports a Gerber Object to an Gerber file.
  6818. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  6819. :param filename: Path to the Gerber file to save to.
  6820. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  6821. When not None, the value will be the actual Gerber object for which to create the Gerber code
  6822. :param use_thread: if to be run in a separate thread
  6823. :return:
  6824. """
  6825. self.defaults.report_usage("export_gerber()")
  6826. if filename is None:
  6827. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6828. is not None else self.defaults["global_last_folder"]
  6829. self.log.debug("export_gerber()")
  6830. if local_use is None:
  6831. try:
  6832. obj = self.collection.get_by_name(str(obj_name))
  6833. except Exception:
  6834. return "Could not retrieve object: %s" % obj_name
  6835. else:
  6836. obj = local_use
  6837. # updated units
  6838. gunits = self.defaults["gerber_exp_units"]
  6839. gwhole = self.defaults["gerber_exp_integer"]
  6840. gfract = self.defaults["gerber_exp_decimals"]
  6841. gzeros = self.defaults["gerber_exp_zeros"]
  6842. fc_units = self.defaults['units'].upper()
  6843. if fc_units == 'MM':
  6844. factor = 1 if gunits == 'MM' else 0.03937
  6845. else:
  6846. factor = 25.4 if gunits == 'MM' else 1
  6847. def make_gerber():
  6848. try:
  6849. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  6850. header = 'G04*\n'
  6851. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  6852. (str(self.version), str(self.version_date))
  6853. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  6854. header += 'G04 Created on : %s*' % time_str + '\n'
  6855. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  6856. header += "%MO{units}*%\n".format(units=gunits)
  6857. for apid in obj.apertures:
  6858. if obj.apertures[apid]['type'] == 'C':
  6859. header += "%ADD{apid}{type},{size}*%\n".format(
  6860. apid=str(apid),
  6861. type='C',
  6862. size=(factor * obj.apertures[apid]['size'])
  6863. )
  6864. elif obj.apertures[apid]['type'] == 'R':
  6865. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  6866. apid=str(apid),
  6867. type='R',
  6868. width=(factor * obj.apertures[apid]['width']),
  6869. height=(factor * obj.apertures[apid]['height'])
  6870. )
  6871. elif obj.apertures[apid]['type'] == 'O':
  6872. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  6873. apid=str(apid),
  6874. type='O',
  6875. width=(factor * obj.apertures[apid]['width']),
  6876. height=(factor * obj.apertures[apid]['height'])
  6877. )
  6878. header += '\n'
  6879. # obsolete units but some software may need it
  6880. if gunits == 'IN':
  6881. header += 'G70*\n'
  6882. else:
  6883. header += 'G71*\n'
  6884. # Absolute Mode
  6885. header += 'G90*\n'
  6886. header += 'G01*\n'
  6887. # positive polarity
  6888. header += '%LPD*%\n'
  6889. footer = 'M02*\n'
  6890. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  6891. exported_gerber = header
  6892. exported_gerber += gerber_code
  6893. exported_gerber += footer
  6894. if local_use is None:
  6895. try:
  6896. with open(filename, 'w') as fp:
  6897. fp.write(exported_gerber)
  6898. except PermissionError:
  6899. self.inform.emit('[WARNING] %s' %
  6900. _("Permission denied, saving not possible.\n"
  6901. "Most likely another app is holding the file open and not accessible."))
  6902. return 'fail'
  6903. if self.defaults["global_open_style"] is False:
  6904. self.file_opened.emit("Gerber", filename)
  6905. self.file_saved.emit("Gerber", filename)
  6906. self.inform.emit('[success] %s: %s' % (_("Gerber file exported to"), filename))
  6907. else:
  6908. return exported_gerber
  6909. except Exception as e:
  6910. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  6911. return 'fail'
  6912. if use_thread is True:
  6913. with self.proc_container.new(_("Exporting Gerber")) as proc:
  6914. def job_thread_grb(app_obj):
  6915. ret = make_gerber()
  6916. if ret == 'fail':
  6917. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  6918. return
  6919. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  6920. else:
  6921. gret = make_gerber()
  6922. if gret == 'fail':
  6923. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  6924. return 'fail'
  6925. if local_use is not None:
  6926. return gret
  6927. def export_dxf(self, obj_name, filename, use_thread=True):
  6928. """
  6929. Exports a Geometry Object to an DXF file.
  6930. :param obj_name: the name of the FlatCAM object to be saved as DXF
  6931. :param filename: Path to the DXF file to save to.
  6932. :param use_thread: if to be run in a separate thread
  6933. :return:
  6934. """
  6935. self.defaults.report_usage("export_dxf()")
  6936. if filename is None:
  6937. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  6938. is not None else self.defaults["global_last_folder"]
  6939. self.log.debug("export_dxf()")
  6940. try:
  6941. obj = self.collection.get_by_name(str(obj_name))
  6942. except Exception:
  6943. # TODO: The return behavior has not been established... should raise exception?
  6944. return "Could not retrieve object: %s" % obj_name
  6945. def make_dxf():
  6946. try:
  6947. dxf_code = obj.export_dxf()
  6948. dxf_code.saveas(filename)
  6949. if self.defaults["global_open_style"] is False:
  6950. self.file_opened.emit("DXF", filename)
  6951. self.file_saved.emit("DXF", filename)
  6952. self.inform.emit('[success] %s: %s' % (_("DXF file exported to"), filename))
  6953. except Exception:
  6954. return 'fail'
  6955. if use_thread is True:
  6956. with self.proc_container.new(_("Exporting DXF")) as proc:
  6957. def job_thread_exc(app_obj):
  6958. ret_dxf_val = make_dxf()
  6959. if ret_dxf_val == 'fail':
  6960. app_obj.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  6961. return
  6962. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  6963. else:
  6964. ret = make_dxf()
  6965. if ret == 'fail':
  6966. self.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  6967. return
  6968. def import_svg(self, filename, geo_type='geometry', outname=None, plot=True):
  6969. """
  6970. Adds a new Geometry Object to the projects and populates
  6971. it with shapes extracted from the SVG file.
  6972. :param plot: If True then the resulting object will be plotted on canvas
  6973. :param filename: Path to the SVG file.
  6974. :param geo_type: Type of FlatCAM object that will be created from SVG
  6975. :param outname: The name given to the resulting FlatCAM object
  6976. :return:
  6977. """
  6978. self.defaults.report_usage("import_svg()")
  6979. log.debug("App.import_svg()")
  6980. obj_type = ""
  6981. if geo_type is None or geo_type == "geometry":
  6982. obj_type = "geometry"
  6983. elif geo_type == "gerber":
  6984. obj_type = "gerber"
  6985. else:
  6986. self.inform.emit('[ERROR_NOTCL] %s' %
  6987. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  6988. return
  6989. units = self.defaults['units'].upper()
  6990. def obj_init(geo_obj, app_obj):
  6991. geo_obj.import_svg(filename, obj_type, units=units)
  6992. geo_obj.multigeo = False
  6993. geo_obj.source_file = self.export_gerber(obj_name=name, filename=None, local_use=geo_obj, use_thread=False)
  6994. with self.proc_container.new(_("Importing SVG")) as proc:
  6995. # Object name
  6996. name = outname or filename.split('/')[-1].split('\\')[-1]
  6997. ret = self.app_obj.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  6998. if ret == 'fail':
  6999. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  7000. return 'fail'
  7001. # Register recent file
  7002. self.file_opened.emit("svg", filename)
  7003. # appGUI feedback
  7004. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7005. def import_dxf(self, filename, geo_type='geometry', outname=None, plot=True):
  7006. """
  7007. Adds a new Geometry Object to the projects and populates
  7008. it with shapes extracted from the DXF file.
  7009. :param filename: Path to the DXF file.
  7010. :param geo_type: Type of FlatCAM object that will be created from DXF
  7011. :param outname: Name for the imported Geometry
  7012. :param plot: If True then the resulting object will be plotted on canvas
  7013. :return:
  7014. """
  7015. self.defaults.report_usage("import_dxf()")
  7016. obj_type = ""
  7017. if geo_type is None or geo_type == "geometry":
  7018. obj_type = "geometry"
  7019. elif geo_type == "gerber":
  7020. obj_type = geo_type
  7021. else:
  7022. self.inform.emit('[ERROR_NOTCL] %s' %
  7023. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  7024. return
  7025. units = self.defaults['units'].upper()
  7026. def obj_init(geo_obj, app_obj):
  7027. geo_obj.import_dxf(filename, obj_type, units=units)
  7028. geo_obj.multigeo = False
  7029. with self.proc_container.new(_("Importing DXF")):
  7030. # Object name
  7031. name = outname or filename.split('/')[-1].split('\\')[-1]
  7032. ret = self.app_obj.new_object(obj_type, name, obj_init, autoselected=False, plot=plot)
  7033. if ret == 'fail':
  7034. self.inform.emit('[ERROR_NOTCL]%s' % _('Import failed.'))
  7035. return 'fail'
  7036. # Register recent file
  7037. self.file_opened.emit("dxf", filename)
  7038. # appGUI feedback
  7039. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7040. def open_gerber(self, filename, outname=None, plot=True, from_tcl=False):
  7041. """
  7042. Opens a Gerber file, parses it and creates a new object for
  7043. it in the program. Thread-safe.
  7044. :param outname: Name of the resulting object. None causes the
  7045. name to be that of the file. Str.
  7046. :param filename: Gerber file filename
  7047. :type filename: str
  7048. :param plot: boolean, to plot or not the resulting object
  7049. :param from_tcl: True if run from Tcl Shell
  7050. :return: None
  7051. """
  7052. # How the object should be initialized
  7053. def obj_init(gerber_obj, app_obj):
  7054. assert isinstance(gerber_obj, GerberObject), \
  7055. "Expected to initialize a GerberObject but got %s" % type(gerber_obj)
  7056. # Opening the file happens here
  7057. try:
  7058. gerber_obj.parse_file(filename)
  7059. except IOError:
  7060. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7061. return "fail"
  7062. except ParseError as err:
  7063. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7064. app_obj.log.error(str(err))
  7065. return "fail"
  7066. except Exception as e:
  7067. log.debug("App.open_gerber() --> %s" % str(e))
  7068. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7069. msg += traceback.format_exc()
  7070. app_obj.inform.emit(msg)
  7071. return "fail"
  7072. if gerber_obj.is_empty():
  7073. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7074. _("Object is not Gerber file or empty. Aborting object creation."))
  7075. return "fail"
  7076. App.log.debug("open_gerber()")
  7077. with self.proc_container.new(_("Opening Gerber")):
  7078. # Object name
  7079. name = outname or filename.split('/')[-1].split('\\')[-1]
  7080. # # ## Object creation # ##
  7081. ret_val = self.app_obj.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  7082. if ret_val == 'fail':
  7083. if from_tcl:
  7084. filename = self.defaults['global_tcl_path'] + '/' + name
  7085. ret_val = self.app_obj.new_object("gerber", name, obj_init, autoselected=False, plot=plot)
  7086. if ret_val == 'fail':
  7087. self.inform.emit('[ERROR_NOTCL]%s' % _('Open Gerber failed. Probable not a Gerber file.'))
  7088. return 'fail'
  7089. # Register recent file
  7090. self.file_opened.emit("gerber", filename)
  7091. # appGUI feedback
  7092. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7093. def open_excellon(self, filename, outname=None, plot=True, from_tcl=False):
  7094. """
  7095. Opens an Excellon file, parses it and creates a new object for
  7096. it in the program. Thread-safe.
  7097. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7098. :param filename: Excellon file filename
  7099. :type filename: str
  7100. :param plot: boolean, to plot or not the resulting object
  7101. :param from_tcl: True if run from Tcl Shell
  7102. :return: None
  7103. """
  7104. App.log.debug("open_excellon()")
  7105. # How the object should be initialized
  7106. def obj_init(excellon_obj, app_obj):
  7107. try:
  7108. ret = excellon_obj.parse_file(filename=filename)
  7109. if ret == "fail":
  7110. log.debug("Excellon parsing failed.")
  7111. self.inform.emit('[ERROR_NOTCL] %s' %
  7112. _("This is not Excellon file."))
  7113. return "fail"
  7114. except IOError:
  7115. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  7116. (_("Cannot open file"), filename))
  7117. log.debug("Could not open Excellon object.")
  7118. return "fail"
  7119. except Exception:
  7120. msg = '[ERROR_NOTCL] %s' % \
  7121. _("An internal error has occurred. See shell.\n")
  7122. msg += traceback.format_exc()
  7123. app_obj.inform.emit(msg)
  7124. return "fail"
  7125. ret = excellon_obj.create_geometry()
  7126. if ret == 'fail':
  7127. log.debug("Could not create geometry for Excellon object.")
  7128. return "fail"
  7129. for tool in excellon_obj.tools:
  7130. if excellon_obj.tools[tool]['solid_geometry']:
  7131. return
  7132. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("No geometry found in file"), filename))
  7133. return "fail"
  7134. with self.proc_container.new(_("Opening Excellon.")):
  7135. # Object name
  7136. name = outname or filename.split('/')[-1].split('\\')[-1]
  7137. ret_val = self.app_obj.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7138. if ret_val == 'fail':
  7139. if from_tcl:
  7140. filename = self.defaults['global_tcl_path'] + '/' + name
  7141. ret_val = self.app_obj.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7142. if ret_val == 'fail':
  7143. self.inform.emit('[ERROR_NOTCL] %s' %
  7144. _('Open Excellon file failed. Probable not an Excellon file.'))
  7145. return
  7146. # Register recent file
  7147. self.file_opened.emit("excellon", filename)
  7148. # appGUI feedback
  7149. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7150. def open_gcode(self, filename, outname=None, force_parsing=None, plot=True, from_tcl=False):
  7151. """
  7152. Opens a G-gcode file, parses it and creates a new object for
  7153. it in the program. Thread-safe.
  7154. :param filename: G-code file filename
  7155. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7156. :param force_parsing:
  7157. :param plot: If True plot the object on canvas
  7158. :param from_tcl: True if run from Tcl Shell
  7159. :return: None
  7160. """
  7161. App.log.debug("open_gcode()")
  7162. # How the object should be initialized
  7163. def obj_init(job_obj, app_obj_):
  7164. """
  7165. :param job_obj: the resulting object
  7166. :type app_obj_: App
  7167. """
  7168. assert isinstance(app_obj_, App), \
  7169. "Initializer expected App, got %s" % type(app_obj_)
  7170. app_obj_.inform.emit('%s...' % _("Reading GCode file"))
  7171. try:
  7172. f = open(filename)
  7173. gcode = f.read()
  7174. f.close()
  7175. except IOError:
  7176. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open"), filename))
  7177. return "fail"
  7178. job_obj.gcode = gcode
  7179. gcode_ret = job_obj.gcode_parse(force_parsing=force_parsing)
  7180. if gcode_ret == "fail":
  7181. self.inform.emit('[ERROR_NOTCL] %s' % _("This is not GCODE"))
  7182. return "fail"
  7183. job_obj.create_geometry()
  7184. with self.proc_container.new(_("Opening G-Code.")):
  7185. # Object name
  7186. name = outname or filename.split('/')[-1].split('\\')[-1]
  7187. # New object creation and file processing
  7188. ret_val = self.app_obj.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7189. if ret_val == 'fail':
  7190. if from_tcl:
  7191. filename = self.defaults['global_tcl_path'] + '/' + name
  7192. ret_val = self.app_obj.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7193. if ret_val == 'fail':
  7194. self.inform.emit('[ERROR_NOTCL] %s' %
  7195. _("Failed to create CNCJob Object. Probable not a GCode file. "
  7196. "Try to load it from File menu.\n "
  7197. "Attempting to create a FlatCAM CNCJob Object from "
  7198. "G-Code file failed during processing"))
  7199. return "fail"
  7200. # Register recent file
  7201. self.file_opened.emit("cncjob", filename)
  7202. # appGUI feedback
  7203. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7204. def open_hpgl2(self, filename, outname=None):
  7205. """
  7206. Opens a HPGL2 file, parses it and creates a new object for
  7207. it in the program. Thread-safe.
  7208. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7209. :param filename: HPGL2 file filename
  7210. :return: None
  7211. """
  7212. filename = filename
  7213. # How the object should be initialized
  7214. def obj_init(geo_obj, app_obj):
  7215. assert isinstance(geo_obj, GeometryObject), \
  7216. "Expected to initialize a GeometryObject but got %s" % type(geo_obj)
  7217. # Opening the file happens here
  7218. obj = HPGL2(self)
  7219. try:
  7220. HPGL2.parse_file(obj, filename)
  7221. except IOError:
  7222. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7223. return "fail"
  7224. except ParseError as err:
  7225. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7226. app_obj.log.error(str(err))
  7227. return "fail"
  7228. except Exception as e:
  7229. log.debug("App.open_hpgl2() --> %s" % str(e))
  7230. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7231. msg += traceback.format_exc()
  7232. app_obj.inform.emit(msg)
  7233. return "fail"
  7234. geo_obj.multigeo = True
  7235. geo_obj.solid_geometry = deepcopy(obj.solid_geometry)
  7236. geo_obj.tools = deepcopy(obj.tools)
  7237. geo_obj.source_file = deepcopy(obj.source_file)
  7238. del obj
  7239. if not geo_obj.solid_geometry:
  7240. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7241. _("Object is not HPGL2 file or empty. Aborting object creation."))
  7242. return "fail"
  7243. App.log.debug("open_hpgl2()")
  7244. with self.proc_container.new(_("Opening HPGL2")):
  7245. # Object name
  7246. name = outname or filename.split('/')[-1].split('\\')[-1]
  7247. # # ## Object creation # ##
  7248. ret = self.app_obj.new_object("geometry", name, obj_init, autoselected=False)
  7249. if ret == 'fail':
  7250. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open HPGL2 failed. Probable not a HPGL2 file.'))
  7251. return 'fail'
  7252. # Register recent file
  7253. self.file_opened.emit("geometry", filename)
  7254. # appGUI feedback
  7255. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7256. def open_script(self, filename, outname=None, silent=False):
  7257. """
  7258. Opens a Script file, parses it and creates a new object for
  7259. it in the program. Thread-safe.
  7260. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7261. :param filename: Script file filename
  7262. :param silent: If True there will be no messages printed to StatusBar
  7263. :return: None
  7264. """
  7265. def obj_init(script_obj, app_obj):
  7266. assert isinstance(script_obj, ScriptObject), \
  7267. "Expected to initialize a ScriptObject but got %s" % type(script_obj)
  7268. if silent is False:
  7269. app_obj.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  7270. try:
  7271. script_obj.parse_file(filename)
  7272. except IOError:
  7273. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7274. return "fail"
  7275. except ParseError as err:
  7276. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7277. app_obj.log.error(str(err))
  7278. return "fail"
  7279. except Exception as e:
  7280. log.debug("App.open_script() -> %s" % str(e))
  7281. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7282. msg += traceback.format_exc()
  7283. app_obj.inform.emit(msg)
  7284. return "fail"
  7285. App.log.debug("open_script()")
  7286. with self.proc_container.new(_("Opening TCL Script...")):
  7287. # Object name
  7288. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  7289. # Object creation
  7290. ret_val = self.app_obj.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7291. if ret_val == 'fail':
  7292. filename = self.defaults['global_tcl_path'] + '/' + script_name
  7293. ret_val = self.app_obj.new_object("script", script_name, obj_init, autoselected=False, plot=False)
  7294. if ret_val == 'fail':
  7295. self.inform.emit('[ERROR_NOTCL]%s' % _('Failed to open TCL Script.'))
  7296. return 'fail'
  7297. # Register recent file
  7298. self.file_opened.emit("script", filename)
  7299. # appGUI feedback
  7300. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7301. def open_config_file(self, filename, run_from_arg=None):
  7302. """
  7303. Loads a config file from the specified file.
  7304. :param filename: Name of the file from which to load.
  7305. :param run_from_arg: if True the FlatConfig file will be open as an command line argument
  7306. :return: None
  7307. """
  7308. App.log.debug("Opening config file: " + filename)
  7309. if run_from_arg:
  7310. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7311. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7312. _("Opening FlatCAM Config file.")),
  7313. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7314. color=QtGui.QColor("gray"))
  7315. # # add the tab if it was closed
  7316. # self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  7317. # # first clear previous text in text editor (if any)
  7318. # self.ui.text_editor_tab.code_editor.clear()
  7319. #
  7320. # # Switch plot_area to CNCJob tab
  7321. # self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  7322. # close the Code editor if already open
  7323. if self.toggle_codeeditor:
  7324. self.on_toggle_code_editor()
  7325. self.on_toggle_code_editor()
  7326. try:
  7327. if filename:
  7328. f = QtCore.QFile(filename)
  7329. if f.open(QtCore.QIODevice.ReadOnly):
  7330. stream = QtCore.QTextStream(f)
  7331. code_edited = stream.readAll()
  7332. self.text_editor_tab.code_editor.setPlainText(code_edited)
  7333. f.close()
  7334. except IOError:
  7335. App.log.error("Failed to open config file: %s" % filename)
  7336. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  7337. (_("Failed to open config file"), filename))
  7338. return
  7339. def open_project(self, filename, run_from_arg=None, plot=True, cli=None, from_tcl=False):
  7340. """
  7341. Loads a project from the specified file.
  7342. 1) Loads and parses file
  7343. 2) Registers the file as recently opened.
  7344. 3) Calls on_file_new()
  7345. 4) Updates options
  7346. 5) Calls app_obj.new_object() with the object's from_dict() as init method.
  7347. 6) Calls plot_all() if plot=True
  7348. :param filename: Name of the file from which to load.
  7349. :param run_from_arg: True if run for arguments
  7350. :param plot: If True plot all objects in the project
  7351. :param cli: Run from command line
  7352. :param from_tcl: True if run from Tcl Sehll
  7353. :return: None
  7354. """
  7355. App.log.debug("Opening project: " + filename)
  7356. # block autosaving while a project is loaded
  7357. self.block_autosave = True
  7358. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7359. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7360. if cli is None:
  7361. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  7362. if run_from_arg:
  7363. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7364. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7365. _("Opening FlatCAM Project file.")),
  7366. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7367. color=QtGui.QColor("gray"))
  7368. # Open and parse an uncompressed Project file
  7369. try:
  7370. f = open(filename, 'r')
  7371. except IOError:
  7372. if from_tcl:
  7373. name = filename.split('/')[-1].split('\\')[-1]
  7374. filename = self.defaults['global_tcl_path'] + '/' + name
  7375. try:
  7376. f = open(filename, 'r')
  7377. except IOError:
  7378. log.error("Failed to open project file: %s" % filename)
  7379. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7380. return
  7381. else:
  7382. log.error("Failed to open project file: %s" % filename)
  7383. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7384. return
  7385. try:
  7386. d = json.load(f, object_hook=dict2obj)
  7387. except Exception as e:
  7388. log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  7389. (filename, str(e)))
  7390. f.close()
  7391. # Open and parse a compressed Project file
  7392. try:
  7393. with lzma.open(filename) as f:
  7394. file_content = f.read().decode('utf-8')
  7395. d = json.loads(file_content, object_hook=dict2obj)
  7396. except Exception as e:
  7397. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  7398. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open project file"), filename))
  7399. return
  7400. # Clear the current project
  7401. # # NOT THREAD SAFE # ##
  7402. if run_from_arg is True:
  7403. pass
  7404. elif cli is True:
  7405. self.delete_selection_shape()
  7406. else:
  7407. self.on_file_new()
  7408. # Project options
  7409. self.options.update(d['options'])
  7410. self.project_filename = filename
  7411. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7412. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7413. if cli is None:
  7414. self.set_screen_units(self.options["units"])
  7415. # Re create objects
  7416. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  7417. for obj in d['objs']:
  7418. try:
  7419. def obj_init(obj_inst, app_inst):
  7420. obj_inst.from_dict(obj)
  7421. App.log.debug("Recreating from opened project an %s object: %s" %
  7422. (obj['kind'].capitalize(), obj['options']['name']))
  7423. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7424. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7425. if cli is None:
  7426. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  7427. obj['kind'].upper(),
  7428. obj['options']['name']
  7429. )
  7430. )
  7431. self.app_obj.new_object(obj['kind'], obj['options']['name'], obj_init, plot=plot)
  7432. except Exception as e:
  7433. print('App.open_project() --> ' + str(e))
  7434. self.inform.emit('[success] %s: %s' % (_("Project loaded from"), filename))
  7435. self.should_we_save = False
  7436. self.file_opened.emit("project", filename)
  7437. # restore autosaving after a project was loaded
  7438. self.block_autosave = False
  7439. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7440. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7441. if cli is None:
  7442. self.set_ui_title(name=self.project_filename)
  7443. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  7444. def plot_all(self, fit_view=True, muted=False, use_thread=True):
  7445. """
  7446. Re-generates all plots from all objects.
  7447. :param fit_view: if True will plot the objects and will adjust the zoom to fit all plotted objects into view
  7448. :param muted: if True don't print messages
  7449. :param use_thread: if True will use threading for plotting the objects
  7450. :return: None
  7451. """
  7452. self.log.debug("Plot_all()")
  7453. if muted is not True:
  7454. self.inform[str, bool].emit('%s...' % _("Redrawing all objects"), False)
  7455. for plot_obj in self.collection.get_list():
  7456. def worker_task(obj):
  7457. with self.proc_container.new("Plotting"):
  7458. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  7459. if fit_view is True:
  7460. self.app_obj.object_plotted.emit(obj)
  7461. if use_thread is True:
  7462. # Send to worker
  7463. self.worker_task.emit({'fcn': worker_task, 'params': [plot_obj]})
  7464. else:
  7465. worker_task(plot_obj)
  7466. def register_folder(self, filename):
  7467. """
  7468. Register the last folder used by the app to open something
  7469. :param filename: the last folder is extracted from the filename
  7470. :return: None
  7471. """
  7472. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  7473. def register_save_folder(self, filename):
  7474. """
  7475. Register the last folder used by the app to save something
  7476. :param filename: the last folder is extracted from the filename
  7477. :return: None
  7478. """
  7479. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  7480. # def set_progress_bar(self, percentage, text=""):
  7481. # """
  7482. # Set a progress bar to a value (percentage)
  7483. #
  7484. # :param percentage: Value set to the progressbar
  7485. # :param text: Not used
  7486. # :return: None
  7487. # """
  7488. # self.ui.progress_bar.setValue(int(percentage))
  7489. def setup_recent_items(self):
  7490. """
  7491. Setup a dictionary with the recent files accessed, organized by type
  7492. :return:
  7493. """
  7494. icons = {
  7495. "gerber": self.resource_location + "/flatcam_icon16.png",
  7496. "excellon": self.resource_location + "/drill16.png",
  7497. 'geometry': self.resource_location + "/geometry16.png",
  7498. "cncjob": self.resource_location + "/cnc16.png",
  7499. "script": self.resource_location + "/script_new24.png",
  7500. "document": self.resource_location + "/notes16_1.png",
  7501. "project": self.resource_location + "/project16.png",
  7502. "svg": self.resource_location + "/geometry16.png",
  7503. "dxf": self.resource_location + "/dxf16.png",
  7504. "pdf": self.resource_location + "/pdf32.png",
  7505. "image": self.resource_location + "/image16.png"
  7506. }
  7507. try:
  7508. image_opener = self.image_tool.import_image
  7509. except AttributeError:
  7510. image_opener = None
  7511. openers = {
  7512. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  7513. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  7514. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  7515. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  7516. "script": lambda fname: self.worker_task.emit({'fcn': self.open_script, 'params': [fname]}),
  7517. "document": None,
  7518. 'project': self.open_project,
  7519. 'svg': self.import_svg,
  7520. 'dxf': self.import_dxf,
  7521. 'image': image_opener,
  7522. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  7523. }
  7524. # Open recent file for files
  7525. try:
  7526. f = open(self.data_path + '/recent.json')
  7527. except IOError:
  7528. App.log.error("Failed to load recent item list.")
  7529. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent item list."))
  7530. return
  7531. try:
  7532. self.recent = json.load(f)
  7533. except json.errors.JSONDecodeError:
  7534. App.log.error("Failed to parse recent item list.")
  7535. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent item list."))
  7536. f.close()
  7537. return
  7538. f.close()
  7539. # Open recent file for projects
  7540. try:
  7541. fp = open(self.data_path + '/recent_projects.json')
  7542. except IOError:
  7543. App.log.error("Failed to load recent project item list.")
  7544. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent projects item list."))
  7545. return
  7546. try:
  7547. self.recent_projects = json.load(fp)
  7548. except json.errors.JSONDecodeError:
  7549. App.log.error("Failed to parse recent project item list.")
  7550. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent project item list."))
  7551. fp.close()
  7552. return
  7553. fp.close()
  7554. # Closure needed to create callbacks in a loop.
  7555. # Otherwise late binding occurs.
  7556. def make_callback(func, fname):
  7557. def opener():
  7558. func(fname)
  7559. return opener
  7560. def reset_recent_files():
  7561. # Reset menu
  7562. self.ui.recent.clear()
  7563. self.recent = []
  7564. try:
  7565. ff = open(self.data_path + '/recent.json', 'w')
  7566. except IOError:
  7567. App.log.error("Failed to open recent items file for writing.")
  7568. return
  7569. json.dump(self.recent, ff)
  7570. def reset_recent_projects():
  7571. # Reset menu
  7572. self.ui.recent_projects.clear()
  7573. self.recent_projects = []
  7574. try:
  7575. frp = open(self.data_path + '/recent_projects.json', 'w')
  7576. except IOError:
  7577. App.log.error("Failed to open recent projects items file for writing.")
  7578. return
  7579. json.dump(self.recent, frp)
  7580. # Reset menu
  7581. self.ui.recent.clear()
  7582. self.ui.recent_projects.clear()
  7583. # Create menu items for projects
  7584. for recent in self.recent_projects:
  7585. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  7586. if recent['kind'] == 'project':
  7587. try:
  7588. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  7589. # Attach callback
  7590. o = make_callback(openers[recent["kind"]], recent['filename'])
  7591. action.triggered.connect(o)
  7592. self.ui.recent_projects.addAction(action)
  7593. except KeyError:
  7594. App.log.error("Unsupported file type: %s" % recent["kind"])
  7595. # Last action in Recent Files menu is one that Clear the content
  7596. clear_action_proj = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  7597. (_("Clear Recent projects")), self)
  7598. clear_action_proj.triggered.connect(reset_recent_projects)
  7599. self.ui.recent_projects.addSeparator()
  7600. self.ui.recent_projects.addAction(clear_action_proj)
  7601. # Create menu items for files
  7602. for recent in self.recent:
  7603. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  7604. if recent['kind'] != 'project':
  7605. try:
  7606. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  7607. # Attach callback
  7608. o = make_callback(openers[recent["kind"]], recent['filename'])
  7609. action.triggered.connect(o)
  7610. self.ui.recent.addAction(action)
  7611. except KeyError:
  7612. App.log.error("Unsupported file type: %s" % recent["kind"])
  7613. # Last action in Recent Files menu is one that Clear the content
  7614. clear_action = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  7615. (_("Clear Recent files")), self)
  7616. clear_action.triggered.connect(reset_recent_files)
  7617. self.ui.recent.addSeparator()
  7618. self.ui.recent.addAction(clear_action)
  7619. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  7620. # self.ui.menufilerecent.set_submenu(recent_menu)
  7621. # recent_menu.show_all()
  7622. # self.ui.recent.show()
  7623. self.log.debug("Recent items list has been populated.")
  7624. def setup_component_editor(self):
  7625. """
  7626. Default text for the Selected tab when is not taken by the Object UI.
  7627. :return:
  7628. """
  7629. # label = QtWidgets.QLabel("Choose an item from Project")
  7630. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  7631. sel_title = QtWidgets.QTextEdit(
  7632. _('<b>Shortcut Key List</b>'))
  7633. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  7634. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  7635. f_settings = QSettings("Open Source", "FlatCAM")
  7636. if f_settings.contains("notebook_font_size"):
  7637. fsize = f_settings.value('notebook_font_size', type=int)
  7638. else:
  7639. fsize = 12
  7640. tsize = fsize + int(fsize / 2)
  7641. # selected_text = (_('''
  7642. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span>
  7643. # </p>
  7644. #
  7645. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  7646. # The normal flow when working in FlatCAM is the following:</span></p>
  7647. #
  7648. # <ol>
  7649. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG
  7650. # file into
  7651. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  7652. # even dragging and dropping the files on the appGUI.<br />
  7653. # <br />
  7654. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp;
  7655. # drop of the
  7656. # file into the FLATCAM appGUI or through the menu/toolbar links offered within the app.</span><br />
  7657. # &nbsp;</li>
  7658. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it
  7659. # and then
  7660. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  7661. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  7662. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  7663. # <br />
  7664. # If the selection of the object is done on the canvas by single click instead, and the
  7665. # <strong>SELECTED TAB</strong>
  7666. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  7667. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  7668. # it even if it was out of focus.<br />
  7669. # <br />
  7670. # You can change the parameters in this screen and the flow direction is like this:<br />
  7671. # <br />
  7672. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;
  7673. # <strong> Geometry Object
  7674. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  7675. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  7676. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  7677. # </ol>
  7678. #
  7679. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  7680. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  7681. # <strong>F3</strong>.</span></p>
  7682. #
  7683. # ''').format(fsize=fsize, tsize=tsize))
  7684. selected_text = '''
  7685. <p><span style="font-size:{tsize}px"><strong>{title}</strong></span></p>
  7686. <p><span style="font-size:{fsize}px"><strong>{subtitle}</strong>:<br />
  7687. {s1}</span></p>
  7688. <ol>
  7689. <li><span style="font-size:{fsize}px">{s2}<br />
  7690. <br />
  7691. {s3}</span><br />
  7692. &nbsp;</li>
  7693. <li><span style="font-size:{fsize}px">{s4}<br />
  7694. &nbsp;</li>
  7695. <br />
  7696. <li><span style="font-size:{fsize}px">{s5}<br />
  7697. &nbsp;</li>
  7698. <br />
  7699. <li><span style="font-size:{fsize}px">{s6}<br />
  7700. <br />
  7701. {s7}</span></li>
  7702. </ol>
  7703. <p><span style="font-size:{fsize}px">{s8}</span></p>
  7704. '''.format(
  7705. title=_("Selected Tab - Choose an Item from Project Tab"),
  7706. subtitle=_("Details"),
  7707. s1=_("The normal flow when working with the application is the following:"),
  7708. s2=_("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into the application "
  7709. "using either the toolbars, key shortcuts or even dragging and dropping the "
  7710. "files on the GUI."),
  7711. s3=_("You can also load a project by double clicking on the project file, "
  7712. "drag and drop of the file into the GUI or through the menu (or toolbar) "
  7713. "actions offered within the app."),
  7714. s4=_("Once an object is available in the Project Tab, by selecting it and then focusing "
  7715. "on SELECTED TAB (more simpler is to double click the object name in the Project Tab, "
  7716. "SELECTED TAB will be updated with the object properties according to its kind: "
  7717. "Gerber, Excellon, Geometry or CNCJob object."),
  7718. s5=_("If the selection of the object is done on the canvas by single click instead, "
  7719. "and the SELECTED TAB is in focus, again the object properties will be displayed into the "
  7720. "Selected Tab. Alternatively, double clicking on the object on the canvas will bring "
  7721. "the SELECTED TAB and populate it even if it was out of focus."),
  7722. s6=_("You can change the parameters in this screen and the flow direction is like this:"),
  7723. s7=_("Gerber/Excellon Object --> Change Parameter --> Generate Geometry --> Geometry Object --> "
  7724. "Add tools (change param in Selected Tab) --> Generate CNCJob --> CNCJob Object --> "
  7725. "Verify GCode (through Edit CNC Code) and/or append/prepend to GCode "
  7726. "(again, done in SELECTED TAB) --> Save GCode."),
  7727. s8=_("A list of key shortcuts is available through an menu entry in Help --> Shortcuts List "
  7728. "or through its own key shortcut: <b>F3</b>."),
  7729. tsize=tsize,
  7730. fsize=fsize
  7731. )
  7732. sel_title.setText(selected_text)
  7733. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  7734. self.ui.selected_scroll_area.setWidget(sel_title)
  7735. def setup_obj_classes(self):
  7736. """
  7737. Sets up application specifics on the FlatCAMObj class. This way the object.app attribute will point to the App
  7738. class.
  7739. :return: None
  7740. """
  7741. FlatCAMObj.app = self
  7742. ObjectCollection.app = self
  7743. Gerber.app = self
  7744. Excellon.app = self
  7745. Geometry.app = self
  7746. CNCjob.app = self
  7747. FCProcess.app = self
  7748. FCProcessContainer.app = self
  7749. OptionsGroupUI.app = self
  7750. def version_check(self):
  7751. """
  7752. Checks for the latest version of the program. Alerts the
  7753. user if theirs is outdated. This method is meant to be run
  7754. in a separate thread.
  7755. :return: None
  7756. """
  7757. self.log.debug("version_check()")
  7758. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  7759. full_url = "%s?s=%s&v=%s&os=%s&%s" % (
  7760. App.version_url,
  7761. str(self.defaults['global_serial']),
  7762. str(self.version),
  7763. str(self.os),
  7764. urllib.parse.urlencode(self.defaults["global_stats"])
  7765. )
  7766. # full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + \
  7767. # "&v=" + str(self.version) + "&os=" + str(self.os) + "&" + \
  7768. # urllib.parse.urlencode(self.defaults["global_stats"])
  7769. else:
  7770. # no_stats dict; just so it won't break things on website
  7771. no_ststs_dict = {}
  7772. no_ststs_dict["global_ststs"] = {}
  7773. full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + "&v=" + str(self.version)
  7774. full_url += "&os=" + str(self.os) + "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  7775. App.log.debug("Checking for updates @ %s" % full_url)
  7776. # ## Get the data
  7777. try:
  7778. f = urllib.request.urlopen(full_url)
  7779. except Exception:
  7780. # App.log.warning("Failed checking for latest version. Could not connect.")
  7781. self.log.warning("Failed checking for latest version. Could not connect.")
  7782. self.inform.emit('[WARNING_NOTCL] %s' % _("Failed checking for latest version. Could not connect."))
  7783. return
  7784. try:
  7785. data = json.load(f)
  7786. except Exception as e:
  7787. App.log.error("Could not parse information about latest version.")
  7788. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not parse information about latest version."))
  7789. App.log.debug("json.load(): %s" % str(e))
  7790. f.close()
  7791. return
  7792. f.close()
  7793. # ## Latest version?
  7794. if self.version >= data["version"]:
  7795. App.log.debug("FlatCAM is up to date!")
  7796. self.inform.emit('[success] %s' % _("FlatCAM is up to date!"))
  7797. return
  7798. App.log.debug("Newer version available.")
  7799. self.message.emit(
  7800. _("Newer Version Available"),
  7801. '%s<br><br>><b>%s</b><br>%s' % (
  7802. _("There is a newer version of FlatCAM available for download:"),
  7803. str(data["name"]),
  7804. str(data["message"])
  7805. ),
  7806. _("info")
  7807. )
  7808. def on_plotcanvas_setup(self, container=None):
  7809. """
  7810. This is doing the setup for the plot area (canvas).
  7811. :param container: QT Widget where to install the canvas
  7812. :return: None
  7813. """
  7814. if container:
  7815. plot_container = container
  7816. else:
  7817. plot_container = self.ui.right_layout
  7818. modifier = QtWidgets.QApplication.queryKeyboardModifiers()
  7819. if self.is_legacy is True or modifier == QtCore.Qt.ControlModifier:
  7820. self.is_legacy = True
  7821. self.defaults["global_graphic_engine"] = "2D"
  7822. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  7823. else:
  7824. try:
  7825. self.plotcanvas = PlotCanvas(plot_container, self)
  7826. except Exception as er:
  7827. msg_txt = traceback.format_exc()
  7828. log.debug("App.on_plotcanvas_setup() failed -> %s" % str(er))
  7829. log.debug("OpenGL canvas initialization failed with the following error.\n" + msg_txt)
  7830. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  7831. msg += _("OpenGL canvas initialization failed. HW or HW configuration not supported."
  7832. "Change the graphic engine to Legacy(2D) in Edit -> Preferences -> General tab.\n\n")
  7833. msg += msg_txt
  7834. self.inform.emit(msg)
  7835. return 'fail'
  7836. # So it can receive key presses
  7837. self.plotcanvas.native.setFocus()
  7838. if self.is_legacy is False:
  7839. pan_button = 2 if self.defaults["global_pan_button"] == '2' else 3
  7840. # Set the mouse button for panning
  7841. self.plotcanvas.view.camera.pan_button_setting = pan_button
  7842. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  7843. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  7844. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  7845. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_mouse_double_click_over_plot)
  7846. # Keys over plot enabled
  7847. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  7848. if self.defaults['global_cursor_type'] == 'small':
  7849. self.app_cursor = self.plotcanvas.new_cursor()
  7850. else:
  7851. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  7852. if self.ui.grid_snap_btn.isChecked():
  7853. self.app_cursor.enabled = True
  7854. else:
  7855. self.app_cursor.enabled = False
  7856. if self.is_legacy is False:
  7857. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  7858. else:
  7859. # will use the default Matplotlib axes
  7860. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  7861. def on_zoom_fit(self):
  7862. """
  7863. Callback for zoom-fit request. This can be either from the corresponding
  7864. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  7865. with axes limits from the geometry bounds of all objects.
  7866. :return: None
  7867. """
  7868. if self.is_legacy is False:
  7869. self.plotcanvas.fit_view()
  7870. else:
  7871. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  7872. width = xmax - xmin
  7873. height = ymax - ymin
  7874. xmin -= 0.05 * width
  7875. xmax += 0.05 * width
  7876. ymin -= 0.05 * height
  7877. ymax += 0.05 * height
  7878. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  7879. def on_zoom_in(self):
  7880. """
  7881. Callback for zoom-in request.
  7882. :return:
  7883. """
  7884. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  7885. def on_zoom_out(self):
  7886. """
  7887. Callback for zoom-out request.
  7888. :return:
  7889. """
  7890. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  7891. def disable_all_plots(self):
  7892. self.defaults.report_usage("disable_all_plots()")
  7893. self.disable_plots(self.collection.get_list())
  7894. self.inform.emit('[success] %s' %
  7895. _("All plots disabled."))
  7896. def disable_other_plots(self):
  7897. self.defaults.report_usage("disable_other_plots()")
  7898. self.disable_plots(self.collection.get_non_selected())
  7899. self.inform.emit('[success] %s' %
  7900. _("All non selected plots disabled."))
  7901. def enable_all_plots(self):
  7902. self.defaults.report_usage("enable_all_plots()")
  7903. self.enable_plots(self.collection.get_list())
  7904. self.inform.emit('[success] %s' %
  7905. _("All plots enabled."))
  7906. def on_enable_sel_plots(self):
  7907. log.debug("App.on_enable_sel_plot()")
  7908. object_list = self.collection.get_selected()
  7909. self.enable_plots(objects=object_list)
  7910. self.inform.emit('[success] %s' % _("Selected plots enabled..."))
  7911. def on_disable_sel_plots(self):
  7912. log.debug("App.on_disable_sel_plot()")
  7913. # self.inform.emit(_("Disabling plots ..."))
  7914. object_list = self.collection.get_selected()
  7915. self.disable_plots(objects=object_list)
  7916. self.inform.emit('[success] %s' % _("Selected plots disabled..."))
  7917. def enable_plots(self, objects):
  7918. """
  7919. Enable plots
  7920. :param objects: list of Objects to be enabled
  7921. :return:
  7922. """
  7923. log.debug("Enabling plots ...")
  7924. # self.inform.emit(_("Working ..."))
  7925. for obj in objects:
  7926. if obj.options['plot'] is False:
  7927. obj.options.set_change_callback(lambda x: None)
  7928. obj.options['plot'] = True
  7929. try:
  7930. # only the Gerber obj has on_plot_cb_click() method
  7931. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  7932. # disable this cb while disconnected,
  7933. # in case the operation takes time the user is not allowed to change it
  7934. obj.ui.plot_cb.setDisabled(True)
  7935. except AttributeError:
  7936. pass
  7937. obj.set_form_item("plot")
  7938. try:
  7939. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  7940. obj.ui.plot_cb.setDisabled(False)
  7941. except AttributeError:
  7942. pass
  7943. obj.options.set_change_callback(obj.on_options_change)
  7944. def worker_task(objs):
  7945. with self.proc_container.new(_("Enabling plots ...")):
  7946. for plot_obj in objs:
  7947. # obj.options['plot'] = True
  7948. if isinstance(plot_obj, CNCJobObject):
  7949. plot_obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  7950. else:
  7951. plot_obj.plot(visible=True)
  7952. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  7953. def disable_plots(self, objects):
  7954. """
  7955. Disables plots
  7956. :param objects: list of Objects to be disabled
  7957. :return:
  7958. """
  7959. # if no objects selected then do nothing
  7960. if not self.collection.get_selected():
  7961. return
  7962. log.debug("Disabling plots ...")
  7963. # self.inform.emit(_("Working ..."))
  7964. for obj in objects:
  7965. if obj.options['plot'] is True:
  7966. obj.options.set_change_callback(lambda x: None)
  7967. obj.options['plot'] = False
  7968. try:
  7969. # only the Gerber obj has on_plot_cb_click() method
  7970. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  7971. obj.ui.plot_cb.setDisabled(True)
  7972. except AttributeError:
  7973. pass
  7974. obj.set_form_item("plot")
  7975. try:
  7976. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  7977. obj.ui.plot_cb.setDisabled(False)
  7978. except AttributeError:
  7979. pass
  7980. obj.options.set_change_callback(obj.on_options_change)
  7981. try:
  7982. self.delete_selection_shape()
  7983. except Exception as e:
  7984. log.debug("App.disable_plots() --> %s" % str(e))
  7985. def worker_task(objs):
  7986. with self.proc_container.new(_("Disabling plots ...")):
  7987. for plot_obj in objs:
  7988. # obj.options['plot'] = True
  7989. if isinstance(plot_obj, CNCJobObject):
  7990. plot_obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  7991. else:
  7992. plot_obj.plot(visible=False)
  7993. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  7994. def toggle_plots(self, objects):
  7995. """
  7996. Toggle plots visibility
  7997. :param objects: list of Objects for which to be toggled the visibility
  7998. :return: None
  7999. """
  8000. # if no objects selected then do nothing
  8001. if not self.collection.get_selected():
  8002. return
  8003. log.debug("Toggling plots ...")
  8004. self.inform.emit(_("Working ..."))
  8005. for obj in objects:
  8006. if obj.options['plot'] is False:
  8007. obj.options['plot'] = True
  8008. else:
  8009. obj.options['plot'] = False
  8010. self.app_obj.plots_updated.emit()
  8011. def clear_plots(self):
  8012. """
  8013. Clear the plots
  8014. :return: None
  8015. """
  8016. objects = self.collection.get_list()
  8017. for obj in objects:
  8018. obj.clear(obj == objects[-1])
  8019. # Clear pool to free memory
  8020. self.clear_pool()
  8021. def on_set_color_action_triggered(self):
  8022. """
  8023. This slot gets called by clicking on the menu entry in the Set Color submenu of the context menu in Project Tab
  8024. :return:
  8025. """
  8026. new_color = self.defaults['gerber_plot_fill']
  8027. clicked_action = self.sender()
  8028. assert isinstance(clicked_action, QAction), "Expected a QAction, got %s" % type(clicked_action)
  8029. act_name = clicked_action.text()
  8030. sel_obj_list = self.collection.get_selected()
  8031. if not sel_obj_list:
  8032. return
  8033. # a default value, I just chose this one
  8034. alpha_level = 'BF'
  8035. for sel_obj in sel_obj_list:
  8036. if sel_obj.kind == 'excellon':
  8037. alpha_level = str(hex(
  8038. self.ui.excellon_defaults_form.excellon_gen_group.excellon_alpha_entry.get_value())[2:])
  8039. elif sel_obj.kind == 'gerber':
  8040. alpha_level = str(hex(self.ui.gerber_defaults_form.gerber_gen_group.gerber_alpha_entry.get_value())[2:])
  8041. elif sel_obj.kind == 'geometry':
  8042. alpha_level = 'FF'
  8043. else:
  8044. log.debug(
  8045. "App.on_set_color_action_triggered() --> Default alpfa for this object type not supported yet")
  8046. continue
  8047. sel_obj.alpha_level = alpha_level
  8048. if act_name == _('Red'):
  8049. new_color = '#FF0000' + alpha_level
  8050. if act_name == _('Blue'):
  8051. new_color = '#0000FF' + alpha_level
  8052. if act_name == _('Yellow'):
  8053. new_color = '#FFDF00' + alpha_level
  8054. if act_name == _('Green'):
  8055. new_color = '#00FF00' + alpha_level
  8056. if act_name == _('Purple'):
  8057. new_color = '#FF00FF' + alpha_level
  8058. if act_name == _('Brown'):
  8059. new_color = '#A52A2A' + alpha_level
  8060. if act_name == _('White'):
  8061. new_color = '#FFFFFF' + alpha_level
  8062. if act_name == _('Black'):
  8063. new_color = '#000000' + alpha_level
  8064. if act_name == _('Custom'):
  8065. new_color = QtGui.QColor(self.defaults['gerber_plot_fill'][:7])
  8066. c_dialog = QtWidgets.QColorDialog()
  8067. plot_fill_color = c_dialog.getColor(initial=new_color)
  8068. if plot_fill_color.isValid() is False:
  8069. return
  8070. new_color = str(plot_fill_color.name()) + alpha_level
  8071. if act_name == _("Default"):
  8072. for sel_obj in sel_obj_list:
  8073. if sel_obj.kind == 'excellon':
  8074. new_color = self.defaults['excellon_plot_fill']
  8075. new_line_color = self.defaults['excellon_plot_line']
  8076. elif sel_obj.kind == 'gerber':
  8077. new_color = self.defaults['gerber_plot_fill']
  8078. new_line_color = self.defaults['gerber_plot_line']
  8079. elif sel_obj.kind == 'geometry':
  8080. new_color = self.defaults['geometry_plot_line']
  8081. new_line_color = self.defaults['geometry_plot_line']
  8082. else:
  8083. log.debug(
  8084. "App.on_set_color_action_triggered() --> Default color for this object type not supported yet")
  8085. continue
  8086. sel_obj.fill_color = new_color
  8087. sel_obj.outline_color = new_line_color
  8088. sel_obj.shapes.redraw(
  8089. update_colors=(new_color, new_line_color)
  8090. )
  8091. return
  8092. if act_name == _("Opacity"):
  8093. alpha_level, ok_button = QtWidgets.QInputDialog.getInt(
  8094. self.ui, _("Set alpha level ..."), '%s:' % _("Value"), min=0, max=255, step=1, value=191)
  8095. if ok_button:
  8096. alpha_str = str(hex(alpha_level)[2:]) if alpha_level != 0 else '00'
  8097. for sel_obj in sel_obj_list:
  8098. sel_obj.fill_color = sel_obj.fill_color[:-2] + alpha_str
  8099. sel_obj.shapes.redraw(
  8100. update_colors=(sel_obj.fill_color, sel_obj.outline_color)
  8101. )
  8102. return
  8103. new_line_color = color_variant(new_color[:7], 0.7)
  8104. if act_name == _("White"):
  8105. new_line_color = color_variant("#dedede", 0.7)
  8106. for sel_obj in sel_obj_list:
  8107. sel_obj.fill_color = new_color
  8108. sel_obj.outline_color = new_line_color
  8109. sel_obj.shapes.redraw(
  8110. update_colors=(new_color, new_line_color)
  8111. )
  8112. def generate_cnc_job(self, objects):
  8113. """
  8114. Slot that will be called by clicking an entry in the contextual menu generated in the Project Tab tree
  8115. :param objects: Selected objects in the Project Tab
  8116. :return:
  8117. """
  8118. self.defaults.report_usage("generate_cnc_job()")
  8119. # for obj in objects:
  8120. # obj.generatecncjob()
  8121. for obj in objects:
  8122. obj.on_generatecnc_button_click()
  8123. def save_project(self, filename, quit_action=False, silent=False, from_tcl=False):
  8124. """
  8125. Saves the current project to the specified file.
  8126. :param filename: Name of the file in which to save.
  8127. :type filename: str
  8128. :param quit_action: if the project saving will be followed by an app quit; boolean
  8129. :param silent: if True will not display status messages
  8130. :param from_tcl True is run from Tcl Shell
  8131. :return: None
  8132. """
  8133. self.log.debug("save_project()")
  8134. self.save_in_progress = True
  8135. with self.proc_container.new(_("Saving FlatCAM Project")):
  8136. # Capture the latest changes
  8137. # Current object
  8138. try:
  8139. current_object = self.collection.get_active()
  8140. if current_object:
  8141. current_object.read_form()
  8142. except Exception as e:
  8143. self.log.debug("save_project() --> There was no active object. Skipping read_form. %s" % str(e))
  8144. pass
  8145. # Serialize the whole project
  8146. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  8147. "options": self.options,
  8148. "version": self.version}
  8149. if self.defaults["global_save_compressed"] is True:
  8150. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  8151. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  8152. # # Write
  8153. f.write(g)
  8154. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8155. else:
  8156. # Open file
  8157. try:
  8158. f = open(filename, 'w')
  8159. except IOError:
  8160. App.log.error("Failed to open file for saving: %s", filename)
  8161. self.inform.emit('[ERROR_NOTCL] %s' % _("The object is used by another application."))
  8162. return
  8163. # Write
  8164. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  8165. f.close()
  8166. # verification of the saved project
  8167. # Open and parse
  8168. try:
  8169. saved_f = open(filename, 'r')
  8170. except IOError:
  8171. if silent is False:
  8172. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8173. (_("Failed to verify project file"), filename, _("Retry to save it.")))
  8174. return
  8175. try:
  8176. saved_d = json.load(saved_f, object_hook=dict2obj)
  8177. except Exception:
  8178. if silent is False:
  8179. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8180. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8181. f.close()
  8182. return
  8183. saved_f.close()
  8184. if silent is False:
  8185. if 'version' in saved_d:
  8186. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8187. else:
  8188. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8189. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8190. tb_settings = QSettings("Open Source", "FlatCAM")
  8191. lock_state = self.ui.lock_action.isChecked()
  8192. tb_settings.setValue('toolbar_lock', lock_state)
  8193. # This will write the setting to the platform specific storage.
  8194. del tb_settings
  8195. # if quit:
  8196. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  8197. # t.start()
  8198. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  8199. def start_delayed_quit(self, delay, filename, should_quit=None):
  8200. """
  8201. :param delay: period of checking if project file size is more than zero; in seconds
  8202. :param filename: the name of the project file to be checked periodically for size more than zero
  8203. :param should_quit: if the task finished will be followed by an app quit; boolean
  8204. :return:
  8205. """
  8206. to_quit = should_quit
  8207. self.save_timer = QtCore.QTimer()
  8208. self.save_timer.setInterval(delay)
  8209. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  8210. self.save_timer.start()
  8211. def check_project_file_size(self, filename, should_quit=None):
  8212. """
  8213. :param filename: the name of the project file to be checked periodically for size more than zero
  8214. :param should_quit: will quit the app if True; boolean
  8215. :return:
  8216. """
  8217. try:
  8218. if os.stat(filename).st_size > 0:
  8219. self.save_in_progress = False
  8220. self.save_timer.stop()
  8221. if should_quit:
  8222. self.app_quit.emit()
  8223. except Exception:
  8224. traceback.print_exc()
  8225. def save_project_auto(self):
  8226. """
  8227. Called periodically to save the project.
  8228. 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
  8229. # progress.
  8230. :return:
  8231. """
  8232. if self.block_autosave is False and self.should_we_save is True and self.save_in_progress is False:
  8233. self.on_file_saveproject()
  8234. def save_project_auto_update(self):
  8235. """
  8236. Update the auto save time interval value.
  8237. :return:
  8238. """
  8239. log.debug("App.save_project_auto_update() --> updated the interval timeout.")
  8240. try:
  8241. if self.autosave_timer.isActive():
  8242. self.autosave_timer.stop()
  8243. except Exception:
  8244. pass
  8245. if self.defaults['global_autosave'] is True:
  8246. self.autosave_timer.setInterval(int(self.defaults['global_autosave_timeout']))
  8247. self.autosave_timer.start()
  8248. def on_options_app2project(self):
  8249. """
  8250. Callback for Options->Transfer Options->App=>Project. Copies options
  8251. from application defaults to project defaults.
  8252. :return: None
  8253. """
  8254. self.defaults.report_usage("on_options_app2project")
  8255. self.preferencesUiManager.defaults_read_form()
  8256. self.options.update(self.defaults)
  8257. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  8258. """
  8259. Shows a message on the FlatCAM Shell
  8260. :param msg: Message to display.
  8261. :param show: Opens the shell.
  8262. :param error: Shows the message as an error.
  8263. :param warning: Shows the message as an warning.
  8264. :param success: Shows the message as an success.
  8265. :param selected: Indicate that something was selected on canvas
  8266. :return: None
  8267. """
  8268. if show:
  8269. self.ui.shell_dock.show()
  8270. try:
  8271. if error:
  8272. self.shell.append_error(msg + "\n")
  8273. elif warning:
  8274. self.shell.append_warning(msg + "\n")
  8275. elif success:
  8276. self.shell.append_success(msg + "\n")
  8277. elif selected:
  8278. self.shell.append_selected(msg + "\n")
  8279. else:
  8280. self.shell.append_output(msg + "\n")
  8281. except AttributeError:
  8282. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  8283. class ArgsThread(QtCore.QObject):
  8284. open_signal = pyqtSignal(list)
  8285. start = pyqtSignal()
  8286. stop = pyqtSignal()
  8287. if sys.platform == 'win32':
  8288. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  8289. else:
  8290. address = ('/tmp/testipc', 'AF_UNIX')
  8291. def __init__(self):
  8292. super().__init__()
  8293. self.listener = None
  8294. self.thread_exit = False
  8295. self.start.connect(self.run)
  8296. self.stop.connect(self.close_listener)
  8297. def my_loop(self, address):
  8298. try:
  8299. self.listener = Listener(*address)
  8300. while self.thread_exit is False:
  8301. conn = self.listener.accept()
  8302. self.serve(conn)
  8303. except socket.error:
  8304. try:
  8305. conn = Client(*address)
  8306. conn.send(sys.argv)
  8307. conn.send('close')
  8308. # close the current instance only if there are args
  8309. if len(sys.argv) > 1:
  8310. try:
  8311. self.listener.close()
  8312. except Exception:
  8313. pass
  8314. sys.exit()
  8315. except ConnectionRefusedError:
  8316. if sys.platform == 'win32':
  8317. pass
  8318. else:
  8319. os.system('rm /tmp/testipc')
  8320. self.listener = Listener(*address)
  8321. while True:
  8322. conn = self.listener.accept()
  8323. self.serve(conn)
  8324. def serve(self, conn):
  8325. while self.thread_exit is False:
  8326. msg = conn.recv()
  8327. if msg == 'close':
  8328. break
  8329. self.open_signal.emit(msg)
  8330. conn.close()
  8331. # the decorator is a must; without it this technique will not work unless the start signal is connected
  8332. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  8333. @pyqtSlot()
  8334. def run(self):
  8335. self.my_loop(self.address)
  8336. @pyqtSlot()
  8337. def close_listener(self):
  8338. self.thread_exit = True
  8339. self.listener.close()
  8340. # end of file