FlatCAMApp.py 578 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797
  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. # ###########################################################
  8. import urllib.request
  9. import urllib.parse
  10. import urllib.error
  11. import webbrowser
  12. import getopt
  13. import random
  14. import simplejson as json
  15. import lzma
  16. import threading
  17. import shutil
  18. import stat
  19. from stat import S_IREAD, S_IRGRP, S_IROTH
  20. import ctypes
  21. # import tkinter as tk
  22. # from PyQt5 import QtPrintSupport
  23. from reportlab.graphics import renderPDF
  24. from reportlab.pdfgen import canvas
  25. from reportlab.graphics import renderPM
  26. from reportlab.lib.units import inch, mm
  27. from reportlab.lib.pagesizes import landscape, portrait
  28. from svglib.svglib import svg2rlg
  29. from contextlib import contextmanager
  30. import gc
  31. from xml.dom.minidom import parseString as parse_xml_string
  32. from multiprocessing.connection import Listener, Client
  33. from multiprocessing import Pool
  34. import socket
  35. from array import array
  36. import vispy.scene as scene
  37. # #######################################
  38. # # Imports part of FlatCAM ##
  39. # #######################################
  40. from ObjectCollection import *
  41. from FlatCAMObj import *
  42. from camlib import to_dict, dict2obj, ET, ParseError
  43. from flatcamGUI.PlotCanvas import *
  44. from flatcamGUI.PlotCanvasLegacy import *
  45. from flatcamGUI.FlatCAMGUI import *
  46. from FlatCAMCommon import LoudDict, BookmarkManager, ToolsDB, color_variant
  47. from FlatCAMPostProc import load_preprocessors
  48. from flatcamEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
  49. from flatcamEditors.FlatCAMExcEditor import FlatCAMExcEditor
  50. from flatcamEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  51. from flatcamEditors.FlatCAMTextEditor import TextEditor
  52. from flatcamParsers.ParseHPGL2 import HPGL2
  53. from FlatCAMProcess import *
  54. from FlatCAMWorkerStack import WorkerStack
  55. # from flatcamGUI.VisPyVisuals import Color
  56. from vispy.gloo.util import _screenshot
  57. from vispy.io import write_png
  58. from flatcamTools import *
  59. import tclCommands
  60. import gettext
  61. import FlatCAMTranslation as fcTranslate
  62. import builtins
  63. if sys.platform == 'win32':
  64. import winreg
  65. fcTranslate.apply_language('strings')
  66. if '_' not in builtins.__dict__:
  67. _ = gettext.gettext
  68. class App(QtCore.QObject):
  69. # ########################################
  70. # # App ###
  71. # ########################################
  72. """
  73. The main application class. The constructor starts the GUI.
  74. """
  75. # Get Cmd Line Options
  76. cmd_line_shellfile = ''
  77. cmd_line_shellvar = ''
  78. cmd_line_headless = None
  79. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>\n" \
  80. "FlatCam.py --shellvar=<1,'C:\\path',23>\n" \
  81. "FlatCam.py --headless=1"
  82. try:
  83. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  84. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=",
  85. "shellvar=",
  86. "headless=",
  87. "multiprocessing-fork="])
  88. except getopt.GetoptError:
  89. print(cmd_line_help)
  90. sys.exit(2)
  91. for opt, arg in cmd_line_options:
  92. if opt == '-h':
  93. print(cmd_line_help)
  94. sys.exit()
  95. elif opt == '--shellfile':
  96. cmd_line_shellfile = arg
  97. elif opt == '--shellvar':
  98. cmd_line_shellvar = arg
  99. elif opt == '--headless':
  100. try:
  101. cmd_line_headless = eval(arg)
  102. except NameError:
  103. pass
  104. # ## Logging ###
  105. log = logging.getLogger('base')
  106. log.setLevel(logging.DEBUG)
  107. # log.setLevel(logging.WARNING)
  108. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  109. handler = logging.StreamHandler()
  110. handler.setFormatter(formatter)
  111. log.addHandler(handler)
  112. # ##########################################################################
  113. # ################## Version and VERSION DATE ##############################
  114. # ##########################################################################
  115. version = 8.992
  116. version_date = "2020/01/30"
  117. beta = True
  118. engine = '3D'
  119. # current date now
  120. date = str(datetime.today()).rpartition('.')[0]
  121. date = ''.join(c for c in date if c not in ':-')
  122. date = date.replace(' ', '_')
  123. # URL for update checks and statistics
  124. version_url = "http://flatcam.org/version"
  125. # App URL
  126. app_url = "http://flatcam.org"
  127. # Manual URL
  128. manual_url = "http://flatcam.org/manual/index.html"
  129. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  130. gerber_spec_url = "https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  131. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  132. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  133. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  134. # this variable will hold the project status
  135. # if True it will mean that the project was modified and not saved
  136. should_we_save = False
  137. # flag is True if saving action has been triggered
  138. save_in_progress = False
  139. # ###########################################################################
  140. # ############################# Signals ################################
  141. # ###########################################################################
  142. # Inform the user
  143. # Handled by:
  144. # * App.info() --> Print on the status bar
  145. inform = QtCore.pyqtSignal(str)
  146. app_quit = QtCore.pyqtSignal()
  147. # General purpose background task
  148. worker_task = QtCore.pyqtSignal(dict)
  149. # File opened
  150. # Handled by:
  151. # * register_folder()
  152. # * register_recent()
  153. # Note: Setting the parameters to unicode does not seem
  154. # to have an effect. Then are received as Qstring
  155. # anyway.
  156. # File type and filename
  157. file_opened = QtCore.pyqtSignal(str, str)
  158. # File type and filename
  159. file_saved = QtCore.pyqtSignal(str, str)
  160. # Percentage of progress
  161. progress = QtCore.pyqtSignal(int)
  162. plots_updated = QtCore.pyqtSignal()
  163. # Emitted by new_object() and passes the new object as argument, plot flag.
  164. # on_object_created() adds the object to the collection, plots on appropriate flag
  165. # and emits new_object_available.
  166. object_created = QtCore.pyqtSignal(object, bool, bool)
  167. # Emitted when a object has been changed (like scaled, mirrored)
  168. object_changed = QtCore.pyqtSignal(object)
  169. # Emitted after object has been plotted.
  170. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  171. object_plotted = QtCore.pyqtSignal(object)
  172. # Emitted when a new object has been added or deleted from/to the collection
  173. object_status_changed = QtCore.pyqtSignal(object, str, str)
  174. message = QtCore.pyqtSignal(str, str, str)
  175. # Emmited when shell command is finished(one command only)
  176. shell_command_finished = QtCore.pyqtSignal(object)
  177. # Emitted when multiprocess pool has been recreated
  178. pool_recreated = QtCore.pyqtSignal(object)
  179. # Emitted when an unhandled exception happens
  180. # in the worker task.
  181. thread_exception = QtCore.pyqtSignal(object)
  182. # used to signal that there are arguments for the app
  183. args_at_startup = QtCore.pyqtSignal(list)
  184. # a reusable signal to replot a list of objects
  185. # should be disconnected after use so it can be reused
  186. replot_signal = pyqtSignal(list)
  187. # signal emitted when jumping
  188. jump_signal = pyqtSignal(tuple)
  189. # signal emitted when jumping
  190. locate_signal = pyqtSignal(tuple, str)
  191. # close app signal
  192. close_app_signal = pyqtSignal()
  193. def __init__(self, user_defaults=True):
  194. """
  195. Starts the application.
  196. :return: app
  197. :rtype: App
  198. """
  199. App.log.info("FlatCAM Starting...")
  200. self.main_thread = QtWidgets.QApplication.instance().thread()
  201. # #########################################################################
  202. # Setup the listening thread for another instance launching with args #####
  203. # #########################################################################
  204. if sys.platform == 'win32' or sys.platform == 'linux':
  205. # make sure the thread is stored by using a self. otherwise it's garbage collected
  206. self.th = QtCore.QThread()
  207. self.th.start(priority=QtCore.QThread.LowestPriority)
  208. self.new_launch = ArgsThread()
  209. self.new_launch.open_signal[list].connect(self.on_startup_args)
  210. self.new_launch.moveToThread(self.th)
  211. self.new_launch.start.emit()
  212. # ############################################################################
  213. # # ################# OS-specific ############################################
  214. # ############################################################################
  215. portable = False
  216. # Folder for user settings.
  217. if sys.platform == 'win32':
  218. from win32comext.shell import shell, shellcon
  219. if platform.architecture()[0] == '32bit':
  220. App.log.debug("Win32!")
  221. else:
  222. App.log.debug("Win64!")
  223. # #########################################################################
  224. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY ###############
  225. # #########################################################################
  226. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  227. try:
  228. with open(config_file, 'r'):
  229. pass
  230. except FileNotFoundError:
  231. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  232. try:
  233. with open(config_file, 'r') as f:
  234. try:
  235. for line in f:
  236. param = str(line).replace('\n', '').rpartition('=')
  237. if param[0] == 'portable':
  238. try:
  239. portable = eval(param[2])
  240. except NameError:
  241. portable = False
  242. if param[0] == 'headless':
  243. if param[2].lower() == 'true':
  244. self.cmd_line_headless = 1
  245. else:
  246. self.cmd_line_headless = None
  247. except Exception as e:
  248. log.debug('App.__init__() -->%s' % str(e))
  249. return
  250. except FileNotFoundError as e:
  251. log.debug(str(e))
  252. pass
  253. if portable is False:
  254. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  255. else:
  256. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  257. self.os = 'windows'
  258. else: # Linux/Unix/MacOS
  259. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  260. self.os = 'unix'
  261. # ##########################################################################
  262. # ################## Setup folders and files ###############################
  263. # ##########################################################################
  264. if not os.path.exists(self.data_path):
  265. os.makedirs(self.data_path)
  266. App.log.debug('Created data folder: ' + self.data_path)
  267. os.makedirs(os.path.join(self.data_path, 'preprocessors'))
  268. App.log.debug('Created data preprocessors folder: ' + os.path.join(self.data_path, 'preprocessors'))
  269. self.preprocessorpaths = os.path.join(self.data_path, 'preprocessors')
  270. if not os.path.exists(self.preprocessorpaths):
  271. os.makedirs(self.preprocessorpaths)
  272. App.log.debug('Created preprocessors folder: ' + self.preprocessorpaths)
  273. # create geo_tools_db.FlatDB file if there is none
  274. try:
  275. f = open(self.data_path + '/geo_tools_db.FlatDB')
  276. f.close()
  277. except IOError:
  278. App.log.debug('Creating empty geo_tool_db.FlatDB')
  279. f = open(self.data_path + '/geo_tools_db.FlatDB', 'w')
  280. json.dump({}, f)
  281. f.close()
  282. # create fctool_tools_db.FlatDB file if there is none
  283. try:
  284. f = open(self.data_path + '/fctool_tools_db.FlatDB')
  285. f.close()
  286. except IOError:
  287. App.log.debug('Creating empty fctool_tool_db.FlatDB')
  288. f = open(self.data_path + '/fctool_tools_db.FlatDB', 'w')
  289. json.dump({}, f)
  290. f.close()
  291. # create current_defaults.FlatConfig file if there is none
  292. try:
  293. f = open(self.data_path + '/current_defaults.FlatConfig')
  294. f.close()
  295. except IOError:
  296. App.log.debug('Creating empty current_defaults.FlatConfig')
  297. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  298. json.dump({}, f)
  299. f.close()
  300. # create factory_defaults.FlatConfig file if there is none
  301. try:
  302. f = open(self.data_path + '/factory_defaults.FlatConfig')
  303. f.close()
  304. except IOError:
  305. App.log.debug('Creating empty factory_defaults.FlatConfig')
  306. f = open(self.data_path + '/factory_defaults.FlatConfig', 'w')
  307. json.dump({}, f)
  308. f.close()
  309. # create a recent files json file if there is none
  310. try:
  311. f = open(self.data_path + '/recent.json')
  312. f.close()
  313. except IOError:
  314. App.log.debug('Creating empty recent.json')
  315. f = open(self.data_path + '/recent.json', 'w')
  316. json.dump([], f)
  317. f.close()
  318. # create a recent projects json file if there is none
  319. try:
  320. fp = open(self.data_path + '/recent_projects.json')
  321. fp.close()
  322. except IOError:
  323. App.log.debug('Creating empty recent_projects.json')
  324. fp = open(self.data_path + '/recent_projects.json', 'w')
  325. json.dump([], fp)
  326. fp.close()
  327. # Application directory. CHDIR to it. Otherwise, trying to load
  328. # GUI icons will fail as their path is relative.
  329. # This will fail under cx_freeze ...
  330. self.app_home = os.path.dirname(os.path.realpath(__file__))
  331. App.log.debug("Application path is " + self.app_home)
  332. App.log.debug("Started in " + os.getcwd())
  333. # cx_freeze workaround
  334. if os.path.isfile(self.app_home):
  335. self.app_home = os.path.dirname(self.app_home)
  336. os.chdir(self.app_home)
  337. # #################################################################################
  338. # #################### DEFAULTS - PREFERENCES STORAGE #############################
  339. # #################################################################################
  340. self.defaults = LoudDict()
  341. self.defaults.update({
  342. # Global APP Preferences
  343. "decimals_inch": 4,
  344. "decimals_metric": 4,
  345. "version": self.version,
  346. "first_run": True,
  347. "units": "MM",
  348. "global_serial": 0,
  349. "global_stats": dict(),
  350. "global_tabs_detachable": True,
  351. "global_jump_ref": 'abs',
  352. "global_locate_pt": 'bl',
  353. "global_tpdf_tmargin": 15.0,
  354. "global_tpdf_bmargin": 10.0,
  355. "global_tpdf_lmargin": 20.0,
  356. "global_tpdf_rmargin": 20.0,
  357. # General
  358. "global_graphic_engine": '3D',
  359. "global_app_level": 'b',
  360. "global_portable": False,
  361. "global_language": 'English',
  362. "global_version_check": True,
  363. "global_send_stats": True,
  364. "global_pan_button": '2',
  365. "global_mselect_key": 'Control',
  366. "global_project_at_startup": False,
  367. "global_systray_icon": True,
  368. "global_project_autohide": True,
  369. "global_toggle_tooltips": True,
  370. "global_worker_number": 2,
  371. "global_tolerance": 0.005,
  372. "global_open_style": True,
  373. "global_delete_confirmation": True,
  374. "global_compression_level": 3,
  375. "global_save_compressed": True,
  376. "global_machinist_setting": False,
  377. # Global GUI Preferences
  378. "global_gridx": 1.0,
  379. "global_gridy": 1.0,
  380. "global_snap_max": 0.05,
  381. "global_workspace": False,
  382. "global_workspaceT": "A4",
  383. "global_workspace_orientation": 'p',
  384. "global_grid_context_menu": {
  385. 'in': [0.01, 0.02, 0.025, 0.05, 0.1],
  386. 'mm': [0.1, 0.2, 0.5, 1, 2.54]
  387. },
  388. "global_sel_fill": '#a5a5ffbf',
  389. "global_sel_line": '#0000ffbf',
  390. "global_alt_sel_fill": '#BBF268BF',
  391. "global_alt_sel_line": '#006E20BF',
  392. "global_draw_color": '#FF0000',
  393. "global_sel_draw_color": '#0000FF',
  394. "global_proj_item_color": '#000000',
  395. "global_proj_item_dis_color": '#b7b7cb',
  396. "global_activity_icon": 'Ball green',
  397. "global_toolbar_view": 511,
  398. "global_background_timeout": 300000, # Default value is 5 minutes
  399. "global_verbose_error_level": 0, # Shell verbosity 0 = default
  400. # (python trace only for unknown errors),
  401. # 1 = show trace(show trace always),
  402. # 2 = (For the future).
  403. # Persistence
  404. "global_last_folder": None,
  405. "global_last_save_folder": None,
  406. # Default window geometry
  407. "global_def_win_x": 100,
  408. "global_def_win_y": 100,
  409. "global_def_win_w": 1024,
  410. "global_def_win_h": 650,
  411. "global_def_notebook_width": 1,
  412. # Constants...
  413. "global_defaults_save_period_ms": 20000, # Time between default saves.
  414. "global_shell_shape": [500, 300], # Shape of the shell in pixels.
  415. "global_shell_at_startup": False, # Show the shell at startup.
  416. "global_recent_limit": 10, # Max. items in recent list.
  417. "global_bookmarks": dict(),
  418. "global_bookmarks_limit": 10,
  419. "fit_key": 'V',
  420. "zoom_out_key": '-',
  421. "zoom_in_key": '=',
  422. "grid_toggle_key": 'G',
  423. "global_zoom_ratio": 1.5,
  424. "global_point_clipboard_format": "(%.*f, %.*f)",
  425. "global_zdownrate": None,
  426. # General GUI Settings
  427. "global_theme": 'white',
  428. "global_gray_icons": False,
  429. "global_hover": False,
  430. "global_selection_shape": True,
  431. "global_layout": "compact",
  432. "global_cursor_type": "small",
  433. "global_cursor_size": 20,
  434. "global_cursor_width": 2,
  435. "global_cursor_color": '#FF0000',
  436. "global_cursor_color_enabled": True,
  437. # Gerber General
  438. "gerber_plot": True,
  439. "gerber_solid": True,
  440. "gerber_multicolored": False,
  441. "gerber_circle_steps": 64,
  442. "gerber_use_buffer_for_union": True,
  443. "gerber_clean_apertures": True,
  444. "gerber_extra_buffering": True,
  445. "gerber_plot_fill": '#BBF268BF',
  446. "gerber_plot_line": '#006E20BF',
  447. "gerber_def_units": 'IN',
  448. "gerber_def_zeros": 'L',
  449. "gerber_save_filters": "Gerber File (*.gbr);;Gerber File (*.bot);;Gerber File (*.bsm);;"
  450. "Gerber File (*.cmp);;Gerber File (*.crc);;Gerber File (*.crs);;"
  451. "Gerber File (*.gb0);;Gerber File (*.gb1);;Gerber File (*.gb2);;"
  452. "Gerber File (*.gb3);;Gerber File (*.gb4);;Gerber File (*.gb5);;"
  453. "Gerber File (*.gb6);;Gerber File (*.gb7);;Gerber File (*.gb8);;"
  454. "Gerber File (*.gb9);;Gerber File (*.gbd);;Gerber File (*.gbl);;"
  455. "Gerber File (*.gbo);;Gerber File (*.gbp);;Gerber File (*.gbs);;"
  456. "Gerber File (*.gdo);;Gerber File (*.ger);;Gerber File (*.gko);;"
  457. "Gerber File (*.gm1);;Gerber File (*.gm2);;Gerber File (*.gm3);;"
  458. "Gerber File (*.grb);;Gerber File (*.gtl);;Gerber File (*.gto);;"
  459. "Gerber File (*.gtp);;Gerber File (*.gts);;Gerber File (*.ly15);;"
  460. "Gerber File (*.ly2);;Gerber File (*.mil);;Gerber File (*.pho);;"
  461. "Gerber File (*.plc);;Gerber File (*.pls);;Gerber File (*.smb);;"
  462. "Gerber File (*.smt);;Gerber File (*.sol);;Gerber File (*.spb);;"
  463. "Gerber File (*.spt);;Gerber File (*.ssb);;Gerber File (*.sst);;"
  464. "Gerber File (*.stc);;Gerber File (*.sts);;Gerber File (*.top);;"
  465. "Gerber File (*.tsm);;Gerber File (*.art)"
  466. "All Files (*.*)",
  467. # Gerber Options
  468. "gerber_isotooldia": 0.1,
  469. "gerber_isopasses": 1,
  470. "gerber_isooverlap": 10,
  471. "gerber_milling_type": "cl",
  472. "gerber_combine_passes": False,
  473. "gerber_iso_scope": 'all',
  474. "gerber_noncoppermargin": 0.1,
  475. "gerber_noncopperrounded": False,
  476. "gerber_bboxmargin": 0.1,
  477. "gerber_bboxrounded": False,
  478. # Gerber Advanced Options
  479. "gerber_aperture_display": False,
  480. "gerber_aperture_scale_factor": 1.0,
  481. "gerber_aperture_buffer_factor": 0.0,
  482. "gerber_follow": False,
  483. "gerber_tool_type": 'circular',
  484. "gerber_vtipdia": 0.1,
  485. "gerber_vtipangle": 30,
  486. "gerber_vcutz": -0.05,
  487. "gerber_iso_type": "full",
  488. "gerber_buffering": "full",
  489. "gerber_simplification": False,
  490. "gerber_simp_tolerance": 0.0005,
  491. # Gerber Export
  492. "gerber_exp_units": 'IN',
  493. "gerber_exp_integer": 2,
  494. "gerber_exp_decimals": 4,
  495. "gerber_exp_zeros": 'L',
  496. # Gerber Editor
  497. "gerber_editor_sel_limit": 30,
  498. "gerber_editor_newcode": 10,
  499. "gerber_editor_newsize": 0.8,
  500. "gerber_editor_newtype": 'C',
  501. "gerber_editor_newdim": "0.5, 0.5",
  502. "gerber_editor_array_size": 5,
  503. "gerber_editor_lin_axis": 'X',
  504. "gerber_editor_lin_pitch": 0.1,
  505. "gerber_editor_lin_angle": 0.0,
  506. "gerber_editor_circ_dir": 'CW',
  507. "gerber_editor_circ_angle": 0.0,
  508. "gerber_editor_scale_f": 1.0,
  509. "gerber_editor_buff_f": 0.1,
  510. "gerber_editor_ma_low": 0.0,
  511. "gerber_editor_ma_high": 1.0,
  512. # Excellon General
  513. "excellon_plot": True,
  514. "excellon_solid": True,
  515. "excellon_format_upper_in": 2,
  516. "excellon_format_lower_in": 4,
  517. "excellon_format_upper_mm": 3,
  518. "excellon_format_lower_mm": 3,
  519. "excellon_zeros": "L",
  520. "excellon_units": "INCH",
  521. "excellon_update": True,
  522. "excellon_optimization_type": 'B',
  523. "excellon_search_time": 3,
  524. "excellon_save_filters": "Excellon File (*.txt);;Excellon File (*.drd);;Excellon File (*.drl);;"
  525. "Excellon File (*.exc);;Excellon File (*.ncd);;Excellon File (*.tap);;"
  526. "Excellon File (*.xln);;All Files (*.*)",
  527. "excellon_plot_fill": '#C40000BF',
  528. "excellon_plot_line": '#750000BF',
  529. # Excellon Options
  530. "excellon_drillz": -1.7,
  531. "excellon_travelz": 2,
  532. "excellon_endz": 0.5,
  533. "excellon_feedrate": 300,
  534. "excellon_spindlespeed": 0,
  535. "excellon_dwell": False,
  536. "excellon_dwelltime": 1,
  537. "excellon_toolchange": False,
  538. "excellon_toolchangez": 15,
  539. "excellon_ppname_e": 'default',
  540. "excellon_tooldia": 0.8,
  541. "excellon_slot_tooldia": 1.8,
  542. "excellon_gcode_type": "drills",
  543. # Excellon Advanced Options
  544. "excellon_offset": 0.0,
  545. "excellon_toolchangexy": "0.0, 0.0",
  546. "excellon_startz": None,
  547. "excellon_feedrate_rapid": 1500,
  548. "excellon_z_pdepth": -0.02,
  549. "excellon_feedrate_probe": 75,
  550. "excellon_spindledir": 'CW',
  551. "excellon_f_plunge": False,
  552. "excellon_f_retract": False,
  553. # Excellon Export
  554. "excellon_exp_units": 'INCH',
  555. "excellon_exp_format": 'ndec',
  556. "excellon_exp_integer": 2,
  557. "excellon_exp_decimals": 4,
  558. "excellon_exp_zeros": 'LZ',
  559. "excellon_exp_slot_type": 'routing',
  560. # Excellon Editor
  561. "excellon_editor_sel_limit": 30,
  562. "excellon_editor_newdia": 1.0,
  563. "excellon_editor_array_size": 5,
  564. "excellon_editor_lin_dir": 'X',
  565. "excellon_editor_lin_pitch": 2.54,
  566. "excellon_editor_lin_angle": 0.0,
  567. "excellon_editor_circ_dir": 'CW',
  568. "excellon_editor_circ_angle": 12,
  569. # Excellon Slots
  570. "excellon_editor_slot_direction": 'X',
  571. "excellon_editor_slot_angle": 0.0,
  572. "excellon_editor_slot_length": 5.0,
  573. # Excellon Slot Array
  574. "excellon_editor_slot_array_size": 5,
  575. "excellon_editor_slot_lin_dir": 'X',
  576. "excellon_editor_slot_lin_pitch": 2.54,
  577. "excellon_editor_slot_lin_angle": 0.0,
  578. "excellon_editor_slot_circ_dir": 'CW',
  579. "excellon_editor_slot_circ_angle": 0.0,
  580. # Geometry General
  581. "geometry_plot": True,
  582. "geometry_circle_steps": 64,
  583. "geometry_cnctooldia": "2.4",
  584. "geometry_plot_line": "#FF0000",
  585. # Geometry Options
  586. "geometry_cutz": -2.4,
  587. "geometry_vtipdia": 0.1,
  588. "geometry_vtipangle": 30,
  589. "geometry_multidepth": False,
  590. "geometry_depthperpass": 0.8,
  591. "geometry_travelz": 2,
  592. "geometry_toolchange": False,
  593. "geometry_toolchangez": 15.0,
  594. "geometry_endz": 15.0,
  595. "geometry_feedrate": 120,
  596. "geometry_feedrate_z": 60,
  597. "geometry_spindlespeed": 0,
  598. "geometry_dwell": False,
  599. "geometry_dwelltime": 1,
  600. "geometry_ppname_g": 'default',
  601. # Geometry Advanced Options
  602. "geometry_toolchangexy": "0.0, 0.0",
  603. "geometry_startz": None,
  604. "geometry_feedrate_rapid": 1500,
  605. "geometry_extracut": False,
  606. "geometry_extracut_length": 0.1,
  607. "geometry_z_pdepth": -0.02,
  608. "geometry_f_plunge": False,
  609. "geometry_spindledir": 'CW',
  610. "geometry_feedrate_probe": 75,
  611. "geometry_segx": 0.0,
  612. "geometry_segy": 0.0,
  613. # Geometry Editor
  614. "geometry_editor_sel_limit": 30,
  615. "geometry_editor_milling_type": "cl",
  616. # CNC Job General
  617. "cncjob_plot": True,
  618. "cncjob_plot_kind": 'all',
  619. "cncjob_annotation": True,
  620. "cncjob_tooldia": 1.0,
  621. "cncjob_coords_type": "G90",
  622. "cncjob_coords_decimals": 4,
  623. "cncjob_fr_decimals": 2,
  624. "cncjob_steps_per_circle": 64,
  625. "cncjob_footer": False,
  626. "cncjob_line_ending": False,
  627. "cncjob_save_filters": "G-Code Files (*.nc);;G-Code Files (*.din);;G-Code Files (*.dnc);;"
  628. "G-Code Files (*.ecs);;G-Code Files (*.eia);;G-Code Files (*.fan);;"
  629. "G-Code Files (*.fgc);;G-Code Files (*.fnc);;G-Code Files (*.gc);;"
  630. "G-Code Files (*.gcd);;G-Code Files (*.gcode);;G-Code Files (*.h);;"
  631. "G-Code Files (*.hnc);;G-Code Files (*.i);;G-Code Files (*.min);;"
  632. "G-Code Files (*.mpf);;G-Code Files (*.mpr);;G-Code Files (*.cnc);;"
  633. "G-Code Files (*.ncc);;G-Code Files (*.ncg);;G-Code Files (*.ncp);;"
  634. "G-Code Files (*.ngc);;G-Code Files (*.out);;G-Code Files (*.ply);;"
  635. "G-Code Files (*.sbp);;G-Code Files (*.tap);;G-Code Files (*.xpi);;"
  636. "All Files (*.*)",
  637. "cncjob_plot_line": '#4650BDFF',
  638. "cncjob_plot_fill": '#5E6CFFFF',
  639. "cncjob_travel_line": '#B5AB3A4C',
  640. "cncjob_travel_fill": '#F0E24D4C',
  641. # CNC Job Options
  642. "cncjob_prepend": "",
  643. "cncjob_append": "",
  644. # CNC Job Advanced Options
  645. "cncjob_toolchange_macro": "",
  646. "cncjob_toolchange_macro_enable": False,
  647. "cncjob_annotation_fontsize": 9,
  648. "cncjob_annotation_fontcolor": '#990000',
  649. # NCC Tool
  650. "tools_ncctools": "1.0, 0.5",
  651. "tools_nccorder": 'rev',
  652. "tools_nccoverlap": 40,
  653. "tools_nccmargin": 1.0,
  654. "tools_nccmethod": "seed",
  655. "tools_nccconnect": True,
  656. "tools_ncccontour": True,
  657. "tools_nccrest": False,
  658. "tools_ncc_offset_choice": False,
  659. "tools_ncc_offset_value": 0.0000,
  660. "tools_nccref": 'itself',
  661. "tools_ncc_plotting": 'normal',
  662. "tools_nccmilling_type": 'cl',
  663. "tools_ncctool_type": 'C1',
  664. "tools_ncccutz": -0.05,
  665. "tools_ncctipdia": 0.1,
  666. "tools_ncctipangle": 30,
  667. "tools_nccnewdia": 0.1,
  668. # Cutout Tool
  669. "tools_cutouttooldia": 2.4,
  670. "tools_cutoutkind": "single",
  671. "tools_cutoutmargin": 0.1,
  672. "tools_cutout_z": -1.8,
  673. "tools_cutout_depthperpass": 0.6,
  674. "tools_cutout_mdepth": True,
  675. "tools_cutoutgapsize": 4,
  676. "tools_gaps_ff": "4",
  677. "tools_cutout_convexshape": False,
  678. # Paint Tool
  679. "tools_painttooldia": 0.3,
  680. "tools_paintorder": 'rev',
  681. "tools_paintoverlap": 20,
  682. "tools_paintmargin": 0.0,
  683. "tools_paintmethod": "seed",
  684. "tools_selectmethod": "all",
  685. "tools_pathconnect": True,
  686. "tools_paintcontour": True,
  687. "tools_paint_plotting": 'normal',
  688. "tools_paintrest": False,
  689. "tools_painttool_type": 'C1',
  690. "tools_paintcutz": -0.05,
  691. "tools_painttipdia": 0.1,
  692. "tools_painttipangle": 30,
  693. "tools_paintnewdia": 0.1,
  694. # 2-Sided Tool
  695. "tools_2sided_mirror_axis": "X",
  696. "tools_2sided_axis_loc": "point",
  697. "tools_2sided_drilldia": 3.125,
  698. "tools_2sided_allign_axis": "X",
  699. # Film Tool
  700. "tools_film_type": 'neg',
  701. "tools_film_boundary": 1.0,
  702. "tools_film_scale_stroke": 0,
  703. "tools_film_color": '#000000',
  704. "tools_film_scale_cb": False,
  705. "tools_film_scale_x_entry": 1.0,
  706. "tools_film_scale_y_entry": 1.0,
  707. "tools_film_skew_cb": False,
  708. "tools_film_skew_x_entry": 0.0,
  709. "tools_film_skew_y_entry": 0.0,
  710. "tools_film_skew_ref_radio": 'bottomleft',
  711. "tools_film_mirror_cb": False,
  712. "tools_film_mirror_axis_radio": 'none',
  713. "tools_film_file_type_radio": 'svg',
  714. "tools_film_orientation": 'p',
  715. "tools_film_pagesize": 'A4',
  716. # Panel Tool
  717. "tools_panelize_spacing_columns": 0,
  718. "tools_panelize_spacing_rows": 0,
  719. "tools_panelize_columns": 1,
  720. "tools_panelize_rows": 1,
  721. "tools_panelize_constrain": False,
  722. "tools_panelize_constrainx": 200.0,
  723. "tools_panelize_constrainy": 290.0,
  724. "tools_panelize_panel_type": 'gerber',
  725. # Calculators Tool
  726. "tools_calc_vshape_tip_dia": 0.2,
  727. "tools_calc_vshape_tip_angle": 30,
  728. "tools_calc_vshape_cut_z": 0.05,
  729. "tools_calc_electro_length": 10.0,
  730. "tools_calc_electro_width": 10.0,
  731. "tools_calc_electro_cdensity": 13.0,
  732. "tools_calc_electro_growth": 10.0,
  733. # Transform Tool
  734. "tools_transform_rotate": 90,
  735. "tools_transform_skew_x": 0.0,
  736. "tools_transform_skew_y": 0.0,
  737. "tools_transform_scale_x": 1.0,
  738. "tools_transform_scale_y": 1.0,
  739. "tools_transform_scale_link": True,
  740. "tools_transform_scale_reference": True,
  741. "tools_transform_offset_x": 0.0,
  742. "tools_transform_offset_y": 0.0,
  743. "tools_transform_mirror_reference": False,
  744. "tools_transform_mirror_point": (0, 0),
  745. "tools_transform_buffer_dis": 0.0,
  746. "tools_transform_buffer_factor": 100.0,
  747. "tools_transform_buffer_corner": True,
  748. # SolderPaste Tool
  749. "tools_solderpaste_tools": "1.0, 0.3",
  750. "tools_solderpaste_new": 0.3,
  751. "tools_solderpaste_z_start": 0.05,
  752. "tools_solderpaste_z_dispense": 0.1,
  753. "tools_solderpaste_z_stop": 0.05,
  754. "tools_solderpaste_z_travel": 0.1,
  755. "tools_solderpaste_z_toolchange": 1.0,
  756. "tools_solderpaste_xy_toolchange": "0.0, 0.0",
  757. "tools_solderpaste_frxy": 150,
  758. "tools_solderpaste_frz": 150,
  759. "tools_solderpaste_frz_dispense": 1.0,
  760. "tools_solderpaste_speedfwd": 300,
  761. "tools_solderpaste_dwellfwd": 1,
  762. "tools_solderpaste_speedrev": 200,
  763. "tools_solderpaste_dwellrev": 1,
  764. "tools_solderpaste_pp": 'Paste_1',
  765. # Subtract Tool
  766. "tools_sub_close_paths": True,
  767. # ###################################################################################
  768. # ################################ TOOLS 2 ##########################################
  769. # ###################################################################################
  770. # Optimal Tool
  771. "tools_opt_precision": 4,
  772. # Check Rules Tool
  773. "tools_cr_trace_size": True,
  774. "tools_cr_trace_size_val": 0.25,
  775. "tools_cr_c2c": True,
  776. "tools_cr_c2c_val": 0.25,
  777. "tools_cr_c2o": True,
  778. "tools_cr_c2o_val": 1.0,
  779. "tools_cr_s2s": True,
  780. "tools_cr_s2s_val": 0.25,
  781. "tools_cr_s2sm": True,
  782. "tools_cr_s2sm_val": 0.25,
  783. "tools_cr_s2o": True,
  784. "tools_cr_s2o_val": 1.0,
  785. "tools_cr_sm2sm": True,
  786. "tools_cr_sm2sm_val": 0.25,
  787. "tools_cr_ri": True,
  788. "tools_cr_ri_val": 0.3,
  789. "tools_cr_h2h": True,
  790. "tools_cr_h2h_val": 0.3,
  791. "tools_cr_dh": True,
  792. "tools_cr_dh_val": 0.3,
  793. # QRCode Tool
  794. "tools_qrcode_version": 1,
  795. "tools_qrcode_error": 'L',
  796. "tools_qrcode_box_size": 3,
  797. "tools_qrcode_border_size": 4,
  798. "tools_qrcode_qrdata": '',
  799. "tools_qrcode_polarity": 'pos',
  800. "tools_qrcode_rounded": 's',
  801. "tools_qrcode_fill_color": '#000000',
  802. "tools_qrcode_back_color": '#FFFFFF',
  803. "tools_qrcode_sel_limit": 330,
  804. # Copper Thieving Tool
  805. "tools_copper_thieving_clearance": 0.25,
  806. "tools_copper_thieving_margin": 1.0,
  807. "tools_copper_thieving_reference": 'itself',
  808. "tools_copper_thieving_box_type": 'rect',
  809. "tools_copper_thieving_circle_steps": 64,
  810. "tools_copper_thieving_fill_type": 'solid',
  811. "tools_copper_thieving_dots_dia": 1.0,
  812. "tools_copper_thieving_dots_spacing": 2.0,
  813. "tools_copper_thieving_squares_size": 1.0,
  814. "tools_copper_thieving_squares_spacing": 2.0,
  815. "tools_copper_thieving_lines_size": 0.25,
  816. "tools_copper_thieving_lines_spacing": 2.0,
  817. "tools_copper_thieving_rb_margin": 1.0,
  818. "tools_copper_thieving_rb_thickness": 1.0,
  819. "tools_copper_thieving_mask_clearance": 0.0,
  820. # Fiducials Tool
  821. "tools_fiducials_dia": 1.0,
  822. "tools_fiducials_margin": 1.0,
  823. "tools_fiducials_mode": 'auto',
  824. "tools_fiducials_second_pos": 'up',
  825. "tools_fiducials_type": 'circular',
  826. "tools_fiducials_line_thickness": 0.25,
  827. # Calibration Tool
  828. "tools_cal_calsource": 'object',
  829. "tools_cal_travelz": 2.0,
  830. "tools_cal_verz": 0.1,
  831. "tools_cal_zeroz": False,
  832. "tools_cal_toolchangez": 15,
  833. "tools_cal_toolchange_xy": '',
  834. "tools_cal_sec_point": 'tl',
  835. # Drills Extraction Tool
  836. "tools_edrills_hole_type": 'fixed',
  837. "tools_edrills_hole_fixed_dia": 0.5,
  838. "tools_edrills_hole_prop_factor": 80.0,
  839. "tools_edrills_circular_ring": 0.2,
  840. "tools_edrills_oblong_ring": 0.2,
  841. "tools_edrills_square_ring": 0.2,
  842. "tools_edrills_rectangular_ring": 0.2,
  843. "tools_edrills_others_ring": 0.2,
  844. "tools_edrills_circular": True,
  845. "tools_edrills_oblong": False,
  846. "tools_edrills_square": False,
  847. "tools_edrills_rectangular": False,
  848. "tools_edrills_others": False,
  849. # Align Objects Tool
  850. "tools_align_objects_align_type": 'sp',
  851. # Utilities
  852. # file associations
  853. "fa_excellon": 'drd, drl, exc, ncd, tap, xln',
  854. "fa_gcode": 'cnc, din, dnc, ecs, eia, fan, fgc, fnc, gc, gcd, gcode, h, hnc, i, min, mpf, mpr, nc, ncc, '
  855. 'ncg, ncp, ngc, out, ply, rol, sbp, tap, xpi',
  856. "fa_gerber": 'art, bot, bsm, cmp, crc, crs, dim, gb0, gb1, gb2, gb3, gb4, gb5, gb6, gb7, gb8, gb9, gbd, '
  857. 'gbl, gbo, gbp, gbr, gbs, gdo, ger, gko, gm1, gm2, gm3, grb, gtl, gto, gtp, gts, ly15, ly2, '
  858. 'mil, pho, plc, pls, smb, smt, sol, spb, spt, ssb, sst, stc, sts, top, tsm',
  859. # Keyword list
  860. "util_autocomplete_keywords": 'Desktop, Documents, FlatConfig, FlatPrj, Marius, My Documents, Paste_1, '
  861. 'Repetier, Roland_MDX_20, Users, Toolchange_Custom, Toolchange_Probe_MACH3, '
  862. 'Toolchange_manual, Users, all, angle_x, angle_y, axis, auto, axisoffset, '
  863. 'box, center_x, center_y, columns, combine, connect, contour, default, '
  864. 'depthperpass, dia, diatol, dist, drilled_dias, drillz, dwelltime, '
  865. 'extracut_length, '
  866. 'feedrate_z, grbl_11, grbl_laser, gridoffsety, gridx, gridy, has_offset, '
  867. 'holes, hpgl, iso_type, line_xyz, margin, marlin, method, milled_dias, '
  868. 'minoffset, name, offset, opt_type, order, outname, overlap, '
  869. 'passes, postamble, pp, ppname_e, ppname_g, preamble, radius, ref, rest, '
  870. 'rows, shellvar_, scale_factor, spacing_columns, spacing_rows, spindlespeed, '
  871. 'toolchange_xy, toolchangez, '
  872. 'tooldia, use_threads, value, x, x0, x1, y, y0, y1, z_cut, '
  873. 'z_move',
  874. "script_autocompleter": True,
  875. "script_text": "",
  876. "script_plot": True,
  877. "script_source_file": "",
  878. "document_autocompleter": False,
  879. "document_text": "",
  880. "document_plot": True,
  881. "document_source_file": "",
  882. "document_font_color": '#000000',
  883. "document_sel_color": '#0055ff',
  884. "document_font_size": 6,
  885. "document_tab_size": 80,
  886. })
  887. # ############################################################
  888. # ############### Load defaults from file ####################
  889. # ############################################################
  890. self.old_defaults_found = False
  891. if user_defaults:
  892. self.load_defaults(filename='current_defaults')
  893. if self.defaults['units'] == 'MM':
  894. self.decimals = int(self.defaults['decimals_metric'])
  895. else:
  896. self.decimals = int(self.defaults['decimals_inch'])
  897. if self.defaults["global_gray_icons"] is False:
  898. self.resource_location = 'share'
  899. else:
  900. self.resource_location = 'share/dark_resources'
  901. self.current_units = self.defaults['units']
  902. # store here the current self.defaults so it can be restored if Preferences changes are cancelled
  903. self.current_defaults = dict()
  904. self.current_defaults.update(self.defaults)
  905. # ##########################################################################
  906. # ##################### SETUP OBJECT CLASSES ###############################
  907. # ##########################################################################
  908. self.setup_obj_classes()
  909. # ##########################################################################
  910. # ##################### CREATE MULTIPROCESSING POOL ########################
  911. # ##########################################################################
  912. self.pool = Pool()
  913. # ##########################################################################
  914. # ################## Setting the Splash Screen #############################
  915. # ##########################################################################
  916. splash_settings = QSettings("Open Source", "FlatCAM")
  917. if splash_settings.contains("splash_screen"):
  918. show_splash = splash_settings.value("splash_screen")
  919. else:
  920. splash_settings.setValue('splash_screen', 1)
  921. # This will write the setting to the platform specific storage.
  922. del splash_settings
  923. show_splash = 1
  924. if show_splash and self.cmd_line_headless != 1:
  925. splash_pix = QtGui.QPixmap(self.resource_location + '/splash.png')
  926. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  927. # self.splash.setMask(splash_pix.mask())
  928. # move splashscreen to the current monitor
  929. desktop = QtWidgets.QApplication.desktop()
  930. screen = desktop.screenNumber(QtGui.QCursor.pos())
  931. current_screen_center = desktop.availableGeometry(screen).center()
  932. self.splash.move(current_screen_center - self.splash.rect().center())
  933. self.splash.show()
  934. self.splash.showMessage(_("FlatCAM is initializing ..."),
  935. alignment=Qt.AlignBottom | Qt.AlignLeft,
  936. color=QtGui.QColor("gray"))
  937. else:
  938. show_splash = 0
  939. # #############################################################################
  940. # ##################### Initialize GUI ########################################
  941. # #############################################################################
  942. # FlatCAM colors used in plotting
  943. self.FC_light_green = '#BBF268BF'
  944. self.FC_dark_green = '#006E20BF'
  945. self.FC_light_blue = '#a5a5ffbf'
  946. self.FC_dark_blue = '#0000ffbf'
  947. QtCore.QObject.__init__(self)
  948. self.ui = FlatCAMGUI(self)
  949. self.on_grid_snap_triggered(state=True)
  950. theme_settings = QtCore.QSettings("Open Source", "FlatCAM")
  951. if theme_settings.contains("theme"):
  952. theme = theme_settings.value('theme', type=str)
  953. else:
  954. theme = 'white'
  955. if self.defaults["global_cursor_color_enabled"]:
  956. self.cursor_color_3D = self.defaults["global_cursor_color"]
  957. else:
  958. if theme == 'white':
  959. self.cursor_color_3D = 'black'
  960. else:
  961. self.cursor_color_3D = 'gray'
  962. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  963. self.ui.final_save.connect(self.final_save)
  964. # restore the toolbar view
  965. self.restore_toolbar_view()
  966. # restore the GUI geometry
  967. self.restore_main_win_geom()
  968. # set FlatCAM units in the Status bar
  969. self.set_screen_units(self.defaults['units'])
  970. # #############################################################################
  971. # ######################## UPDATE PREFERENCES GUI FORMS #######################
  972. # #############################################################################
  973. # when adding entries here read the comments in the method found bellow named:
  974. # def new_object(self, kind, name, initialize, active=True, fit=True, plot=True)
  975. self.defaults_form_fields = {
  976. # General App
  977. "decimals_inch": self.ui.general_defaults_form.general_app_group.precision_inch_entry,
  978. "decimals_metric": self.ui.general_defaults_form.general_app_group.precision_metric_entry,
  979. "units": self.ui.general_defaults_form.general_app_group.units_radio,
  980. "global_graphic_engine": self.ui.general_defaults_form.general_app_group.ge_radio,
  981. "global_app_level": self.ui.general_defaults_form.general_app_group.app_level_radio,
  982. "global_portable": self.ui.general_defaults_form.general_app_group.portability_cb,
  983. "global_language": self.ui.general_defaults_form.general_app_group.language_cb,
  984. "global_systray_icon": self.ui.general_defaults_form.general_app_group.systray_cb,
  985. "global_shell_at_startup": self.ui.general_defaults_form.general_app_group.shell_startup_cb,
  986. "global_project_at_startup": self.ui.general_defaults_form.general_app_group.project_startup_cb,
  987. "global_version_check": self.ui.general_defaults_form.general_app_group.version_check_cb,
  988. "global_send_stats": self.ui.general_defaults_form.general_app_group.send_stats_cb,
  989. "global_worker_number": self.ui.general_defaults_form.general_app_group.worker_number_sb,
  990. "global_tolerance": self.ui.general_defaults_form.general_app_group.tol_entry,
  991. "global_compression_level": self.ui.general_defaults_form.general_app_group.compress_spinner,
  992. "global_save_compressed": self.ui.general_defaults_form.general_app_group.save_type_cb,
  993. "global_tpdf_tmargin": self.ui.general_defaults_form.general_app_group.tmargin_entry,
  994. "global_tpdf_bmargin": self.ui.general_defaults_form.general_app_group.bmargin_entry,
  995. "global_tpdf_lmargin": self.ui.general_defaults_form.general_app_group.lmargin_entry,
  996. "global_tpdf_rmargin": self.ui.general_defaults_form.general_app_group.rmargin_entry,
  997. # General GUI Preferences
  998. "global_theme": self.ui.general_defaults_form.general_gui_group.theme_radio,
  999. "global_gray_icons": self.ui.general_defaults_form.general_gui_group.gray_icons_cb,
  1000. "global_layout": self.ui.general_defaults_form.general_gui_group.layout_combo,
  1001. "global_hover": self.ui.general_defaults_form.general_gui_group.hover_cb,
  1002. "global_selection_shape": self.ui.general_defaults_form.general_gui_group.selection_cb,
  1003. "global_sel_fill": self.ui.general_defaults_form.general_gui_group.sf_color_entry,
  1004. "global_sel_line": self.ui.general_defaults_form.general_gui_group.sl_color_entry,
  1005. "global_alt_sel_fill": self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry,
  1006. "global_alt_sel_line": self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry,
  1007. "global_draw_color": self.ui.general_defaults_form.general_gui_group.draw_color_entry,
  1008. "global_sel_draw_color": self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry,
  1009. "global_proj_item_color": self.ui.general_defaults_form.general_gui_group.proj_color_entry,
  1010. "global_proj_item_dis_color": self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry,
  1011. "global_project_autohide": self.ui.general_defaults_form.general_gui_group.project_autohide_cb,
  1012. # General GUI Settings
  1013. "global_gridx": self.ui.general_defaults_form.general_app_set_group.gridx_entry,
  1014. "global_gridy": self.ui.general_defaults_form.general_app_set_group.gridy_entry,
  1015. "global_snap_max": self.ui.general_defaults_form.general_app_set_group.snap_max_dist_entry,
  1016. "global_workspace": self.ui.general_defaults_form.general_app_set_group.workspace_cb,
  1017. "global_workspaceT": self.ui.general_defaults_form.general_app_set_group.wk_cb,
  1018. "global_workspace_orientation": self.ui.general_defaults_form.general_app_set_group.wk_orientation_radio,
  1019. "global_cursor_type": self.ui.general_defaults_form.general_app_set_group.cursor_radio,
  1020. "global_cursor_size": self.ui.general_defaults_form.general_app_set_group.cursor_size_entry,
  1021. "global_cursor_width": self.ui.general_defaults_form.general_app_set_group.cursor_width_entry,
  1022. "global_cursor_color_enabled": self.ui.general_defaults_form.general_app_set_group.mouse_cursor_color_cb,
  1023. "global_cursor_color": self.ui.general_defaults_form.general_app_set_group.mouse_cursor_entry,
  1024. "global_pan_button": self.ui.general_defaults_form.general_app_set_group.pan_button_radio,
  1025. "global_mselect_key": self.ui.general_defaults_form.general_app_set_group.mselect_radio,
  1026. "global_delete_confirmation": self.ui.general_defaults_form.general_app_set_group.delete_conf_cb,
  1027. "global_open_style": self.ui.general_defaults_form.general_app_set_group.open_style_cb,
  1028. "global_toggle_tooltips": self.ui.general_defaults_form.general_app_set_group.toggle_tooltips_cb,
  1029. "global_machinist_setting": self.ui.general_defaults_form.general_app_set_group.machinist_cb,
  1030. "global_bookmarks_limit": self.ui.general_defaults_form.general_app_set_group.bm_limit_spinner,
  1031. "global_activity_icon": self.ui.general_defaults_form.general_app_set_group.activity_combo,
  1032. # Gerber General
  1033. "gerber_plot": self.ui.gerber_defaults_form.gerber_gen_group.plot_cb,
  1034. "gerber_solid": self.ui.gerber_defaults_form.gerber_gen_group.solid_cb,
  1035. "gerber_multicolored": self.ui.gerber_defaults_form.gerber_gen_group.multicolored_cb,
  1036. "gerber_circle_steps": self.ui.gerber_defaults_form.gerber_gen_group.circle_steps_entry,
  1037. "gerber_def_units": self.ui.gerber_defaults_form.gerber_gen_group.gerber_units_radio,
  1038. "gerber_def_zeros": self.ui.gerber_defaults_form.gerber_gen_group.gerber_zeros_radio,
  1039. "gerber_clean_apertures": self.ui.gerber_defaults_form.gerber_gen_group.gerber_clean_cb,
  1040. "gerber_extra_buffering": self.ui.gerber_defaults_form.gerber_gen_group.gerber_extra_buffering,
  1041. "gerber_plot_fill": self.ui.gerber_defaults_form.gerber_gen_group.pf_color_entry,
  1042. "gerber_plot_line": self.ui.gerber_defaults_form.gerber_gen_group.pl_color_entry,
  1043. # Gerber Options
  1044. "gerber_isotooldia": self.ui.gerber_defaults_form.gerber_opt_group.iso_tool_dia_entry,
  1045. "gerber_isopasses": self.ui.gerber_defaults_form.gerber_opt_group.iso_width_entry,
  1046. "gerber_isooverlap": self.ui.gerber_defaults_form.gerber_opt_group.iso_overlap_entry,
  1047. "gerber_combine_passes": self.ui.gerber_defaults_form.gerber_opt_group.combine_passes_cb,
  1048. "gerber_iso_scope": self.ui.gerber_defaults_form.gerber_opt_group.iso_scope_radio,
  1049. "gerber_milling_type": self.ui.gerber_defaults_form.gerber_opt_group.milling_type_radio,
  1050. "gerber_noncoppermargin": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_margin_entry,
  1051. "gerber_noncopperrounded": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_rounded_cb,
  1052. "gerber_bboxmargin": self.ui.gerber_defaults_form.gerber_opt_group.bbmargin_entry,
  1053. "gerber_bboxrounded": self.ui.gerber_defaults_form.gerber_opt_group.bbrounded_cb,
  1054. # Gerber Advanced Options
  1055. "gerber_aperture_display": self.ui.gerber_defaults_form.gerber_adv_opt_group.aperture_table_visibility_cb,
  1056. # "gerber_aperture_scale_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.scale_aperture_entry,
  1057. # "gerber_aperture_buffer_factor": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffer_aperture_entry,
  1058. "gerber_follow": self.ui.gerber_defaults_form.gerber_adv_opt_group.follow_cb,
  1059. "gerber_tool_type": self.ui.gerber_defaults_form.gerber_adv_opt_group.tool_type_radio,
  1060. "gerber_vtipdia": self.ui.gerber_defaults_form.gerber_adv_opt_group.tipdia_spinner,
  1061. "gerber_vtipangle": self.ui.gerber_defaults_form.gerber_adv_opt_group.tipangle_spinner,
  1062. "gerber_vcutz": self.ui.gerber_defaults_form.gerber_adv_opt_group.cutz_spinner,
  1063. "gerber_iso_type": self.ui.gerber_defaults_form.gerber_adv_opt_group.iso_type_radio,
  1064. "gerber_buffering": self.ui.gerber_defaults_form.gerber_adv_opt_group.buffering_radio,
  1065. "gerber_simplification": self.ui.gerber_defaults_form.gerber_adv_opt_group.simplify_cb,
  1066. "gerber_simp_tolerance": self.ui.gerber_defaults_form.gerber_adv_opt_group.simplification_tol_spinner,
  1067. # Gerber Export
  1068. "gerber_exp_units": self.ui.gerber_defaults_form.gerber_exp_group.gerber_units_radio,
  1069. "gerber_exp_integer": self.ui.gerber_defaults_form.gerber_exp_group.format_whole_entry,
  1070. "gerber_exp_decimals": self.ui.gerber_defaults_form.gerber_exp_group.format_dec_entry,
  1071. "gerber_exp_zeros": self.ui.gerber_defaults_form.gerber_exp_group.zeros_radio,
  1072. # Gerber Editor
  1073. "gerber_editor_sel_limit": self.ui.gerber_defaults_form.gerber_editor_group.sel_limit_entry,
  1074. "gerber_editor_newcode": self.ui.gerber_defaults_form.gerber_editor_group.addcode_entry,
  1075. "gerber_editor_newsize": self.ui.gerber_defaults_form.gerber_editor_group.addsize_entry,
  1076. "gerber_editor_newtype": self.ui.gerber_defaults_form.gerber_editor_group.addtype_combo,
  1077. "gerber_editor_newdim": self.ui.gerber_defaults_form.gerber_editor_group.adddim_entry,
  1078. "gerber_editor_array_size": self.ui.gerber_defaults_form.gerber_editor_group.grb_array_size_entry,
  1079. "gerber_editor_lin_axis": self.ui.gerber_defaults_form.gerber_editor_group.grb_axis_radio,
  1080. "gerber_editor_lin_pitch": self.ui.gerber_defaults_form.gerber_editor_group.grb_pitch_entry,
  1081. "gerber_editor_lin_angle": self.ui.gerber_defaults_form.gerber_editor_group.grb_angle_entry,
  1082. "gerber_editor_circ_dir": self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_dir_radio,
  1083. "gerber_editor_circ_angle":
  1084. self.ui.gerber_defaults_form.gerber_editor_group.grb_circular_angle_entry,
  1085. "gerber_editor_scale_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_scale_entry,
  1086. "gerber_editor_buff_f": self.ui.gerber_defaults_form.gerber_editor_group.grb_buff_entry,
  1087. "gerber_editor_ma_low": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_low_entry,
  1088. "gerber_editor_ma_high": self.ui.gerber_defaults_form.gerber_editor_group.grb_ma_high_entry,
  1089. # Excellon General
  1090. "excellon_plot": self.ui.excellon_defaults_form.excellon_gen_group.plot_cb,
  1091. "excellon_solid": self.ui.excellon_defaults_form.excellon_gen_group.solid_cb,
  1092. "excellon_format_upper_in":
  1093. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry,
  1094. "excellon_format_lower_in":
  1095. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry,
  1096. "excellon_format_upper_mm":
  1097. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry,
  1098. "excellon_format_lower_mm":
  1099. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry,
  1100. "excellon_zeros": self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio,
  1101. "excellon_units": self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio,
  1102. "excellon_update": self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb,
  1103. "excellon_optimization_type": self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio,
  1104. "excellon_search_time": self.ui.excellon_defaults_form.excellon_gen_group.optimization_time_entry,
  1105. "excellon_plot_fill": self.ui.excellon_defaults_form.excellon_gen_group.fill_color_entry,
  1106. "excellon_plot_line": self.ui.excellon_defaults_form.excellon_gen_group.line_color_entry,
  1107. # Excellon Options
  1108. "excellon_drillz": self.ui.excellon_defaults_form.excellon_opt_group.cutz_entry,
  1109. "excellon_travelz": self.ui.excellon_defaults_form.excellon_opt_group.travelz_entry,
  1110. "excellon_endz": self.ui.excellon_defaults_form.excellon_opt_group.eendz_entry,
  1111. "excellon_feedrate": self.ui.excellon_defaults_form.excellon_opt_group.feedrate_entry,
  1112. "excellon_spindlespeed": self.ui.excellon_defaults_form.excellon_opt_group.spindlespeed_entry,
  1113. "excellon_dwell": self.ui.excellon_defaults_form.excellon_opt_group.dwell_cb,
  1114. "excellon_dwelltime": self.ui.excellon_defaults_form.excellon_opt_group.dwelltime_entry,
  1115. "excellon_toolchange": self.ui.excellon_defaults_form.excellon_opt_group.toolchange_cb,
  1116. "excellon_toolchangez": self.ui.excellon_defaults_form.excellon_opt_group.toolchangez_entry,
  1117. "excellon_ppname_e": self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb,
  1118. "excellon_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.tooldia_entry,
  1119. "excellon_slot_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.slot_tooldia_entry,
  1120. "excellon_gcode_type": self.ui.excellon_defaults_form.excellon_opt_group.excellon_gcode_type_radio,
  1121. # Excellon Advanced Options
  1122. "excellon_offset": self.ui.excellon_defaults_form.excellon_adv_opt_group.offset_entry,
  1123. "excellon_toolchangexy": self.ui.excellon_defaults_form.excellon_adv_opt_group.toolchangexy_entry,
  1124. "excellon_startz": self.ui.excellon_defaults_form.excellon_adv_opt_group.estartz_entry,
  1125. "excellon_feedrate_rapid": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_rapid_entry,
  1126. "excellon_z_pdepth": self.ui.excellon_defaults_form.excellon_adv_opt_group.pdepth_entry,
  1127. "excellon_feedrate_probe": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_probe_entry,
  1128. "excellon_spindledir": self.ui.excellon_defaults_form.excellon_adv_opt_group.spindledir_radio,
  1129. "excellon_f_plunge": self.ui.excellon_defaults_form.excellon_adv_opt_group.fplunge_cb,
  1130. "excellon_f_retract": self.ui.excellon_defaults_form.excellon_adv_opt_group.fretract_cb,
  1131. # Excellon Export
  1132. "excellon_exp_units": self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio,
  1133. "excellon_exp_format": self.ui.excellon_defaults_form.excellon_exp_group.format_radio,
  1134. "excellon_exp_integer": self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry,
  1135. "excellon_exp_decimals": self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry,
  1136. "excellon_exp_zeros": self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio,
  1137. "excellon_exp_slot_type": self.ui.excellon_defaults_form.excellon_exp_group.slot_type_radio,
  1138. # Excellon Editor
  1139. "excellon_editor_sel_limit": self.ui.excellon_defaults_form.excellon_editor_group.sel_limit_entry,
  1140. "excellon_editor_newdia": self.ui.excellon_defaults_form.excellon_editor_group.addtool_entry,
  1141. "excellon_editor_array_size": self.ui.excellon_defaults_form.excellon_editor_group.drill_array_size_entry,
  1142. "excellon_editor_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_axis_radio,
  1143. "excellon_editor_lin_pitch": self.ui.excellon_defaults_form.excellon_editor_group.drill_pitch_entry,
  1144. "excellon_editor_lin_angle": self.ui.excellon_defaults_form.excellon_editor_group.drill_angle_entry,
  1145. "excellon_editor_circ_dir": self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_dir_radio,
  1146. "excellon_editor_circ_angle":
  1147. self.ui.excellon_defaults_form.excellon_editor_group.drill_circular_angle_entry,
  1148. # Excellon Slots
  1149. "excellon_editor_slot_direction":
  1150. self.ui.excellon_defaults_form.excellon_editor_group.slot_axis_radio,
  1151. "excellon_editor_slot_angle":
  1152. self.ui.excellon_defaults_form.excellon_editor_group.slot_angle_spinner,
  1153. "excellon_editor_slot_length":
  1154. self.ui.excellon_defaults_form.excellon_editor_group.slot_length_entry,
  1155. # Excellon Slots
  1156. "excellon_editor_slot_array_size":
  1157. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_size_entry,
  1158. "excellon_editor_slot_lin_dir": self.ui.excellon_defaults_form.excellon_editor_group.slot_array_axis_radio,
  1159. "excellon_editor_slot_lin_pitch":
  1160. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_pitch_entry,
  1161. "excellon_editor_slot_lin_angle":
  1162. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_angle_entry,
  1163. "excellon_editor_slot_circ_dir":
  1164. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_dir_radio,
  1165. "excellon_editor_slot_circ_angle":
  1166. self.ui.excellon_defaults_form.excellon_editor_group.slot_array_circular_angle_entry,
  1167. # Geometry General
  1168. "geometry_plot": self.ui.geometry_defaults_form.geometry_gen_group.plot_cb,
  1169. "geometry_circle_steps": self.ui.geometry_defaults_form.geometry_gen_group.circle_steps_entry,
  1170. "geometry_cnctooldia": self.ui.geometry_defaults_form.geometry_gen_group.cnctooldia_entry,
  1171. "geometry_plot_line": self.ui.geometry_defaults_form.geometry_gen_group.line_color_entry,
  1172. # Geometry Options
  1173. "geometry_cutz": self.ui.geometry_defaults_form.geometry_opt_group.cutz_entry,
  1174. "geometry_travelz": self.ui.geometry_defaults_form.geometry_opt_group.travelz_entry,
  1175. "geometry_feedrate": self.ui.geometry_defaults_form.geometry_opt_group.cncfeedrate_entry,
  1176. "geometry_feedrate_z": self.ui.geometry_defaults_form.geometry_opt_group.cncplunge_entry,
  1177. "geometry_spindlespeed": self.ui.geometry_defaults_form.geometry_opt_group.cncspindlespeed_entry,
  1178. "geometry_dwell": self.ui.geometry_defaults_form.geometry_opt_group.dwell_cb,
  1179. "geometry_dwelltime": self.ui.geometry_defaults_form.geometry_opt_group.dwelltime_entry,
  1180. "geometry_ppname_g": self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb,
  1181. "geometry_toolchange": self.ui.geometry_defaults_form.geometry_opt_group.toolchange_cb,
  1182. "geometry_toolchangez": self.ui.geometry_defaults_form.geometry_opt_group.toolchangez_entry,
  1183. "geometry_endz": self.ui.geometry_defaults_form.geometry_opt_group.gendz_entry,
  1184. "geometry_depthperpass": self.ui.geometry_defaults_form.geometry_opt_group.depthperpass_entry,
  1185. "geometry_multidepth": self.ui.geometry_defaults_form.geometry_opt_group.multidepth_cb,
  1186. # Geometry Advanced Options
  1187. "geometry_toolchangexy": self.ui.geometry_defaults_form.geometry_adv_opt_group.toolchangexy_entry,
  1188. "geometry_startz": self.ui.geometry_defaults_form.geometry_adv_opt_group.gstartz_entry,
  1189. "geometry_feedrate_rapid": self.ui.geometry_defaults_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  1190. "geometry_extracut": self.ui.geometry_defaults_form.geometry_adv_opt_group.extracut_cb,
  1191. "geometry_extracut_length": self.ui.geometry_defaults_form.geometry_adv_opt_group.e_cut_entry,
  1192. "geometry_z_pdepth": self.ui.geometry_defaults_form.geometry_adv_opt_group.pdepth_entry,
  1193. "geometry_feedrate_probe": self.ui.geometry_defaults_form.geometry_adv_opt_group.feedrate_probe_entry,
  1194. "geometry_spindledir": self.ui.geometry_defaults_form.geometry_adv_opt_group.spindledir_radio,
  1195. "geometry_f_plunge": self.ui.geometry_defaults_form.geometry_adv_opt_group.fplunge_cb,
  1196. "geometry_segx": self.ui.geometry_defaults_form.geometry_adv_opt_group.segx_entry,
  1197. "geometry_segy": self.ui.geometry_defaults_form.geometry_adv_opt_group.segy_entry,
  1198. # Geometry Editor
  1199. "geometry_editor_sel_limit": self.ui.geometry_defaults_form.geometry_editor_group.sel_limit_entry,
  1200. "geometry_editor_milling_type": self.ui.geometry_defaults_form.geometry_editor_group.milling_type_radio,
  1201. # CNCJob General
  1202. "cncjob_plot": self.ui.cncjob_defaults_form.cncjob_gen_group.plot_cb,
  1203. "cncjob_plot_kind": self.ui.cncjob_defaults_form.cncjob_gen_group.cncplot_method_radio,
  1204. "cncjob_annotation": self.ui.cncjob_defaults_form.cncjob_gen_group.annotation_cb,
  1205. "cncjob_tooldia": self.ui.cncjob_defaults_form.cncjob_gen_group.tooldia_entry,
  1206. "cncjob_coords_type": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_type_radio,
  1207. "cncjob_coords_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_dec_entry,
  1208. "cncjob_fr_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.fr_dec_entry,
  1209. "cncjob_steps_per_circle": self.ui.cncjob_defaults_form.cncjob_gen_group.steps_per_circle_entry,
  1210. "cncjob_line_ending": self.ui.cncjob_defaults_form.cncjob_gen_group.line_ending_cb,
  1211. "cncjob_plot_line": self.ui.cncjob_defaults_form.cncjob_gen_group.line_color_entry,
  1212. "cncjob_plot_fill": self.ui.cncjob_defaults_form.cncjob_gen_group.fill_color_entry,
  1213. "cncjob_travel_line": self.ui.cncjob_defaults_form.cncjob_gen_group.tline_color_entry,
  1214. "cncjob_travel_fill": self.ui.cncjob_defaults_form.cncjob_gen_group.tfill_color_entry,
  1215. # CNC Job Options
  1216. "cncjob_prepend": self.ui.cncjob_defaults_form.cncjob_opt_group.prepend_text,
  1217. "cncjob_append": self.ui.cncjob_defaults_form.cncjob_opt_group.append_text,
  1218. # CNC Job Advanced Options
  1219. "cncjob_toolchange_macro": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_text,
  1220. "cncjob_toolchange_macro_enable": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.toolchange_cb,
  1221. "cncjob_annotation_fontsize": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontsize_sp,
  1222. "cncjob_annotation_fontcolor": self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry,
  1223. # NCC Tool
  1224. "tools_ncctools": self.ui.tools_defaults_form.tools_ncc_group.ncc_tool_dia_entry,
  1225. "tools_nccorder": self.ui.tools_defaults_form.tools_ncc_group.ncc_order_radio,
  1226. "tools_nccoverlap": self.ui.tools_defaults_form.tools_ncc_group.ncc_overlap_entry,
  1227. "tools_nccmargin": self.ui.tools_defaults_form.tools_ncc_group.ncc_margin_entry,
  1228. "tools_nccmethod": self.ui.tools_defaults_form.tools_ncc_group.ncc_method_radio,
  1229. "tools_nccconnect": self.ui.tools_defaults_form.tools_ncc_group.ncc_connect_cb,
  1230. "tools_ncccontour": self.ui.tools_defaults_form.tools_ncc_group.ncc_contour_cb,
  1231. "tools_nccrest": self.ui.tools_defaults_form.tools_ncc_group.ncc_rest_cb,
  1232. "tools_ncc_offset_choice": self.ui.tools_defaults_form.tools_ncc_group.ncc_choice_offset_cb,
  1233. "tools_ncc_offset_value": self.ui.tools_defaults_form.tools_ncc_group.ncc_offset_spinner,
  1234. "tools_nccref": self.ui.tools_defaults_form.tools_ncc_group.reference_radio,
  1235. "tools_ncc_plotting": self.ui.tools_defaults_form.tools_ncc_group.ncc_plotting_radio,
  1236. "tools_nccmilling_type": self.ui.tools_defaults_form.tools_ncc_group.milling_type_radio,
  1237. "tools_ncctool_type": self.ui.tools_defaults_form.tools_ncc_group.tool_type_radio,
  1238. "tools_ncccutz": self.ui.tools_defaults_form.tools_ncc_group.cutz_entry,
  1239. "tools_ncctipdia": self.ui.tools_defaults_form.tools_ncc_group.tipdia_entry,
  1240. "tools_ncctipangle": self.ui.tools_defaults_form.tools_ncc_group.tipangle_entry,
  1241. "tools_nccnewdia": self.ui.tools_defaults_form.tools_ncc_group.newdia_entry,
  1242. # CutOut Tool
  1243. "tools_cutouttooldia": self.ui.tools_defaults_form.tools_cutout_group.cutout_tooldia_entry,
  1244. "tools_cutoutkind": self.ui.tools_defaults_form.tools_cutout_group.obj_kind_combo,
  1245. "tools_cutoutmargin": self.ui.tools_defaults_form.tools_cutout_group.cutout_margin_entry,
  1246. "tools_cutout_z": self.ui.tools_defaults_form.tools_cutout_group.cutz_entry,
  1247. "tools_cutout_depthperpass": self.ui.tools_defaults_form.tools_cutout_group.maxdepth_entry,
  1248. "tools_cutout_mdepth": self.ui.tools_defaults_form.tools_cutout_group.mpass_cb,
  1249. "tools_cutoutgapsize": self.ui.tools_defaults_form.tools_cutout_group.cutout_gap_entry,
  1250. "tools_gaps_ff": self.ui.tools_defaults_form.tools_cutout_group.gaps_combo,
  1251. "tools_cutout_convexshape": self.ui.tools_defaults_form.tools_cutout_group.convex_box,
  1252. # Paint Area Tool
  1253. "tools_painttooldia": self.ui.tools_defaults_form.tools_paint_group.painttooldia_entry,
  1254. "tools_paintorder": self.ui.tools_defaults_form.tools_paint_group.paint_order_radio,
  1255. "tools_paintoverlap": self.ui.tools_defaults_form.tools_paint_group.paintoverlap_entry,
  1256. "tools_paintmargin": self.ui.tools_defaults_form.tools_paint_group.paintmargin_entry,
  1257. "tools_paintmethod": self.ui.tools_defaults_form.tools_paint_group.paintmethod_combo,
  1258. "tools_selectmethod": self.ui.tools_defaults_form.tools_paint_group.selectmethod_combo,
  1259. "tools_pathconnect": self.ui.tools_defaults_form.tools_paint_group.pathconnect_cb,
  1260. "tools_paintcontour": self.ui.tools_defaults_form.tools_paint_group.contour_cb,
  1261. "tools_paint_plotting": self.ui.tools_defaults_form.tools_paint_group.paint_plotting_radio,
  1262. "tools_paintrest": self.ui.tools_defaults_form.tools_paint_group.rest_cb,
  1263. "tools_painttool_type": self.ui.tools_defaults_form.tools_paint_group.tool_type_radio,
  1264. "tools_paintcutz": self.ui.tools_defaults_form.tools_paint_group.cutz_entry,
  1265. "tools_painttipdia": self.ui.tools_defaults_form.tools_paint_group.tipdia_entry,
  1266. "tools_painttipangle": self.ui.tools_defaults_form.tools_paint_group.tipangle_entry,
  1267. "tools_paintnewdia": self.ui.tools_defaults_form.tools_paint_group.newdia_entry,
  1268. # 2-sided Tool
  1269. "tools_2sided_mirror_axis": self.ui.tools_defaults_form.tools_2sided_group.mirror_axis_radio,
  1270. "tools_2sided_axis_loc": self.ui.tools_defaults_form.tools_2sided_group.axis_location_radio,
  1271. "tools_2sided_drilldia": self.ui.tools_defaults_form.tools_2sided_group.drill_dia_entry,
  1272. "tools_2sided_allign_axis": self.ui.tools_defaults_form.tools_2sided_group.align_axis_radio,
  1273. # Film Tool
  1274. "tools_film_type": self.ui.tools_defaults_form.tools_film_group.film_type_radio,
  1275. "tools_film_boundary": self.ui.tools_defaults_form.tools_film_group.film_boundary_entry,
  1276. "tools_film_scale_stroke": self.ui.tools_defaults_form.tools_film_group.film_scale_stroke_entry,
  1277. "tools_film_color": self.ui.tools_defaults_form.tools_film_group.film_color_entry,
  1278. "tools_film_scale_cb": self.ui.tools_defaults_form.tools_film_group.film_scale_cb,
  1279. "tools_film_scale_x_entry": self.ui.tools_defaults_form.tools_film_group.film_scalex_entry,
  1280. "tools_film_scale_y_entry": self.ui.tools_defaults_form.tools_film_group.film_scaley_entry,
  1281. "tools_film_skew_cb": self.ui.tools_defaults_form.tools_film_group.film_skew_cb,
  1282. "tools_film_skew_x_entry": self.ui.tools_defaults_form.tools_film_group.film_skewx_entry,
  1283. "tools_film_skew_y_entry": self.ui.tools_defaults_form.tools_film_group.film_skewy_entry,
  1284. "tools_film_skew_ref_radio": self.ui.tools_defaults_form.tools_film_group.film_skew_reference,
  1285. "tools_film_mirror_cb": self.ui.tools_defaults_form.tools_film_group.film_mirror_cb,
  1286. "tools_film_mirror_axis_radio": self.ui.tools_defaults_form.tools_film_group.film_mirror_axis,
  1287. "tools_film_file_type_radio": self.ui.tools_defaults_form.tools_film_group.file_type_radio,
  1288. "tools_film_orientation": self.ui.tools_defaults_form.tools_film_group.orientation_radio,
  1289. "tools_film_pagesize": self.ui.tools_defaults_form.tools_film_group.pagesize_combo,
  1290. # Panelize Tool
  1291. "tools_panelize_spacing_columns": self.ui.tools_defaults_form.tools_panelize_group.pspacing_columns,
  1292. "tools_panelize_spacing_rows": self.ui.tools_defaults_form.tools_panelize_group.pspacing_rows,
  1293. "tools_panelize_columns": self.ui.tools_defaults_form.tools_panelize_group.pcolumns,
  1294. "tools_panelize_rows": self.ui.tools_defaults_form.tools_panelize_group.prows,
  1295. "tools_panelize_constrain": self.ui.tools_defaults_form.tools_panelize_group.pconstrain_cb,
  1296. "tools_panelize_constrainx": self.ui.tools_defaults_form.tools_panelize_group.px_width_entry,
  1297. "tools_panelize_constrainy": self.ui.tools_defaults_form.tools_panelize_group.py_height_entry,
  1298. "tools_panelize_panel_type": self.ui.tools_defaults_form.tools_panelize_group.panel_type_radio,
  1299. # Calculators Tool
  1300. "tools_calc_vshape_tip_dia": self.ui.tools_defaults_form.tools_calculators_group.tip_dia_entry,
  1301. "tools_calc_vshape_tip_angle": self.ui.tools_defaults_form.tools_calculators_group.tip_angle_entry,
  1302. "tools_calc_vshape_cut_z": self.ui.tools_defaults_form.tools_calculators_group.cut_z_entry,
  1303. "tools_calc_electro_length": self.ui.tools_defaults_form.tools_calculators_group.pcblength_entry,
  1304. "tools_calc_electro_width": self.ui.tools_defaults_form.tools_calculators_group.pcbwidth_entry,
  1305. "tools_calc_electro_cdensity": self.ui.tools_defaults_form.tools_calculators_group.cdensity_entry,
  1306. "tools_calc_electro_growth": self.ui.tools_defaults_form.tools_calculators_group.growth_entry,
  1307. # Transformations Tool
  1308. "tools_transform_rotate": self.ui.tools_defaults_form.tools_transform_group.rotate_entry,
  1309. "tools_transform_skew_x": self.ui.tools_defaults_form.tools_transform_group.skewx_entry,
  1310. "tools_transform_skew_y": self.ui.tools_defaults_form.tools_transform_group.skewy_entry,
  1311. "tools_transform_scale_x": self.ui.tools_defaults_form.tools_transform_group.scalex_entry,
  1312. "tools_transform_scale_y": self.ui.tools_defaults_form.tools_transform_group.scaley_entry,
  1313. "tools_transform_scale_link": self.ui.tools_defaults_form.tools_transform_group.link_cb,
  1314. "tools_transform_scale_reference": self.ui.tools_defaults_form.tools_transform_group.reference_cb,
  1315. "tools_transform_offset_x": self.ui.tools_defaults_form.tools_transform_group.offx_entry,
  1316. "tools_transform_offset_y": self.ui.tools_defaults_form.tools_transform_group.offy_entry,
  1317. "tools_transform_mirror_reference": self.ui.tools_defaults_form.tools_transform_group.mirror_reference_cb,
  1318. "tools_transform_mirror_point": self.ui.tools_defaults_form.tools_transform_group.flip_ref_entry,
  1319. "tools_transform_buffer_dis": self.ui.tools_defaults_form.tools_transform_group.buffer_entry,
  1320. "tools_transform_buffer_factor": self.ui.tools_defaults_form.tools_transform_group.buffer_factor_entry,
  1321. "tools_transform_buffer_corner": self.ui.tools_defaults_form.tools_transform_group.buffer_rounded_cb,
  1322. # SolderPaste Dispensing Tool
  1323. "tools_solderpaste_tools": self.ui.tools_defaults_form.tools_solderpaste_group.nozzle_tool_dia_entry,
  1324. "tools_solderpaste_new": self.ui.tools_defaults_form.tools_solderpaste_group.addtool_entry,
  1325. "tools_solderpaste_z_start": self.ui.tools_defaults_form.tools_solderpaste_group.z_start_entry,
  1326. "tools_solderpaste_z_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.z_dispense_entry,
  1327. "tools_solderpaste_z_stop": self.ui.tools_defaults_form.tools_solderpaste_group.z_stop_entry,
  1328. "tools_solderpaste_z_travel": self.ui.tools_defaults_form.tools_solderpaste_group.z_travel_entry,
  1329. "tools_solderpaste_z_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.z_toolchange_entry,
  1330. "tools_solderpaste_xy_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.xy_toolchange_entry,
  1331. "tools_solderpaste_frxy": self.ui.tools_defaults_form.tools_solderpaste_group.frxy_entry,
  1332. "tools_solderpaste_frz": self.ui.tools_defaults_form.tools_solderpaste_group.frz_entry,
  1333. "tools_solderpaste_frz_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.frz_dispense_entry,
  1334. "tools_solderpaste_speedfwd": self.ui.tools_defaults_form.tools_solderpaste_group.speedfwd_entry,
  1335. "tools_solderpaste_dwellfwd": self.ui.tools_defaults_form.tools_solderpaste_group.dwellfwd_entry,
  1336. "tools_solderpaste_speedrev": self.ui.tools_defaults_form.tools_solderpaste_group.speedrev_entry,
  1337. "tools_solderpaste_dwellrev": self.ui.tools_defaults_form.tools_solderpaste_group.dwellrev_entry,
  1338. "tools_solderpaste_pp": self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo,
  1339. "tools_sub_close_paths": self.ui.tools_defaults_form.tools_sub_group.close_paths_cb,
  1340. # ###################################################################################
  1341. # ################################ TOOLS 2 ##########################################
  1342. # ###################################################################################
  1343. # Optimal Tool
  1344. "tools_opt_precision": self.ui.tools2_defaults_form.tools2_optimal_group.precision_sp,
  1345. # Check Rules Tool
  1346. "tools_cr_trace_size": self.ui.tools2_defaults_form.tools2_checkrules_group.trace_size_cb,
  1347. "tools_cr_trace_size_val": self.ui.tools2_defaults_form.tools2_checkrules_group.trace_size_entry,
  1348. "tools_cr_c2c": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_copper2copper_cb,
  1349. "tools_cr_c2c_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_copper2copper_entry,
  1350. "tools_cr_c2o": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_copper2ol_cb,
  1351. "tools_cr_c2o_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_copper2ol_entry,
  1352. "tools_cr_s2s": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2silk_cb,
  1353. "tools_cr_s2s_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2silk_entry,
  1354. "tools_cr_s2sm": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2sm_cb,
  1355. "tools_cr_s2sm_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2sm_entry,
  1356. "tools_cr_s2o": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2ol_cb,
  1357. "tools_cr_s2o_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_silk2ol_entry,
  1358. "tools_cr_sm2sm": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_sm2sm_cb,
  1359. "tools_cr_sm2sm_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_sm2sm_entry,
  1360. "tools_cr_ri": self.ui.tools2_defaults_form.tools2_checkrules_group.ring_integrity_cb,
  1361. "tools_cr_ri_val": self.ui.tools2_defaults_form.tools2_checkrules_group.ring_integrity_entry,
  1362. "tools_cr_h2h": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_d2d_cb,
  1363. "tools_cr_h2h_val": self.ui.tools2_defaults_form.tools2_checkrules_group.clearance_d2d_entry,
  1364. "tools_cr_dh": self.ui.tools2_defaults_form.tools2_checkrules_group.drill_size_cb,
  1365. "tools_cr_dh_val": self.ui.tools2_defaults_form.tools2_checkrules_group.drill_size_entry,
  1366. # QRCode Tool
  1367. "tools_qrcode_version": self.ui.tools2_defaults_form.tools2_qrcode_group.version_entry,
  1368. "tools_qrcode_error": self.ui.tools2_defaults_form.tools2_qrcode_group.error_radio,
  1369. "tools_qrcode_box_size": self.ui.tools2_defaults_form.tools2_qrcode_group.bsize_entry,
  1370. "tools_qrcode_border_size": self.ui.tools2_defaults_form.tools2_qrcode_group.border_size_entry,
  1371. "tools_qrcode_qrdata": self.ui.tools2_defaults_form.tools2_qrcode_group.text_data,
  1372. "tools_qrcode_polarity": self.ui.tools2_defaults_form.tools2_qrcode_group.pol_radio,
  1373. "tools_qrcode_rounded": self.ui.tools2_defaults_form.tools2_qrcode_group.bb_radio,
  1374. "tools_qrcode_fill_color": self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry,
  1375. "tools_qrcode_back_color": self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry,
  1376. "tools_qrcode_sel_limit": self.ui.tools2_defaults_form.tools2_qrcode_group.sel_limit_entry,
  1377. # Copper Thieving Tool
  1378. "tools_copper_thieving_clearance": self.ui.tools2_defaults_form.tools2_cfill_group.clearance_entry,
  1379. "tools_copper_thieving_margin": self.ui.tools2_defaults_form.tools2_cfill_group.margin_entry,
  1380. "tools_copper_thieving_reference": self.ui.tools2_defaults_form.tools2_cfill_group.reference_radio,
  1381. "tools_copper_thieving_box_type": self.ui.tools2_defaults_form.tools2_cfill_group.bbox_type_radio,
  1382. "tools_copper_thieving_circle_steps": self.ui.tools2_defaults_form.tools2_cfill_group.circlesteps_entry,
  1383. "tools_copper_thieving_fill_type": self.ui.tools2_defaults_form.tools2_cfill_group.fill_type_radio,
  1384. "tools_copper_thieving_dots_dia": self.ui.tools2_defaults_form.tools2_cfill_group.dot_dia_entry,
  1385. "tools_copper_thieving_dots_spacing": self.ui.tools2_defaults_form.tools2_cfill_group.dot_spacing_entry,
  1386. "tools_copper_thieving_squares_size": self.ui.tools2_defaults_form.tools2_cfill_group.square_size_entry,
  1387. "tools_copper_thieving_squares_spacing":
  1388. self.ui.tools2_defaults_form.tools2_cfill_group.squares_spacing_entry,
  1389. "tools_copper_thieving_lines_size": self.ui.tools2_defaults_form.tools2_cfill_group.line_size_entry,
  1390. "tools_copper_thieving_lines_spacing": self.ui.tools2_defaults_form.tools2_cfill_group.lines_spacing_entry,
  1391. "tools_copper_thieving_rb_margin": self.ui.tools2_defaults_form.tools2_cfill_group.rb_margin_entry,
  1392. "tools_copper_thieving_rb_thickness": self.ui.tools2_defaults_form.tools2_cfill_group.rb_thickness_entry,
  1393. "tools_copper_thieving_mask_clearance": self.ui.tools2_defaults_form.tools2_cfill_group.clearance_ppm_entry,
  1394. # Fiducials Tool
  1395. "tools_fiducials_dia": self.ui.tools2_defaults_form.tools2_fiducials_group.dia_entry,
  1396. "tools_fiducials_margin": self.ui.tools2_defaults_form.tools2_fiducials_group.margin_entry,
  1397. "tools_fiducials_mode": self.ui.tools2_defaults_form.tools2_fiducials_group.mode_radio,
  1398. "tools_fiducials_second_pos": self.ui.tools2_defaults_form.tools2_fiducials_group.pos_radio,
  1399. "tools_fiducials_type": self.ui.tools2_defaults_form.tools2_fiducials_group.fid_type_radio,
  1400. "tools_fiducials_line_thickness": self.ui.tools2_defaults_form.tools2_fiducials_group.line_thickness_entry,
  1401. # Calibration Tool
  1402. "tools_cal_calsource": self.ui.tools2_defaults_form.tools2_cal_group.cal_source_radio,
  1403. "tools_cal_travelz": self.ui.tools2_defaults_form.tools2_cal_group.travelz_entry,
  1404. "tools_cal_verz": self.ui.tools2_defaults_form.tools2_cal_group.verz_entry,
  1405. "tools_cal_zeroz": self.ui.tools2_defaults_form.tools2_cal_group.zeroz_cb,
  1406. "tools_cal_toolchangez": self.ui.tools2_defaults_form.tools2_cal_group.toolchangez_entry,
  1407. "tools_cal_toolchange_xy": self.ui.tools2_defaults_form.tools2_cal_group.toolchange_xy_entry,
  1408. "tools_cal_sec_point": self.ui.tools2_defaults_form.tools2_cal_group.second_point_radio,
  1409. # Extract Drills Tool
  1410. "tools_edrills_hole_type": self.ui.tools2_defaults_form.tools2_edrills_group.hole_size_radio,
  1411. "tools_edrills_hole_fixed_dia": self.ui.tools2_defaults_form.tools2_edrills_group.dia_entry,
  1412. "tools_edrills_hole_prop_factor": self.ui.tools2_defaults_form.tools2_edrills_group.factor_entry,
  1413. "tools_edrills_circular_ring": self.ui.tools2_defaults_form.tools2_edrills_group.circular_ring_entry,
  1414. "tools_edrills_oblong_ring": self.ui.tools2_defaults_form.tools2_edrills_group.oblong_ring_entry,
  1415. "tools_edrills_square_ring": self.ui.tools2_defaults_form.tools2_edrills_group.square_ring_entry,
  1416. "tools_edrills_rectangular_ring": self.ui.tools2_defaults_form.tools2_edrills_group.rectangular_ring_entry,
  1417. "tools_edrills_others_ring": self.ui.tools2_defaults_form.tools2_edrills_group.other_ring_entry,
  1418. "tools_edrills_circular": self.ui.tools2_defaults_form.tools2_edrills_group.circular_cb,
  1419. "tools_edrills_oblong": self.ui.tools2_defaults_form.tools2_edrills_group.oblong_cb,
  1420. "tools_edrills_square": self.ui.tools2_defaults_form.tools2_edrills_group.square_cb,
  1421. "tools_edrills_rectangular": self.ui.tools2_defaults_form.tools2_edrills_group.rectangular_cb,
  1422. "tools_edrills_others": self.ui.tools2_defaults_form.tools2_edrills_group.other_cb,
  1423. # Utilities
  1424. # File associations
  1425. "fa_excellon": self.ui.util_defaults_form.fa_excellon_group.exc_list_text,
  1426. "fa_gcode": self.ui.util_defaults_form.fa_gcode_group.gco_list_text,
  1427. # "fa_geometry": self.ui.util_defaults_form.fa_geometry_group.close_paths_cb,
  1428. "fa_gerber": self.ui.util_defaults_form.fa_gerber_group.grb_list_text,
  1429. "util_autocomplete_keywords": self.ui.util_defaults_form.kw_group.kw_list_text,
  1430. }
  1431. # update the Preferences GUI elements with the values in the self.defaults
  1432. self.defaults_write_form()
  1433. # When the self.defaults dictionary changes will update the Preferences GUI forms
  1434. self.defaults.set_change_callback(self.on_defaults_dict_change)
  1435. # ##############################################################################
  1436. # ########################## FIRST RUN SECTION #################################
  1437. # ##################### It's done only once after install ####################
  1438. # ##############################################################################
  1439. if self.defaults["first_run"] is True:
  1440. self.save_factory_defaults(silent_message=False)
  1441. # and then make the factory_defaults.FlatConfig file read_only so it can't be modified after creation.
  1442. filename_factory = self.data_path + '/factory_defaults.FlatConfig'
  1443. os.chmod(filename_factory, S_IREAD | S_IRGRP | S_IROTH)
  1444. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  1445. initial_lay = 'compact'
  1446. self.on_layout(lay=initial_lay)
  1447. # Set the combobox in Preferences to the current layout
  1448. idx = self.ui.general_defaults_form.general_gui_group.layout_combo.findText(initial_lay)
  1449. self.ui.general_defaults_form.general_gui_group.layout_combo.setCurrentIndex(idx)
  1450. # after the first run, this object should be False
  1451. self.defaults["first_run"] = False
  1452. self.save_defaults(silent=True)
  1453. # #############################################################################
  1454. # ############################## Data #########################################
  1455. # #############################################################################
  1456. self.recent = []
  1457. self.recent_projects = []
  1458. self.clipboard = QtWidgets.QApplication.clipboard()
  1459. self.project_filename = None
  1460. self.toggle_units_ignore = False
  1461. # #############################################################################
  1462. # ########################## LOAD PREPROCESSORS ###############################
  1463. # #############################################################################
  1464. # a dictionary that have as keys the name of the preprocessor files and the value is the class from
  1465. # the preprocessor file
  1466. self.preprocessors = load_preprocessors(self)
  1467. # make sure that always the 'default' preprocessor is the first item in the dictionary
  1468. if 'default' in self.preprocessors.keys():
  1469. new_ppp_dict = dict()
  1470. # add the 'default' name first in the dict after removing from the preprocessor's dictionary
  1471. default_pp = self.preprocessors.pop('default')
  1472. new_ppp_dict['default'] = default_pp
  1473. # then add the rest of the keys
  1474. for name, val_class in self.preprocessors.items():
  1475. new_ppp_dict[name] = val_class
  1476. # and now put back the ordered dict with 'default' key first
  1477. self.preprocessors = new_ppp_dict
  1478. for name in list(self.preprocessors.keys()):
  1479. # 'Paste' preprocessors are to be used only in the Solder Paste Dispensing Tool
  1480. if name.partition('_')[0] == 'Paste':
  1481. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  1482. continue
  1483. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  1484. # HPGL preprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  1485. if name == 'hpgl':
  1486. continue
  1487. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  1488. # #############################################################################
  1489. # ########################## LOAD LANGUAGES ##################################
  1490. # #############################################################################
  1491. self.languages = fcTranslate.load_languages()
  1492. for name in sorted(self.languages.values()):
  1493. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  1494. # #############################################################################
  1495. # ############################ APPLY APP LANGUAGE #############################
  1496. # #############################################################################
  1497. ret_val = fcTranslate.apply_language('strings')
  1498. if ret_val == "no language":
  1499. self.inform.emit('[ERROR] %s' %
  1500. _("Could not find the Language files. The App strings are missing."))
  1501. log.debug("Could not find the Language files. The App strings are missing.")
  1502. else:
  1503. # make the current language the current selection on the language combobox
  1504. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  1505. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  1506. # #############################################################################
  1507. # ########################### CREATE UNIQUE SERIAL NUMBER #####################
  1508. # #############################################################################
  1509. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  1510. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  1511. self.defaults['global_serial'] = ''.join([random.choice(chars) for __ in range(20)])
  1512. self.save_defaults(silent=True, first_time=True)
  1513. self.propagate_defaults(silent=True)
  1514. # def auto_save_defaults():
  1515. # try:
  1516. # self.save_defaults(silent=True)
  1517. # self.propagate_defaults(silent=True)
  1518. # finally:
  1519. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  1520. # the following lines activates automatic defaults save
  1521. # if user_defaults:
  1522. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  1523. # #############################################################################
  1524. # ########################### UPDATE THE OPTIONS ##############################
  1525. # #############################################################################
  1526. self.options = LoudDict()
  1527. # ----------------------------------------------------------------------------------------------------
  1528. # Update the self.options from the self.defaults
  1529. # The self.defaults holds the application defaults while the self.options holds the object defaults
  1530. # -----------------------------------------------------------------------------------------------------
  1531. # Copy app defaults to project options
  1532. for def_key, def_val in self.defaults.items():
  1533. self.options[def_key] = deepcopy(def_val)
  1534. # self.options.update(self.defaults)
  1535. self.gen_form = None
  1536. self.ger_form = None
  1537. self.exc_form = None
  1538. self.geo_form = None
  1539. self.cnc_form = None
  1540. self.tools_form = None
  1541. self.tools2_form = None
  1542. self.fa_form = None
  1543. # Will show the Preferences GUI
  1544. self.show_preferences_gui()
  1545. # Initialize the color box's color in Preferences -> Global -> Color
  1546. self.init_color_pickers_in_preferences_gui()
  1547. # ### End of Data ####
  1548. # #############################################################################
  1549. # ######################## SETUP OBJECT COLLECTION ############################
  1550. # #############################################################################
  1551. self.collection = ObjectCollection(self)
  1552. self.ui.project_tab_layout.addWidget(self.collection.view)
  1553. # ### Adjust tabs width ## ##
  1554. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  1555. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  1556. self.collection.view.setMinimumWidth(290)
  1557. self.log.debug("Finished creating Object Collection.")
  1558. # #############################################################################
  1559. # ############################## SETUP Plot Area ##############################
  1560. # #############################################################################
  1561. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  1562. if self.defaults["global_graphic_engine"] == '3D':
  1563. self.is_legacy = False
  1564. else:
  1565. self.is_legacy = True
  1566. # Event signals disconnect id holders
  1567. self.mp = None
  1568. self.mm = None
  1569. self.mr = None
  1570. self.mdc = None
  1571. self.mp_zc = None
  1572. self.kp = None
  1573. # Matplotlib axis
  1574. self.axes = None
  1575. if show_splash:
  1576. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  1577. "Canvas initialization started."),
  1578. alignment=Qt.AlignBottom | Qt.AlignLeft,
  1579. color=QtGui.QColor("gray"))
  1580. start_plot_time = time.time() # debug
  1581. self.plotcanvas = None
  1582. self.app_cursor = None
  1583. self.hover_shapes = None
  1584. self.log.debug("Setting up canvas: %s" % str(self.defaults["global_graphic_engine"]))
  1585. # setup the PlotCanvas
  1586. self.on_plotcanvas_setup()
  1587. end_plot_time = time.time()
  1588. self.used_time = end_plot_time - start_plot_time
  1589. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  1590. if show_splash:
  1591. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  1592. "Canvas initialization started.\n"
  1593. "Canvas initialization finished in"), '%.2f' % self.used_time),
  1594. alignment=Qt.AlignBottom | Qt.AlignLeft,
  1595. color=QtGui.QColor("gray"))
  1596. self.ui.splitter.setStretchFactor(1, 2)
  1597. # #############################################################################
  1598. # ################################### SYS TRAY ################################
  1599. # #############################################################################
  1600. if self.defaults["global_systray_icon"]:
  1601. self.parent_w = QtWidgets.QWidget()
  1602. if self.cmd_line_headless == 1:
  1603. self.trayIcon = FlatCAMSystemTray(app=self,
  1604. icon=QtGui.QIcon(self.resource_location +
  1605. '/flatcam_icon32_green.png'),
  1606. headless=True,
  1607. parent=self.parent_w)
  1608. else:
  1609. self.trayIcon = FlatCAMSystemTray(app=self,
  1610. icon=QtGui.QIcon(self.resource_location +
  1611. '/flatcam_icon32_green.png'),
  1612. parent=self.parent_w)
  1613. # #############################################################################
  1614. # ################################## Worker SETUP #############################
  1615. # #############################################################################
  1616. if self.defaults["global_worker_number"]:
  1617. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  1618. else:
  1619. self.workers = WorkerStack(workers_number=2)
  1620. self.worker_task.connect(self.workers.add_task)
  1621. self.log.debug("Finished creating Workers crew.")
  1622. # #############################################################################
  1623. # ################################# Activity Monitor ##########################
  1624. # #############################################################################
  1625. self.activity_view = FlatCAMActivityView(app=self)
  1626. self.ui.infobar.addWidget(self.activity_view)
  1627. self.proc_container = FCVisibleProcessContainer(self.activity_view)
  1628. # #############################################################################
  1629. # ################################## Signal handling ##########################
  1630. # #############################################################################
  1631. # ################################# Custom signals ###########################
  1632. # signal for displaying messages in status bar
  1633. self.inform.connect(self.info)
  1634. # signal to be called when the app is quiting
  1635. self.app_quit.connect(self.quit_application, type=Qt.QueuedConnection)
  1636. self.message.connect(self.message_dialog)
  1637. # self.progress.connect(self.set_progress_bar)
  1638. # signals that are emitted when object state changes
  1639. self.object_created.connect(self.on_object_created)
  1640. self.object_changed.connect(self.on_object_changed)
  1641. self.object_plotted.connect(self.on_object_plotted)
  1642. self.plots_updated.connect(self.on_plots_updated)
  1643. # signals emitted when file state change
  1644. self.file_opened.connect(self.register_recent)
  1645. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  1646. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  1647. # ############# Standard signals ###################
  1648. # ### Menu
  1649. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  1650. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  1651. self.ui.menufilenewgrb.triggered.connect(self.new_gerber_object)
  1652. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  1653. self.ui.menufilenewdoc.triggered.connect(self.new_document_object)
  1654. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  1655. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  1656. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  1657. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  1658. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  1659. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  1660. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  1661. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  1662. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  1663. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  1664. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  1665. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  1666. self.ui.menufileimport_hpgl2_as_geo.triggered.connect(self.on_fileopenhpgl2)
  1667. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  1668. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  1669. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  1670. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  1671. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  1672. self.ui.menufile_print.triggered.connect(lambda: self.on_file_save_objects_pdf(use_thread=True))
  1673. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  1674. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  1675. self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  1676. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  1677. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  1678. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  1679. self.ui.menufile_exit.triggered.connect(self.final_save)
  1680. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  1681. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  1682. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  1683. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  1684. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  1685. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  1686. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  1687. self.ui.menueditdelete.triggered.connect(self.on_delete)
  1688. self.ui.menueditcopyobject.triggered.connect(self.on_copy_command)
  1689. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  1690. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  1691. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  1692. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  1693. self.ui.menueditlocate.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  1694. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  1695. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  1696. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  1697. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  1698. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  1699. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  1700. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  1701. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  1702. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  1703. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  1704. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  1705. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  1706. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  1707. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  1708. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  1709. self.ui.menuoptions_tools_db.triggered.connect(self.on_tools_database)
  1710. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  1711. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  1712. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  1713. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  1714. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  1715. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  1716. self.ui.menuview_replot.triggered.connect(self.plot_all)
  1717. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  1718. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  1719. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  1720. self.ui.menuview_toggle_notebook.triggered.connect(self.on_toggle_notebook)
  1721. self.ui.menu_toggle_nb.triggered.connect(self.on_toggle_notebook)
  1722. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  1723. self.ui.menuview_toggle_grid_lines.triggered.connect(self.on_toggle_grid_lines)
  1724. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  1725. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_toggle)
  1726. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  1727. self.ui.menuhelp_about.triggered.connect(self.on_about)
  1728. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  1729. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  1730. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  1731. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  1732. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  1733. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  1734. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  1735. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  1736. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  1737. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  1738. self.ui.menuprojectcopy.triggered.connect(self.on_copy_command)
  1739. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  1740. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  1741. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  1742. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  1743. # ToolBar signals
  1744. self.connect_toolbar_signals()
  1745. # Notebook and Plot Tab Area signals
  1746. # make the right click on the notebook tab and plot tab area tab raise a menu
  1747. self.ui.notebook.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  1748. self.ui.plot_tab_area.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  1749. self.on_tab_setup_context_menu()
  1750. # activate initial state
  1751. self.on_tab_rmb_click(self.defaults["global_tabs_detachable"])
  1752. # Context Menu
  1753. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  1754. self.ui.popmenu_panel_toggle.triggered.connect(self.on_toggle_notebook)
  1755. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  1756. self.ui.popmenu_new_grb.triggered.connect(self.new_gerber_object)
  1757. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  1758. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  1759. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  1760. self.ui.clearplot.triggered.connect(self.clear_plots)
  1761. self.ui.replot.triggered.connect(self.plot_all)
  1762. self.ui.popmenu_copy.triggered.connect(self.on_copy_command)
  1763. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  1764. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  1765. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  1766. self.ui.popmenu_move.triggered.connect(self.obj_move)
  1767. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  1768. # Project Context Menu -> Color Setting
  1769. for act in self.ui.menuprojectcolor.actions():
  1770. act.triggered.connect(self.on_set_color_action_triggered)
  1771. # Preferences Plot Area TAB
  1772. self.ui.pref_save_button.clicked.connect(lambda: self.on_save_button(save_to_file=True))
  1773. self.ui.pref_apply_button.clicked.connect(lambda: self.on_save_button(save_to_file=False))
  1774. self.ui.pref_close_button.clicked.connect(self.on_pref_close_button)
  1775. self.ui.pref_defaults_button.clicked.connect(self.on_restore_defaults_preferences)
  1776. # #############################################################################
  1777. # ######################### GUI PREFERENCES SIGNALS ###########################
  1778. # #############################################################################
  1779. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  1780. lambda: self.on_toggle_units(no_pref=False))
  1781. # ############################# Workspace Setting Signals #####################
  1782. self.ui.general_defaults_form.general_app_set_group.wk_cb.currentIndexChanged.connect(
  1783. self.on_workspace_modified)
  1784. self.ui.general_defaults_form.general_app_set_group.wk_orientation_radio.activated_custom.connect(
  1785. self.on_workspace_modified
  1786. )
  1787. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  1788. self.ui.general_defaults_form.general_gui_group.layout_combo.activated.connect(self.on_layout)
  1789. # #############################################################################
  1790. # ############################# GUI SETTINGS SIGNALS ##########################
  1791. # #############################################################################
  1792. self.ui.general_defaults_form.general_app_group.ge_radio.activated_custom.connect(self.on_app_restart)
  1793. self.ui.general_defaults_form.general_app_set_group.cursor_radio.activated_custom.connect(self.on_cursor_type)
  1794. # ########## Tools related signals #############
  1795. # Film Tool
  1796. self.ui.tools_defaults_form.tools_film_group.film_color_entry.editingFinished.connect(
  1797. self.on_film_color_entry)
  1798. self.ui.tools_defaults_form.tools_film_group.film_color_button.clicked.connect(
  1799. self.on_film_color_button)
  1800. # QRCode Tool
  1801. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.editingFinished.connect(
  1802. self.on_qrcode_fill_color_entry)
  1803. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.clicked.connect(
  1804. self.on_qrcode_fill_color_button)
  1805. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.editingFinished.connect(
  1806. self.on_qrcode_back_color_entry)
  1807. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.clicked.connect(
  1808. self.on_qrcode_back_color_button)
  1809. # portability changed signal
  1810. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  1811. # Object list
  1812. self.collection.view.activated.connect(self.on_row_activated)
  1813. self.collection.item_selected.connect(self.on_row_selected)
  1814. self.object_status_changed.connect(self.on_collection_updated)
  1815. # Make sure that when the Excellon loading parameters are changed, the change is reflected in the
  1816. # Export Excellon parameters.
  1817. self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb.stateChanged.connect(
  1818. self.on_update_exc_export
  1819. )
  1820. # call it once to make sure it is updated at startup
  1821. self.on_update_exc_export(state=self.defaults["excellon_update"])
  1822. # when there are arguments at application startup this get launched
  1823. self.args_at_startup[list].connect(self.on_startup_args)
  1824. # #############################################################################
  1825. # ########################## FILE ASSOCIATIONS SIGNALS ########################
  1826. # #############################################################################
  1827. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  1828. lambda: self.restore_extensions(ext_type='excellon'))
  1829. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  1830. lambda: self.restore_extensions(ext_type='gcode'))
  1831. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  1832. lambda: self.restore_extensions(ext_type='gerber'))
  1833. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  1834. lambda: self.delete_all_extensions(ext_type='excellon'))
  1835. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  1836. lambda: self.delete_all_extensions(ext_type='gcode'))
  1837. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  1838. lambda: self.delete_all_extensions(ext_type='gerber'))
  1839. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  1840. lambda: self.add_extension(ext_type='excellon'))
  1841. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  1842. lambda: self.add_extension(ext_type='gcode'))
  1843. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  1844. lambda: self.add_extension(ext_type='gerber'))
  1845. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  1846. lambda: self.del_extension(ext_type='excellon'))
  1847. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  1848. lambda: self.del_extension(ext_type='gcode'))
  1849. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  1850. lambda: self.del_extension(ext_type='gerber'))
  1851. # connect the 'Apply' buttons from the Preferences/File Associations
  1852. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  1853. lambda: self.on_register_files(obj_type='excellon'))
  1854. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  1855. lambda: self.on_register_files(obj_type='gcode'))
  1856. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  1857. lambda: self.on_register_files(obj_type='gerber'))
  1858. # #############################################################################
  1859. # ################################ KEYWORDS SIGNALS ###########################
  1860. # #############################################################################
  1861. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  1862. lambda: self.restore_extensions(ext_type='keyword'))
  1863. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  1864. lambda: self.delete_all_extensions(ext_type='keyword'))
  1865. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  1866. lambda: self.add_extension(ext_type='keyword'))
  1867. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  1868. lambda: self.del_extension(ext_type='keyword'))
  1869. # connect the abort_all_tasks related slots to the related signals
  1870. self.proc_container.idle_flag.connect(self.app_is_idle)
  1871. # signal emitted when a tab is closed in the Plot Area
  1872. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  1873. self.ui.grid_snap_btn.triggered.connect(self.on_grid_snap_triggered)
  1874. # signal to close the application
  1875. self.close_app_signal.connect(self.kill_app)
  1876. # #####################################################################################
  1877. # ########### FINISHED CONNECTING SIGNALS #############################################
  1878. # #####################################################################################
  1879. self.log.debug("Finished connecting Signals.")
  1880. # #####################################################################################
  1881. # ########################## Other setups #############################################
  1882. # #####################################################################################
  1883. # to use for tools like Distance tool who depends on the event sources who are changed inside the Editors
  1884. # depending on from where those tools are called different actions can be done
  1885. self.call_source = 'app'
  1886. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  1887. self.tool_tab_locked = False
  1888. # decide if to show or hide the Notebook side of the screen at startup
  1889. if self.defaults["global_project_at_startup"] is True:
  1890. self.ui.splitter.setSizes([1, 1])
  1891. else:
  1892. self.ui.splitter.setSizes([0, 1])
  1893. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  1894. self.setup_component_editor()
  1895. # #####################################################################################
  1896. # ######################### Auto-complete KEYWORDS ####################################
  1897. # #####################################################################################
  1898. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  1899. 'aligndrill', 'aligndrillgrid', 'bbox', 'bounding_box', 'clear', 'cncjob', 'cutout',
  1900. 'delete', 'drillcncjob', 'export_dxf', 'edxf', 'export_excellon', 'ee', 'export_exc',
  1901. 'export_gcode', 'export_gerber', 'egr', 'export_svg', 'ext', 'exteriors', 'follow',
  1902. 'geo_union', 'geocutout', 'get_names', 'get_sys', 'getsys', 'help', 'import_svg',
  1903. 'interiors', 'isolate', 'join_excellon', 'join_excellons', 'join_geometries',
  1904. 'join_geometry', 'list_sys', 'listsys', 'milld', 'mills', 'milldrills', 'millslots',
  1905. 'mirror', 'ncc',
  1906. 'ncc_clear', 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  1907. 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'options', 'origin',
  1908. 'paint', 'pan', 'panel', 'panelize', 'plot_all', 'plot_objects', 'quit_flatcam',
  1909. 'save', 'save_project',
  1910. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_sys',
  1911. 'setsys', 'skew', 'subtract_poly', 'subtract_rectangle',
  1912. 'version', 'write_gcode'
  1913. ]
  1914. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'Marius', 'My Documents', 'Paste_1',
  1915. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  1916. 'Toolchange_manual', 'Users', 'all', 'angle_x', 'angle_y', 'auto', 'axis',
  1917. 'axisoffset',
  1918. 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect', 'contour', 'default',
  1919. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz',
  1920. 'dwelltime', 'extracut_length',
  1921. 'feedrate_z', 'grbl_11', 'grbl_laser', 'gridoffsety', 'gridx', 'gridy',
  1922. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  1923. 'milled_dias', 'minoffset', 'name', 'offset', 'opt_type', 'order',
  1924. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  1925. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  1926. 'spacing_columns',
  1927. 'spacing_rows', 'spindlespeed', 'toolchange_xy', 'toolchangez',
  1928. 'tooldia', 'use_threads', 'value',
  1929. 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  1930. ]
  1931. self.tcl_keywords = [
  1932. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  1933. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  1934. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  1935. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  1936. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  1937. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  1938. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  1939. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  1940. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  1941. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  1942. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  1943. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  1944. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  1945. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  1946. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  1947. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  1948. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  1949. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  1950. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  1951. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  1952. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  1953. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  1954. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  1955. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  1956. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  1957. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  1958. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  1959. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  1960. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  1961. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  1962. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  1963. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  1964. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  1965. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  1966. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  1967. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  1968. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  1969. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  1970. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  1971. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  1972. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  1973. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  1974. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  1975. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  1976. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  1977. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  1978. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  1979. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  1980. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  1981. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  1982. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  1983. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  1984. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  1985. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  1986. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  1987. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  1988. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  1989. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  1990. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  1991. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  1992. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  1993. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  1994. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  1995. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  1996. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  1997. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  1998. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  1999. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  2000. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  2001. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  2002. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  2003. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  2004. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  2005. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  2006. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  2007. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  2008. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  2009. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  2010. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  2011. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  2012. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  2013. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  2014. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  2015. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  2016. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  2017. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  2018. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  2019. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  2020. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  2021. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  2022. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  2023. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  2024. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  2025. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  2026. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  2027. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  2028. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  2029. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  2030. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  2031. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  2032. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  2033. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  2034. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  2035. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  2036. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  2037. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  2038. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  2039. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  2040. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  2041. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  2042. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  2043. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  2044. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  2045. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  2046. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  2047. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  2048. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  2049. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  2050. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  2051. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  2052. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  2053. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  2054. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  2055. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  2056. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  2057. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  2058. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  2059. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  2060. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  2061. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  2062. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  2063. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  2064. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  2065. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  2066. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  2067. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  2068. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  2069. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  2070. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  2071. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  2072. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  2073. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  2074. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  2075. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  2076. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  2077. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  2078. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  2079. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  2080. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  2081. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  2082. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  2083. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  2084. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  2085. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  2086. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  2087. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  2088. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  2089. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  2090. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  2091. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  2092. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  2093. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  2094. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  2095. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  2096. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  2097. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  2098. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  2099. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  2100. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  2101. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  2102. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  2103. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  2104. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  2105. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  2106. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  2107. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  2108. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  2109. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  2110. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  2111. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  2112. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  2113. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  2114. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  2115. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  2116. ]
  2117. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  2118. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  2119. # ####################################################################################
  2120. # ####################### Shell SETUP ################################################
  2121. # ####################################################################################
  2122. # this will hold the TCL instance
  2123. self.tcl = None
  2124. self.init_tcl()
  2125. self.shell = FCShell(self, version=self.version)
  2126. self.shell._edit.set_model_data(self.myKeywords)
  2127. self.shell.setWindowIcon(self.ui.app_icon)
  2128. self.shell.setWindowTitle("FlatCAM Shell")
  2129. self.shell.resize(*self.defaults["global_shell_shape"])
  2130. self.shell.append_output("FlatCAM %s - " % self.version)
  2131. self.shell.append_output(_("Type >help< to get started\n\n"))
  2132. self.ui.shell_dock = QtWidgets.QDockWidget("FlatCAM TCL Shell")
  2133. self.ui.shell_dock.setObjectName('Shell_DockWidget')
  2134. self.ui.shell_dock.setWidget(self.shell)
  2135. self.ui.shell_dock.setAllowedAreas(QtCore.Qt.AllDockWidgetAreas)
  2136. self.ui.shell_dock.setFeatures(QtWidgets.QDockWidget.DockWidgetMovable |
  2137. QtWidgets.QDockWidget.DockWidgetFloatable |
  2138. QtWidgets.QDockWidget.DockWidgetClosable)
  2139. self.ui.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.ui.shell_dock)
  2140. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  2141. if self.defaults["global_shell_at_startup"]:
  2142. self.ui.shell_dock.show()
  2143. else:
  2144. self.ui.shell_dock.hide()
  2145. # ##################################################################################
  2146. # ###################### Tools and Plugins #########################################
  2147. # ##################################################################################
  2148. self.dblsidedtool = None
  2149. self.distance_tool = None
  2150. self.distance_min_tool = None
  2151. self.panelize_tool = None
  2152. self.film_tool = None
  2153. self.paste_tool = None
  2154. self.calculator_tool = None
  2155. self.rules_tool = None
  2156. self.sub_tool = None
  2157. self.move_tool = None
  2158. self.cutout_tool = None
  2159. self.ncclear_tool = None
  2160. self.optimal_tool = None
  2161. self.paint_tool = None
  2162. self.transform_tool = None
  2163. self.properties_tool = None
  2164. self.pdf_tool = None
  2165. self.image_tool = None
  2166. self.pcb_wizard_tool = None
  2167. self.cal_exc_tool = None
  2168. self.qrcode_tool = None
  2169. self.copper_thieving_tool = None
  2170. self.fiducial_tool = None
  2171. self.edrills_tool = None
  2172. self.align_objects_tool = None
  2173. self.punch_tool = None
  2174. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  2175. try:
  2176. self.install_tools()
  2177. except AttributeError as e:
  2178. log.debug("App.__init__() install tools() --> %s" % str(e))
  2179. # ##################################################################################
  2180. # ########################### SETUP RECENT ITEMS ###################################
  2181. # ##################################################################################
  2182. self.setup_recent_items()
  2183. # ##################################################################################
  2184. # ########################### BookMarks Manager ####################################
  2185. # ##################################################################################
  2186. # install Bookmark Manager and populate bookmarks in the Help -> Bookmarks
  2187. self.install_bookmarks()
  2188. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"])
  2189. # ##################################################################################
  2190. # ############################## Tools Database ####################################
  2191. # ##################################################################################
  2192. self.tools_db_tab = None
  2193. # ### System Font Parsing ###
  2194. # self.f_parse = ParseFont(self)
  2195. # self.parse_system_fonts()
  2196. # #####################################################################################
  2197. # ######################## Check for updates ##########################################
  2198. # #####################################################################################
  2199. # Separate thread (Not worker)
  2200. # Check for updates on startup but only if the user consent and the app is not in Beta version
  2201. if (self.beta is False or self.beta is None) and \
  2202. self.ui.general_defaults_form.general_app_group.version_check_cb.get_value() is True:
  2203. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  2204. self.thr2 = QtCore.QThread()
  2205. self.worker_task.emit({'fcn': self.version_check,
  2206. 'params': []})
  2207. self.thr2.start(QtCore.QThread.LowPriority)
  2208. # #####################################################################################
  2209. # ######################### Register files with FlatCAM; #############################
  2210. # ######################### It works only for Windows for now ########################
  2211. # #####################################################################################
  2212. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  2213. self.on_register_files()
  2214. # #####################################################################################
  2215. # ###################### Variables for global usage ###################################
  2216. # #####################################################################################
  2217. # hold the App units
  2218. self.units = 'MM'
  2219. # coordinates for relative position display
  2220. self.rel_point1 = (0, 0)
  2221. self.rel_point2 = (0, 0)
  2222. # variable to store coordinates
  2223. self.pos = (0, 0)
  2224. self.pos_canvas = (0, 0)
  2225. self.pos_jump = (0, 0)
  2226. # variable to store mouse coordinates
  2227. self.mouse = [0, 0]
  2228. # decide if we have a double click or single click
  2229. self.doubleclick = False
  2230. # store here the is_dragging value
  2231. self.event_is_dragging = False
  2232. # variable to store if a command is active (then the var is not None) and which one it is
  2233. self.command_active = None
  2234. # variable to store the status of moving selection action
  2235. # None value means that it's not an selection action
  2236. # True value = a selection from left to right
  2237. # False value = a selection from right to left
  2238. self.selection_type = None
  2239. # List to store the objects that are currently loaded in FlatCAM
  2240. # This list is updated on each object creation or object delete
  2241. self.all_objects_list = list()
  2242. # List to store the objects that are selected
  2243. self.sel_objects_list = list()
  2244. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  2245. self.key_modifiers = None
  2246. # Variable to hold the status of the axis
  2247. self.toggle_axis = True
  2248. # Variable to hold the status of the grid lines
  2249. self.toggle_grid_lines = True
  2250. # Variable to store the status of the fullscreen event
  2251. self.toggle_fscreen = False
  2252. # Variable to store the status of the code editor
  2253. self.toggle_codeeditor = False
  2254. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  2255. self.click_noproject = False
  2256. self.cursor = None
  2257. # Variable to store the GCODE that was edited
  2258. self.gcode_edited = ""
  2259. self.text_editor_tab = None
  2260. # reference for the self.ui.code_editor
  2261. self.reference_code_editor = None
  2262. self.script_code = ''
  2263. # if Preferences are changed in the Edit -> Preferences tab the value will be set to True
  2264. self.preferences_changed_flag = False
  2265. # if Tools DB are changed/edited in the Edit -> Tools Database tab the value will be set to True
  2266. self.tools_db_changed_flag = False
  2267. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  2268. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  2269. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'pho',
  2270. 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top', 'tsm']
  2271. self.exc_list = ['drd', 'drl', 'exc', 'ncd', 'tap', 'txt', 'xln']
  2272. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  2273. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ngc', 'ncp', 'out', 'ply', 'rol',
  2274. 'sbp', 'tap', 'xpi']
  2275. self.svg_list = ['svg']
  2276. self.dxf_list = ['dxf']
  2277. self.pdf_list = ['pdf']
  2278. self.prj_list = ['flatprj']
  2279. self.conf_list = ['flatconfig']
  2280. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  2281. # flag for polygons not cleared
  2282. self.poly_not_cleared = False
  2283. # VisPy visuals
  2284. self.isHovering = False
  2285. self.notHovering = True
  2286. # Window geometry
  2287. self.x_pos = None
  2288. self.y_pos = None
  2289. self.width = None
  2290. self.height = None
  2291. # when True, the app has to return from any thread
  2292. self.abort_flag = False
  2293. # set the value used in the Windows Title
  2294. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  2295. # this holds a widget that is installed in the Plot Area when View Source option is used
  2296. self.source_editor_tab = None
  2297. # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry
  2298. # VisPy visuals
  2299. if self.is_legacy is False:
  2300. try:
  2301. self.tool_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  2302. except AttributeError:
  2303. self.tool_shapes = None
  2304. else:
  2305. from flatcamGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  2306. self.tool_shapes = ShapeCollectionLegacy(obj=self, app=self, name="tool")
  2307. # used in the delayed shutdown self.start_delayed_quit() method
  2308. self.save_timer = None
  2309. # ###############################################################################
  2310. # ################# ADDING FlatCAM EDITORS section ##############################
  2311. # ###############################################################################
  2312. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  2313. # at the first launch of the App , the editors will not be functional.
  2314. try:
  2315. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  2316. except AttributeError:
  2317. pass
  2318. try:
  2319. self.exc_editor = FlatCAMExcEditor(self)
  2320. except AttributeError:
  2321. pass
  2322. try:
  2323. self.grb_editor = FlatCAMGrbEditor(self)
  2324. except AttributeError:
  2325. pass
  2326. self.log.debug("Finished adding FlatCAM Editor's.")
  2327. self.set_ui_title(name=_("New Project - Not saved"))
  2328. # disable the Excellon path optimizations made with Google OR-Tools if the app is run on a 32bit platform
  2329. current_platform = platform.architecture()[0]
  2330. if current_platform != '64bit':
  2331. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  2332. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.setDisabled(True)
  2333. # ###############################################################################
  2334. # ####################### Finished the CONSTRUCTOR ##############################
  2335. # ###############################################################################
  2336. App.log.debug("END of constructor. Releasing control.")
  2337. # #####################################################################################
  2338. # ########################## SHOW GUI #################################################
  2339. # #####################################################################################
  2340. # if the app is not started as headless, show it
  2341. if self.cmd_line_headless != 1:
  2342. if show_splash:
  2343. # finish the splash
  2344. self.splash.finish(self.ui)
  2345. mgui_settings = QSettings("Open Source", "FlatCAM")
  2346. if mgui_settings.contains("maximized_gui"):
  2347. maximized_ui = mgui_settings.value('maximized_gui', type=bool)
  2348. if maximized_ui is True:
  2349. self.ui.showMaximized()
  2350. else:
  2351. self.ui.show()
  2352. else:
  2353. self.ui.show()
  2354. if self.defaults["global_systray_icon"]:
  2355. self.trayIcon.show()
  2356. else:
  2357. log.warning("******************* RUNNING HEADLESS *******************")
  2358. # #####################################################################################
  2359. # ########################## START-UP ARGUMENTS #######################################
  2360. # #####################################################################################
  2361. # test if the program was started with a script as parameter
  2362. if self.cmd_line_shellvar:
  2363. try:
  2364. cnt = 0
  2365. command_tcl = 0
  2366. for i in self.cmd_line_shellvar.split(','):
  2367. if i is not None:
  2368. # noinspection PyBroadException
  2369. try:
  2370. command_tcl = eval(i)
  2371. except Exception:
  2372. command_tcl = i
  2373. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  2374. cnt += 1
  2375. # if there are Windows paths then replace the path separator with a Unix like one
  2376. if sys.platform == 'win32':
  2377. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  2378. self.shell._sysShell.exec_command(command_tcl_formatted, no_echo=True)
  2379. except Exception as ext:
  2380. print("ERROR: ", ext)
  2381. sys.exit(2)
  2382. if self.cmd_line_shellfile:
  2383. if self.cmd_line_headless != 1:
  2384. if self.ui.shell_dock.isHidden():
  2385. self.ui.shell_dock.show()
  2386. try:
  2387. with open(self.cmd_line_shellfile, "r") as myfile:
  2388. # if show_splash:
  2389. # self.splash.showMessage('%s: %ssec\n%s' % (
  2390. # _("Canvas initialization started.\n"
  2391. # "Canvas initialization finished in"), '%.2f' % self.used_time,
  2392. # _("Executing Tcl Script ...")),
  2393. # alignment=Qt.AlignBottom | Qt.AlignLeft,
  2394. # color=QtGui.QColor("gray"))
  2395. cmd_line_shellfile_text = myfile.read()
  2396. if self.cmd_line_headless != 1:
  2397. self.shell._sysShell.exec_command(cmd_line_shellfile_text)
  2398. else:
  2399. self.shell._sysShell.exec_command(cmd_line_shellfile_text, no_echo=True)
  2400. except Exception as ext:
  2401. print("ERROR: ", ext)
  2402. sys.exit(2)
  2403. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  2404. # the path/file_name must be enclosed in quotes if it contain spaces
  2405. if App.args:
  2406. self.args_at_startup.emit(App.args)
  2407. if self.old_defaults_found is True:
  2408. self.inform.emit('[WARNING_NOTCL] %s' % _("Found old default preferences files. "
  2409. "Please reboot the application to update."))
  2410. self.old_defaults_found = False
  2411. @staticmethod
  2412. def copy_and_overwrite(from_path, to_path):
  2413. """
  2414. From here:
  2415. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  2416. :param from_path: source path
  2417. :param to_path: destination path
  2418. :return: None
  2419. """
  2420. if os.path.exists(to_path):
  2421. shutil.rmtree(to_path)
  2422. try:
  2423. shutil.copytree(from_path, to_path)
  2424. except FileNotFoundError:
  2425. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\flatcamGUI\\VisPyData\\data'
  2426. shutil.copytree(from_new_path, to_path)
  2427. def on_startup_args(self, args, silent=False):
  2428. """
  2429. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  2430. :param silent: when True it will not print messages on Tcl Shell and/or status bar
  2431. :param args: a list containing the application args at startup
  2432. :return: None
  2433. """
  2434. if args is not None:
  2435. args_to_process = args
  2436. else:
  2437. args_to_process = App.args
  2438. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  2439. for argument in args_to_process:
  2440. if '.FlatPrj'.lower() in argument.lower():
  2441. try:
  2442. project_name = str(argument)
  2443. if project_name == "":
  2444. if silent is False:
  2445. self.inform.emit(_("Open cancelled."))
  2446. else:
  2447. # self.open_project(project_name)
  2448. run_from_arg = True
  2449. # self.worker_task.emit({'fcn': self.open_project,
  2450. # 'params': [project_name, run_from_arg]})
  2451. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  2452. except Exception as e:
  2453. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  2454. elif '.FlatConfig'.lower() in argument.lower():
  2455. try:
  2456. file_name = str(argument)
  2457. if file_name == "":
  2458. if silent is False:
  2459. self.inform.emit(_("Open Config file failed."))
  2460. else:
  2461. run_from_arg = True
  2462. # self.worker_task.emit({'fcn': self.open_config_file,
  2463. # 'params': [file_name, run_from_arg]})
  2464. self.open_config_file(file_name, run_from_arg=run_from_arg)
  2465. except Exception as e:
  2466. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  2467. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  2468. try:
  2469. file_name = str(argument)
  2470. if file_name == "":
  2471. if silent is False:
  2472. self.inform.emit(_("Open Script file failed."))
  2473. else:
  2474. if silent is False:
  2475. self.on_fileopenscript(name=file_name)
  2476. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  2477. self.on_filerunscript(name=file_name)
  2478. except Exception as e:
  2479. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  2480. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  2481. log.debug("App.on_startup_args() --> Quit event.")
  2482. sys.exit()
  2483. elif 'save'.lower() in argument.lower():
  2484. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  2485. self.save_defaults()
  2486. else:
  2487. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  2488. proc_arg = argument.lower()
  2489. for ext in exc_list:
  2490. proc_ext = ext.replace(' ', '')
  2491. proc_ext = '.%s' % proc_ext
  2492. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2493. file_name = str(argument)
  2494. if file_name == "":
  2495. if silent is False:
  2496. self.inform.emit(_("Open Excellon file failed."))
  2497. else:
  2498. self.on_fileopenexcellon(name=file_name)
  2499. return
  2500. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  2501. for ext in gco_list:
  2502. proc_ext = ext.replace(' ', '')
  2503. proc_ext = '.%s' % proc_ext
  2504. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2505. file_name = str(argument)
  2506. if file_name == "":
  2507. if silent is False:
  2508. self.inform.emit(_("Open GCode file failed."))
  2509. else:
  2510. self.on_fileopengcode(name=file_name)
  2511. return
  2512. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  2513. for ext in grb_list:
  2514. proc_ext = ext.replace(' ', '')
  2515. proc_ext = '.%s' % proc_ext
  2516. if proc_ext.lower() in proc_arg and proc_ext != '.':
  2517. file_name = str(argument)
  2518. if file_name == "":
  2519. if silent is False:
  2520. self.inform.emit(_("Open Gerber file failed."))
  2521. else:
  2522. self.on_fileopengerber(name=file_name)
  2523. return
  2524. # if it reached here without already returning then the app was registered with a file that it does not
  2525. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  2526. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  2527. # for arg in args_to_process:
  2528. # if 'FlatCAM.exe' in arg:
  2529. # continue
  2530. # else:
  2531. # sys.exit(2)
  2532. def set_ui_title(self, name):
  2533. """
  2534. Sets the title of the main window.
  2535. :param name: String that store the project path and project name
  2536. :return: None
  2537. """
  2538. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  2539. (self.version,
  2540. ('BETA' if self.beta else ''),
  2541. platform.architecture()[0],
  2542. self.engine,
  2543. name)
  2544. )
  2545. def on_app_restart(self):
  2546. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  2547. # be left in the SySTray
  2548. try:
  2549. self.trayIcon.hide()
  2550. except Exception:
  2551. pass
  2552. fcTranslate.restart_program(app=self)
  2553. def defaults_read_form(self):
  2554. """
  2555. Will read all the values in the Preferences GUI and update the defaults dictionary.
  2556. :return: None
  2557. """
  2558. for option in self.defaults_form_fields:
  2559. try:
  2560. self.defaults[option] = self.defaults_form_fields[option].get_value()
  2561. except Exception as e:
  2562. log.debug("App.defaults_read_form() --> %s" % str(e))
  2563. def defaults_write_form(self, factor=None, fl_units=None, source_dict=None):
  2564. """
  2565. Will set the values for all the GUI elements in Preferences GUI based on the values found in the
  2566. self.defaults dictionary.
  2567. :param factor: will apply a factor to the values that written in the GUI elements
  2568. :param fl_units: current measuring units in FlatCAM: Metric or Inch
  2569. :param source_dict: the repository of options, usually is the self.defaults
  2570. :return: None
  2571. """
  2572. options_storage = self.defaults if source_dict is None else source_dict
  2573. for option in options_storage:
  2574. if source_dict:
  2575. self.defaults_write_form_field(option, factor=factor, units=fl_units, defaults_dict=source_dict)
  2576. else:
  2577. self.defaults_write_form_field(option, factor=factor, units=fl_units)
  2578. # try:
  2579. # self.defaults_form_fields[option].set_value(self.defaults[option])
  2580. # except KeyError:
  2581. # #self.log.debug("defaults_write_form(): No field for: %s" % option)
  2582. # pass
  2583. def defaults_write_form_field(self, field, factor=None, units=None, defaults_dict=None):
  2584. """
  2585. Basically it is the worker in the self.defaults_write_form()
  2586. :param field: the GUI element in Preferences GUI to be updated
  2587. :param factor: factor to be applied to the field parameter
  2588. :param units: current FLatCAM measuring units
  2589. :param defaults_dict: the defaults storage
  2590. :return: None, it updates GUI elements
  2591. """
  2592. def_dict = self.defaults if defaults_dict is None else defaults_dict
  2593. try:
  2594. if factor is None:
  2595. if units is None:
  2596. self.defaults_form_fields[field].set_value(def_dict[field])
  2597. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2598. self.defaults_form_fields[field].set_value(def_dict[field])
  2599. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2600. self.defaults_form_fields[field].set_value(def_dict[field])
  2601. else:
  2602. if units is None:
  2603. self.defaults_form_fields[field].set_value(def_dict[field] * factor)
  2604. elif units == 'IN' and (field == 'global_gridx' or field == 'global_gridy'):
  2605. self.defaults_form_fields[field].set_value((def_dict[field] * factor))
  2606. elif units == 'MM' and (field == 'global_gridx' or field == 'global_gridy'):
  2607. self.defaults_form_fields[field].set_value((def_dict[field] * factor))
  2608. except KeyError:
  2609. pass
  2610. except AttributeError:
  2611. log.debug(field)
  2612. def clear_pool(self):
  2613. """
  2614. Clear the multiprocessing pool and calls garbage collector.
  2615. :return: None
  2616. """
  2617. self.pool.close()
  2618. self.pool = Pool()
  2619. self.pool_recreated.emit(self.pool)
  2620. gc.collect()
  2621. def install_tools(self):
  2622. """
  2623. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  2624. Instantiation of the Tools classes.
  2625. The order that the tools are installed is important as they can depend on each other install position.
  2626. :return: None
  2627. """
  2628. self.distance_tool = Distance(self)
  2629. self.distance_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance16.png'), pos=self.ui.menuedit,
  2630. before=self.ui.menueditorigin,
  2631. separator=False)
  2632. self.distance_min_tool = DistanceMin(self)
  2633. self.distance_min_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance_min16.png'),
  2634. pos=self.ui.menuedit,
  2635. before=self.ui.menueditorigin,
  2636. separator=True)
  2637. self.dblsidedtool = DblSidedTool(self)
  2638. self.dblsidedtool.install(icon=QtGui.QIcon(self.resource_location + '/doubleside16.png'), separator=False)
  2639. self.cal_exc_tool = ToolCalibration(self)
  2640. self.cal_exc_tool.install(icon=QtGui.QIcon(self.resource_location + '/calibrate_16.png'), pos=self.ui.menutool,
  2641. before=self.dblsidedtool.menuAction,
  2642. separator=False)
  2643. self.align_objects_tool = AlignObjects(self)
  2644. self.align_objects_tool.install(icon=QtGui.QIcon(self.resource_location + '/align16.png'), separator=False)
  2645. self.edrills_tool = ToolExtractDrills(self)
  2646. self.edrills_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), separator=True)
  2647. self.panelize_tool = Panelize(self)
  2648. self.panelize_tool.install(icon=QtGui.QIcon(self.resource_location + '/panelize16.png'))
  2649. self.film_tool = Film(self)
  2650. self.film_tool.install(icon=QtGui.QIcon(self.resource_location + '/film16.png'))
  2651. self.paste_tool = SolderPaste(self)
  2652. self.paste_tool.install(icon=QtGui.QIcon(self.resource_location + '/solderpastebis32.png'))
  2653. self.calculator_tool = ToolCalculator(self)
  2654. self.calculator_tool.install(icon=QtGui.QIcon(self.resource_location + '/calculator16.png'), separator=True)
  2655. self.sub_tool = ToolSub(self)
  2656. self.sub_tool.install(icon=QtGui.QIcon(self.resource_location + '/sub32.png'),
  2657. pos=self.ui.menutool, separator=True)
  2658. self.rules_tool = RulesCheck(self)
  2659. self.rules_tool.install(icon=QtGui.QIcon(self.resource_location + '/rules32.png'),
  2660. pos=self.ui.menutool, separator=False)
  2661. self.optimal_tool = ToolOptimal(self)
  2662. self.optimal_tool.install(icon=QtGui.QIcon(self.resource_location + '/open_excellon32.png'),
  2663. pos=self.ui.menutool, separator=True)
  2664. self.move_tool = ToolMove(self)
  2665. self.move_tool.install(icon=QtGui.QIcon(self.resource_location + '/move16.png'), pos=self.ui.menuedit,
  2666. before=self.ui.menueditorigin, separator=True)
  2667. self.cutout_tool = CutOut(self)
  2668. self.cutout_tool.install(icon=QtGui.QIcon(self.resource_location + '/cut16_bis.png'), pos=self.ui.menutool,
  2669. before=self.sub_tool.menuAction)
  2670. self.ncclear_tool = NonCopperClear(self)
  2671. self.ncclear_tool.install(icon=QtGui.QIcon(self.resource_location + '/ncc16.png'), pos=self.ui.menutool,
  2672. before=self.sub_tool.menuAction, separator=True)
  2673. self.paint_tool = ToolPaint(self)
  2674. self.paint_tool.install(icon=QtGui.QIcon(self.resource_location + '/paint16.png'), pos=self.ui.menutool,
  2675. before=self.sub_tool.menuAction, separator=True)
  2676. self.copper_thieving_tool = ToolCopperThieving(self)
  2677. self.copper_thieving_tool.install(icon=QtGui.QIcon(self.resource_location + '/copperfill32.png'),
  2678. pos=self.ui.menutool)
  2679. self.fiducial_tool = ToolFiducials(self)
  2680. self.fiducial_tool.install(icon=QtGui.QIcon(self.resource_location + '/fiducials_32.png'),
  2681. pos=self.ui.menutool)
  2682. self.qrcode_tool = QRCode(self)
  2683. self.qrcode_tool.install(icon=QtGui.QIcon(self.resource_location + '/qrcode32.png'),
  2684. pos=self.ui.menutool)
  2685. self.punch_tool = ToolPunchGerber(self)
  2686. self.punch_tool.install(icon=QtGui.QIcon(self.resource_location + '/punch32.png'), pos=self.ui.menutool)
  2687. self.transform_tool = ToolTransform(self)
  2688. self.transform_tool.install(icon=QtGui.QIcon(self.resource_location + '/transform.png'),
  2689. pos=self.ui.menuoptions, separator=True)
  2690. self.properties_tool = Properties(self)
  2691. self.properties_tool.install(icon=QtGui.QIcon(self.resource_location + '/properties32.png'),
  2692. pos=self.ui.menuoptions)
  2693. self.pdf_tool = ToolPDF(self)
  2694. self.pdf_tool.install(icon=QtGui.QIcon(self.resource_location + '/pdf32.png'),
  2695. pos=self.ui.menufileimport,
  2696. separator=True)
  2697. self.image_tool = ToolImage(self)
  2698. self.image_tool.install(icon=QtGui.QIcon(self.resource_location + '/image32.png'),
  2699. pos=self.ui.menufileimport,
  2700. separator=True)
  2701. self.pcb_wizard_tool = PcbWizard(self)
  2702. self.pcb_wizard_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill32.png'),
  2703. pos=self.ui.menufileimport)
  2704. self.log.debug("Tools are installed.")
  2705. def remove_tools(self):
  2706. """
  2707. Will remove all the actions in the Tool menu.
  2708. :return: None
  2709. """
  2710. for act in self.ui.menutool.actions():
  2711. self.ui.menutool.removeAction(act)
  2712. def init_tools(self):
  2713. """
  2714. Initialize the Tool tab in the notebook side of the central widget.
  2715. Remove the actions in the Tools menu.
  2716. Instantiate again the FlatCAM tools (plugins).
  2717. All this is required when changing the layout: standard, compact etc.
  2718. :return: None
  2719. """
  2720. log.debug("init_tools()")
  2721. # delete the data currently in the Tools Tab and the Tab itself
  2722. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  2723. if widget is not None:
  2724. widget.deleteLater()
  2725. self.ui.notebook.removeTab(2)
  2726. # rebuild the Tools Tab
  2727. self.ui.tool_tab = QtWidgets.QWidget()
  2728. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  2729. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  2730. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  2731. self.ui.tool_scroll_area = VerticalScrollArea()
  2732. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  2733. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  2734. # first remove all of them
  2735. self.remove_tools()
  2736. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  2737. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon(self.resource_location + '/shell16.png'),
  2738. '&Command Line\tS')
  2739. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  2740. # third install all of them
  2741. try:
  2742. self.install_tools()
  2743. except AttributeError:
  2744. pass
  2745. self.log.debug("Tools are initialized.")
  2746. # def parse_system_fonts(self):
  2747. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  2748. # 'params': []})
  2749. def connect_toolbar_signals(self):
  2750. """
  2751. Reconnect the signals to the actions in the toolbar.
  2752. This has to be done each time after the FlatCAM tools are removed/installed.
  2753. :return: None
  2754. """
  2755. # Toolbar
  2756. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  2757. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  2758. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  2759. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  2760. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  2761. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  2762. self.ui.replot_btn.triggered.connect(self.plot_all)
  2763. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  2764. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  2765. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  2766. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  2767. self.ui.newgrb_btn.triggered.connect(self.new_gerber_object)
  2768. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  2769. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  2770. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  2771. self.ui.copy_btn.triggered.connect(self.on_copy_command)
  2772. self.ui.delete_btn.triggered.connect(self.on_delete)
  2773. self.ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  2774. self.ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  2775. self.ui.origin_btn.triggered.connect(self.on_set_origin)
  2776. self.ui.jmp_btn.triggered.connect(self.on_jump_to)
  2777. self.ui.locate_btn.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  2778. self.ui.shell_btn.triggered.connect(self.on_toggle_shell)
  2779. self.ui.new_script_btn.triggered.connect(self.on_filenewscript)
  2780. self.ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  2781. self.ui.run_script_btn.triggered.connect(self.on_filerunscript)
  2782. # Tools Toolbar Signals
  2783. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  2784. self.ui.cal_btn.triggered.connect(lambda: self.cal_exc_tool.run(toggle=True))
  2785. self.ui.align_btn.triggered.connect(lambda: self.align_objects_tool.run(toggle=True))
  2786. self.ui.extract_btn.triggered.connect(lambda: self.edrills_tool.run(toggle=True))
  2787. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  2788. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  2789. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  2790. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  2791. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  2792. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  2793. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  2794. self.ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  2795. self.ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  2796. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  2797. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  2798. self.ui.qrcode_btn.triggered.connect(lambda: self.qrcode_tool.run(toggle=True))
  2799. self.ui.copperfill_btn.triggered.connect(lambda: self.copper_thieving_tool.run(toggle=True))
  2800. self.ui.fiducials_btn.triggered.connect(lambda: self.fiducial_tool.run(toggle=True))
  2801. self.ui.punch_btn.triggered.connect(lambda: self.punch_tool.run(toggle=True))
  2802. def object2editor(self):
  2803. """
  2804. Send the current Geometry or Excellon object (if any) into the it's editor.
  2805. :return: None
  2806. """
  2807. self.report_usage("object2editor()")
  2808. # disable the objects menu as it may interfere with the Editors
  2809. self.ui.menuobjects.setDisabled(True)
  2810. edited_object = self.collection.get_active()
  2811. if isinstance(edited_object, FlatCAMGerber) or isinstance(edited_object, FlatCAMGeometry) or \
  2812. isinstance(edited_object, FlatCAMExcellon):
  2813. pass
  2814. else:
  2815. self.inform.emit('[WARNING_NOTCL] %s' % _("Select a Geometry, Gerber or Excellon Object to edit."))
  2816. return
  2817. if isinstance(edited_object, FlatCAMGeometry):
  2818. # store the Geometry Editor Toolbar visibility before entering in the Editor
  2819. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  2820. # we set the notebook to hidden
  2821. # self.ui.splitter.setSizes([0, 1])
  2822. if edited_object.multigeo is True:
  2823. sel_rows = [item.row() for item in edited_object.ui.geo_tools_table.selectedItems()]
  2824. if len(sel_rows) > 1:
  2825. self.inform.emit('[WARNING_NOTCL] %s' %
  2826. _("Simultaneous editing of tools geometry in a MultiGeo Geometry "
  2827. "is not possible.\n"
  2828. "Edit only one geometry at a time."))
  2829. # determine the tool dia of the selected tool
  2830. selected_tooldia = float(edited_object.ui.geo_tools_table.item(sel_rows[0], 1).text())
  2831. # now find the key in the edited_object.tools that has this tooldia
  2832. multi_tool = 1
  2833. for tool in edited_object.tools:
  2834. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  2835. multi_tool = tool
  2836. break
  2837. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  2838. else:
  2839. self.geo_editor.edit_fcgeometry(edited_object)
  2840. # set call source to the Editor we go into
  2841. self.call_source = 'geo_editor'
  2842. elif isinstance(edited_object, FlatCAMExcellon):
  2843. # store the Excellon Editor Toolbar visibility before entering in the Editor
  2844. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  2845. if self.ui.splitter.sizes()[0] == 0:
  2846. self.ui.splitter.setSizes([1, 1])
  2847. self.exc_editor.edit_fcexcellon(edited_object)
  2848. # set call source to the Editor we go into
  2849. self.call_source = 'exc_editor'
  2850. elif isinstance(edited_object, FlatCAMGerber):
  2851. # store the Gerber Editor Toolbar visibility before entering in the Editor
  2852. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  2853. if self.ui.splitter.sizes()[0] == 0:
  2854. self.ui.splitter.setSizes([1, 1])
  2855. self.grb_editor.edit_fcgerber(edited_object)
  2856. # set call source to the Editor we go into
  2857. self.call_source = 'grb_editor'
  2858. # reset the following variables so the UI is built again after edit
  2859. edited_object.ui_build = False
  2860. edited_object.build_aperture_storage = False
  2861. # make sure that we can't select another object while in Editor Mode:
  2862. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  2863. self.ui.project_frame.setDisabled(True)
  2864. # delete any selection shape that might be active as they are not relevant in Editor
  2865. self.delete_selection_shape()
  2866. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  2867. self.ui.plot_tab_area.protectTab(0)
  2868. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor is activated ..."))
  2869. self.should_we_save = True
  2870. def editor2object(self, cleanup=None):
  2871. """
  2872. Transfers the Geometry or Excellon from it's editor to the current object.
  2873. :return: None
  2874. """
  2875. self.report_usage("editor2object()")
  2876. # re-enable the objects menu that was disabled on entry in Editor mode
  2877. self.ui.menuobjects.setDisabled(False)
  2878. # do not update a geometry or excellon object unless it comes out of an editor
  2879. if self.call_source != 'app':
  2880. edited_obj = self.collection.get_active()
  2881. if cleanup is None:
  2882. msgbox = QtWidgets.QMessageBox()
  2883. msgbox.setText(_("Do you want to save the edited object?"))
  2884. msgbox.setWindowTitle(_("Close Editor"))
  2885. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  2886. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2887. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2888. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2889. msgbox.setDefaultButton(bt_yes)
  2890. msgbox.exec_()
  2891. response = msgbox.clickedButton()
  2892. if response == bt_yes:
  2893. # clean the Tools Tab
  2894. self.ui.tool_scroll_area.takeWidget()
  2895. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2896. self.ui.notebook.setTabText(2, "Tool")
  2897. if isinstance(edited_obj, FlatCAMGeometry):
  2898. obj_type = "Geometry"
  2899. if cleanup is None:
  2900. self.geo_editor.update_fcgeometry(edited_obj)
  2901. # self.geo_editor.update_options(edited_obj)
  2902. self.geo_editor.deactivate()
  2903. # restore GUI to the Selected TAB
  2904. # Remove anything else in the GUI
  2905. self.ui.tool_scroll_area.takeWidget()
  2906. # update the geo object options so it is including the bounding box values
  2907. try:
  2908. xmin, ymin, xmax, ymax = edited_obj.bounds()
  2909. edited_obj.options['xmin'] = xmin
  2910. edited_obj.options['ymin'] = ymin
  2911. edited_obj.options['xmax'] = xmax
  2912. edited_obj.options['ymax'] = ymax
  2913. except AttributeError as e:
  2914. self.inform.emit('[WARNING] %s' % _("Object empty after edit."))
  2915. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  2916. edited_obj.build_ui()
  2917. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  2918. elif isinstance(edited_obj, FlatCAMGerber):
  2919. obj_type = "Gerber"
  2920. if cleanup is None:
  2921. self.grb_editor.update_fcgerber()
  2922. self.grb_editor.update_options(edited_obj)
  2923. self.grb_editor.deactivate_grb_editor()
  2924. # delete the old object (the source object) if it was an empty one
  2925. try:
  2926. if len(edited_obj.solid_geometry) == 0:
  2927. old_name = edited_obj.options['name']
  2928. self.collection.set_active(old_name)
  2929. self.collection.delete_active()
  2930. except TypeError:
  2931. # if the solid_geometry is a single Polygon the len() will not work
  2932. # in any case, falling here means that we have something in the solid_geometry, even if only
  2933. # a single Polygon, therefore we pass this
  2934. pass
  2935. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  2936. # restore GUI to the Selected TAB
  2937. # Remove anything else in the GUI
  2938. self.ui.selected_scroll_area.takeWidget()
  2939. elif isinstance(edited_obj, FlatCAMExcellon):
  2940. obj_type = "Excellon"
  2941. if cleanup is None:
  2942. self.exc_editor.update_fcexcellon(edited_obj)
  2943. # self.exc_editor.update_options(edited_obj)
  2944. self.exc_editor.deactivate()
  2945. # restore GUI to the Selected TAB
  2946. # Remove anything else in the GUI
  2947. self.ui.tool_scroll_area.takeWidget()
  2948. # delete the old object (the source object) if it was an empty one
  2949. if len(edited_obj.drills) == 0 and len(edited_obj.slots) == 0:
  2950. old_name = edited_obj.options['name']
  2951. self.collection.delete_by_name(name=old_name)
  2952. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  2953. else:
  2954. self.inform.emit('[WARNING_NOTCL] %s' %
  2955. _("Select a Gerber, Geometry or Excellon Object to update."))
  2956. return
  2957. self.inform.emit('[selected] %s %s' % (obj_type, _("is updated, returning to App...")))
  2958. elif response == bt_no:
  2959. # clean the Tools Tab
  2960. self.ui.tool_scroll_area.takeWidget()
  2961. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  2962. self.ui.notebook.setTabText(2, "Tool")
  2963. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor exited. Editor content was not saved."))
  2964. if isinstance(edited_obj, FlatCAMGeometry):
  2965. self.geo_editor.deactivate()
  2966. edited_obj.build_ui()
  2967. elif isinstance(edited_obj, FlatCAMGerber):
  2968. self.grb_editor.deactivate_grb_editor()
  2969. edited_obj.build_ui()
  2970. elif isinstance(edited_obj, FlatCAMExcellon):
  2971. self.exc_editor.deactivate()
  2972. edited_obj.build_ui()
  2973. else:
  2974. self.inform.emit('[WARNING_NOTCL] %s' %
  2975. _("Select a Gerber, Geometry or Excellon Object to update."))
  2976. return
  2977. elif response == bt_cancel:
  2978. return
  2979. # edited_obj.set_ui(edited_obj.ui_type(decimals=self.decimals))
  2980. # edited_obj.build_ui()
  2981. # Switch notebook to Selected page
  2982. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  2983. else:
  2984. if isinstance(edited_obj, FlatCAMGeometry):
  2985. self.geo_editor.deactivate()
  2986. elif isinstance(edited_obj, FlatCAMGerber):
  2987. self.grb_editor.deactivate_grb_editor()
  2988. elif isinstance(edited_obj, FlatCAMExcellon):
  2989. self.exc_editor.deactivate()
  2990. else:
  2991. self.inform.emit('[WARNING_NOTCL] %s' %
  2992. _("Select a Gerber, Geometry or Excellon Object to update."))
  2993. return
  2994. # if notebook is hidden we show it
  2995. if self.ui.splitter.sizes()[0] == 0:
  2996. self.ui.splitter.setSizes([1, 1])
  2997. # restore the call_source to app
  2998. self.call_source = 'app'
  2999. edited_obj.plot()
  3000. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  3001. self.ui.plot_tab_area.protectTab(0)
  3002. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  3003. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  3004. self.ui.project_frame.setDisabled(False)
  3005. def get_last_folder(self):
  3006. """
  3007. Get the folder path from where the last file was opened.
  3008. :return: String, last opened folder path
  3009. """
  3010. return self.defaults["global_last_folder"]
  3011. def get_last_save_folder(self):
  3012. """
  3013. Get the folder path from where the last file was saved.
  3014. :return: String, last saved folder path
  3015. """
  3016. loc = self.defaults["global_last_save_folder"]
  3017. if loc is None:
  3018. loc = self.defaults["global_last_folder"]
  3019. if loc is None:
  3020. loc = os.path.dirname(__file__)
  3021. return loc
  3022. def report_usage(self, resource):
  3023. """
  3024. Increments usage counter for the given resource
  3025. in self.defaults['global_stats'].
  3026. :param resource: Name of the resource.
  3027. :return: None
  3028. """
  3029. if resource in self.defaults['global_stats']:
  3030. self.defaults['global_stats'][resource] += 1
  3031. else:
  3032. self.defaults['global_stats'][resource] = 1
  3033. def init_tcl(self):
  3034. """
  3035. Initialize the TCL Shell. A dock widget that holds the GUI interface to the FlatCAM command line.
  3036. :return: None
  3037. """
  3038. if hasattr(self, 'tcl') and self.tcl is not None:
  3039. # self.tcl = None
  3040. # TODO we need to clean non default variables and procedures here
  3041. # new object cannot be used here as it will not remember values created for next passes,
  3042. # because tcl was execudted in old instance of TCL
  3043. pass
  3044. else:
  3045. self.tcl = tk.Tcl()
  3046. self.setup_shell()
  3047. self.log.debug("TCL Shell has been initialized.")
  3048. # TODO: This shouldn't be here.
  3049. class TclErrorException(Exception):
  3050. """
  3051. this exception is defined here, to be able catch it if we successfully handle all errors from shell command
  3052. """
  3053. pass
  3054. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  3055. """
  3056. Shows a message on the FlatCAM Shell
  3057. :param msg: Message to display.
  3058. :param show: Opens the shell.
  3059. :param error: Shows the message as an error.
  3060. :param warning: Shows the message as an warning.
  3061. :param success: Shows the message as an success.
  3062. :param selected: Indicate that something was selected on canvas
  3063. :return: None
  3064. """
  3065. if show:
  3066. self.ui.shell_dock.show()
  3067. try:
  3068. if error:
  3069. self.shell.append_error(msg + "\n")
  3070. elif warning:
  3071. self.shell.append_warning(msg + "\n")
  3072. elif success:
  3073. self.shell.append_success(msg + "\n")
  3074. elif selected:
  3075. self.shell.append_selected(msg + "\n")
  3076. else:
  3077. self.shell.append_output(msg + "\n")
  3078. except AttributeError:
  3079. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  3080. def raise_tcl_unknown_error(self, unknownException):
  3081. """
  3082. Raise exception if is different type than TclErrorException
  3083. this is here mainly to show unknown errors inside TCL shell console.
  3084. :param unknownException:
  3085. :return:
  3086. """
  3087. if not isinstance(unknownException, self.TclErrorException):
  3088. self.raise_tcl_error("Unknown error: %s" % str(unknownException))
  3089. else:
  3090. raise unknownException
  3091. def display_tcl_error(self, error, error_info=None):
  3092. """
  3093. Escape bracket [ with '\' otherwise there is error
  3094. "ERROR: missing close-bracket" instead of real error
  3095. :param error: it may be text or exception
  3096. :param error_info: Some informations about the error
  3097. :return: None
  3098. """
  3099. if isinstance(error, Exception):
  3100. exc_type, exc_value, exc_traceback = error_info
  3101. if not isinstance(error, self.TclErrorException):
  3102. show_trace = 1
  3103. else:
  3104. show_trace = int(self.defaults['global_verbose_error_level'])
  3105. if show_trace > 0:
  3106. trc = traceback.format_list(traceback.extract_tb(exc_traceback))
  3107. trc_formated = []
  3108. for a in reversed(trc):
  3109. trc_formated.append(a.replace(" ", " > ").replace("\n", ""))
  3110. text = "%s\nPython traceback: %s\n%s" % (exc_value, exc_type, "\n".join(trc_formated))
  3111. else:
  3112. text = "%s" % error
  3113. else:
  3114. text = error
  3115. text = text.replace('[', '\\[').replace('"', '\\"')
  3116. self.tcl.eval('return -code error "%s"' % text)
  3117. def raise_tcl_error(self, text):
  3118. """
  3119. This method pass exception from python into TCL as error, so we get stacktrace and reason
  3120. :param text: text of error
  3121. :return: raise exception
  3122. """
  3123. self.display_tcl_error(text)
  3124. raise self.TclErrorException(text)
  3125. def exec_command(self, text, no_echo=False):
  3126. """
  3127. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  3128. Also handles execution in separated threads
  3129. :param text: FlatCAM TclCommand with parameters
  3130. :param no_echo: If True it will not try to print to the Shell because most likely the shell is hidden and it
  3131. will create crashes of the _Expandable_Edit widget
  3132. :return: output if there was any
  3133. """
  3134. self.report_usage('exec_command')
  3135. result = self.exec_command_test(text, False, no_echo=no_echo)
  3136. # MS: added this method call so the geometry is updated once the TCL command is executed
  3137. # if no_plot is None:
  3138. # self.plot_all()
  3139. return result
  3140. def exec_command_test(self, text, reraise=True, no_echo=False):
  3141. """
  3142. Same as exec_command(...) with additional control over exceptions.
  3143. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  3144. :param text: Input command
  3145. :param reraise: Re-raise TclError exceptions in Python (mostly for unittests).
  3146. :param no_echo: If True it will not try to print to the Shell because most likely the shell is hidden and it
  3147. will create crashes of the _Expandable_Edit widget
  3148. :return: Output from the command
  3149. """
  3150. tcl_command_string = str(text)
  3151. try:
  3152. if no_echo is False:
  3153. self.shell.open_processing() # Disables input box.
  3154. result = self.tcl.eval(str(tcl_command_string))
  3155. if result != 'None' and no_echo is False:
  3156. self.shell.append_output(result + '\n')
  3157. except tk.TclError as e:
  3158. # This will display more precise answer if something in TCL shell fails
  3159. result = self.tcl.eval("set errorInfo")
  3160. self.log.error("Exec command Exception: %s" % (result + '\n'))
  3161. if no_echo is False:
  3162. self.shell.append_error('ERROR: ' + result + '\n')
  3163. # Show error in console and just return or in test raise exception
  3164. if reraise:
  3165. raise e
  3166. finally:
  3167. if no_echo is False:
  3168. self.shell.close_processing()
  3169. pass
  3170. return result
  3171. # """
  3172. # Code below is unsused. Saved for later.
  3173. # """
  3174. # parts = re.findall(r'([\w\\:\.]+|".*?")+', text)
  3175. # parts = [p.replace('\n', '').replace('"', '') for p in parts]
  3176. # self.log.debug(parts)
  3177. # try:
  3178. # if parts[0] not in commands:
  3179. # self.shell.append_error("Unknown command\n")
  3180. # return
  3181. #
  3182. # #import inspect
  3183. # #inspect.getargspec(someMethod)
  3184. # if (type(commands[parts[0]]["params"]) is not list and len(parts)-1 != commands[parts[0]]["params"]) or \
  3185. # (type(commands[parts[0]]["params"]) is list and len(parts)-1 not in commands[parts[0]]["params"]):
  3186. # self.shell.append_error(
  3187. # "Command %s takes %d arguments. %d given.\n" %
  3188. # (parts[0], commands[parts[0]]["params"], len(parts)-1)
  3189. # )
  3190. # return
  3191. #
  3192. # cmdfcn = commands[parts[0]]["fcn"]
  3193. # cmdconv = commands[parts[0]]["converters"]
  3194. # if len(parts) - 1 > 0:
  3195. # retval = cmdfcn(*[cmdconv[i](parts[i + 1]) for i in range(len(parts)-1)])
  3196. # else:
  3197. # retval = cmdfcn()
  3198. # retfcn = commands[parts[0]]["retfcn"]
  3199. # if retval and retfcn(retval):
  3200. # self.shell.append_output(retfcn(retval) + "\n")
  3201. #
  3202. # except Exception as e:
  3203. # #self.shell.append_error(''.join(traceback.format_exc()))
  3204. # #self.shell.append_error("?\n")
  3205. # self.shell.append_error(str(e) + "\n")
  3206. def info(self, msg):
  3207. """
  3208. Informs the user. Normally on the status bar, optionally
  3209. also on the shell.
  3210. :param msg: Text to write.
  3211. :return: None
  3212. """
  3213. # Type of message in brackets at the beginning of the message.
  3214. match = re.search("\[([^\]]+)\](.*)", msg)
  3215. if match:
  3216. level = match.group(1)
  3217. msg_ = match.group(2)
  3218. self.ui.fcinfo.set_status(str(msg_), level=level)
  3219. if level.lower() == "error":
  3220. self.shell_message(msg, error=True, show=True)
  3221. elif level.lower() == "warning":
  3222. self.shell_message(msg, warning=True, show=True)
  3223. elif level.lower() == "error_notcl":
  3224. self.shell_message(msg, error=True, show=False)
  3225. elif level.lower() == "warning_notcl":
  3226. self.shell_message(msg, warning=True, show=False)
  3227. elif level.lower() == "success":
  3228. self.shell_message(msg, success=True, show=False)
  3229. elif level.lower() == "selected":
  3230. self.shell_message(msg, selected=True, show=False)
  3231. else:
  3232. self.shell_message(msg, show=False)
  3233. else:
  3234. self.ui.fcinfo.set_status(str(msg), level="info")
  3235. # make sure that if the message is to clear the infobar with a space
  3236. # is not printed over and over on the shell
  3237. if msg != '':
  3238. self.shell_message(msg)
  3239. def restore_toolbar_view(self):
  3240. """
  3241. Some toolbars may be hidden by user and here we restore the state of the toolbars visibility that
  3242. was saved in the defaults dictionary.
  3243. :return: None
  3244. """
  3245. tb = self.defaults["global_toolbar_view"]
  3246. if tb & 1:
  3247. self.ui.toolbarfile.setVisible(True)
  3248. else:
  3249. self.ui.toolbarfile.setVisible(False)
  3250. if tb & 2:
  3251. self.ui.toolbargeo.setVisible(True)
  3252. else:
  3253. self.ui.toolbargeo.setVisible(False)
  3254. if tb & 4:
  3255. self.ui.toolbarview.setVisible(True)
  3256. else:
  3257. self.ui.toolbarview.setVisible(False)
  3258. if tb & 8:
  3259. self.ui.toolbartools.setVisible(True)
  3260. else:
  3261. self.ui.toolbartools.setVisible(False)
  3262. if tb & 16:
  3263. self.ui.exc_edit_toolbar.setVisible(True)
  3264. else:
  3265. self.ui.exc_edit_toolbar.setVisible(False)
  3266. if tb & 32:
  3267. self.ui.geo_edit_toolbar.setVisible(True)
  3268. else:
  3269. self.ui.geo_edit_toolbar.setVisible(False)
  3270. if tb & 64:
  3271. self.ui.grb_edit_toolbar.setVisible(True)
  3272. else:
  3273. self.ui.grb_edit_toolbar.setVisible(False)
  3274. if tb & 128:
  3275. self.ui.snap_toolbar.setVisible(True)
  3276. else:
  3277. self.ui.snap_toolbar.setVisible(False)
  3278. if tb & 256:
  3279. self.ui.toolbarshell.setVisible(True)
  3280. else:
  3281. self.ui.toolbarshell.setVisible(False)
  3282. def load_defaults(self, filename):
  3283. """
  3284. Loads the aplication's default settings from current_defaults.FlatConfig into
  3285. ``self.defaults``.
  3286. :return: None
  3287. """
  3288. try:
  3289. f = open(self.data_path + "/" + filename + ".FlatConfig")
  3290. options = f.read()
  3291. f.close()
  3292. except IOError:
  3293. self.log.error("Could not load defaults file.")
  3294. self.inform.emit('[ERROR] %s' % _("Could not load defaults file."))
  3295. # in case the defaults file can't be loaded, show all toolbars
  3296. self.defaults["global_toolbar_view"] = 511
  3297. return
  3298. try:
  3299. defaults = json.loads(options)
  3300. except Exception:
  3301. # in case the defaults file can't be loaded, show all toolbars
  3302. self.defaults["global_toolbar_view"] = 511
  3303. e = sys.exc_info()[0]
  3304. App.log.error(str(e))
  3305. self.inform.emit('[ERROR] %s' % _("Failed to parse defaults file."))
  3306. return
  3307. if defaults:
  3308. if 'version' not in defaults or defaults['version'] != self.defaults['version']:
  3309. for k, v in defaults.items():
  3310. if k in self.defaults and k != 'version':
  3311. self.defaults[k] = v
  3312. # delete old factory defaults
  3313. try:
  3314. fact_def_file_path = os.path.join(self.data_path, 'factory_defaults.FlatConfig')
  3315. os.chmod(fact_def_file_path, stat.S_IRWXO | stat.S_IWRITE | stat.S_IWGRP)
  3316. os.remove(fact_def_file_path)
  3317. # recreate a new factory defaults file and save the factory defaults data into it
  3318. f_f_def_s = open(self.data_path + "/factory_defaults.FlatConfig", "w")
  3319. json.dump(self.defaults, f_f_def_s, default=to_dict, indent=2, sort_keys=True)
  3320. f_f_def_s.close()
  3321. # and then make the factory_defaults.FlatConfig file read_only
  3322. # so it can't be modified after creation.
  3323. os.chmod(fact_def_file_path, S_IREAD | S_IRGRP | S_IROTH)
  3324. except Exception as e:
  3325. log.debug("App.load_defaults() -> deleting old factory defaults file -> %s" % str(e))
  3326. self.old_defaults_found = True
  3327. else:
  3328. self.old_defaults_found = False
  3329. self.defaults.update(defaults)
  3330. log.debug("FlatCAM defaults loaded from: %s" % filename)
  3331. def on_restore_defaults_preferences(self):
  3332. """
  3333. Loads the application's factory default settings from factory_defaults.FlatConfig into
  3334. ``self.defaults``.
  3335. :return: None
  3336. """
  3337. App.log.debug("App.on_restore_defaults_preferences()")
  3338. filename = self.data_path + '/factory_defaults.FlatConfig'
  3339. if filename == "":
  3340. self.inform.emit('[WARNING_NOTCL] %s' % _("Preferences default restore was cancelled."))
  3341. else:
  3342. try:
  3343. f = open(filename)
  3344. options = f.read()
  3345. f.close()
  3346. except IOError:
  3347. self.log.error("Could not load factory defaults file.")
  3348. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load factory defaults file."))
  3349. return
  3350. try:
  3351. defaults_from_file = json.loads(options)
  3352. except Exception:
  3353. e = sys.exc_info()[0]
  3354. App.log.error(str(e))
  3355. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse factory defaults file."))
  3356. return
  3357. self.defaults.update(defaults_from_file)
  3358. # update the dict that is used to restore the values in the defaults form if Cancel is clicked in the
  3359. # Preferences window
  3360. self.current_defaults.update(defaults_from_file)
  3361. self.on_preferences_edited()
  3362. self.inform.emit('[success] %s' % _("Preferences default values are restored."))
  3363. def on_import_preferences(self):
  3364. """
  3365. Loads the application default settings from a saved file into
  3366. ``self.defaults`` dictionary.
  3367. :return: None
  3368. """
  3369. self.report_usage("on_import_preferences")
  3370. App.log.debug("App.on_import_preferences()")
  3371. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  3372. try:
  3373. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  3374. directory=self.data_path,
  3375. filter=filter_)
  3376. except TypeError:
  3377. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  3378. filter=filter_)
  3379. filename = str(filename)
  3380. if filename == "":
  3381. self.inform.emit('[WARNING_NOTCL] %s' % _("FlatCAM preferences import cancelled."))
  3382. else:
  3383. try:
  3384. f = open(filename)
  3385. options = f.read()
  3386. f.close()
  3387. except IOError:
  3388. self.log.error("Could not load defaults file.")
  3389. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load defaults file."))
  3390. return
  3391. try:
  3392. defaults_from_file = json.loads(options)
  3393. except Exception:
  3394. e = sys.exc_info()[0]
  3395. App.log.error(str(e))
  3396. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse defaults file."))
  3397. return
  3398. self.defaults.update(defaults_from_file)
  3399. # update the dict that is used to restore the values in the defaults form if Cancel is clicked in the
  3400. # Preferences window
  3401. self.current_defaults.update(defaults_from_file)
  3402. self.on_preferences_edited()
  3403. self.inform.emit('[success] %s: %s' % (_("Imported Defaults from"), filename))
  3404. def on_export_preferences(self):
  3405. """
  3406. Save the defaults dictionary to a file.
  3407. :return: None
  3408. """
  3409. self.report_usage("on_export_preferences")
  3410. App.log.debug("on_export_preferences()")
  3411. defaults_file_content = None
  3412. self.date = str(datetime.today()).rpartition('.')[0]
  3413. self.date = ''.join(c for c in self.date if c not in ':-')
  3414. self.date = self.date.replace(' ', '_')
  3415. filter__ = "Config File (*.FlatConfig);;All Files (*.*)"
  3416. try:
  3417. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  3418. caption=_("Export FlatCAM Preferences"),
  3419. directory=self.data_path + '/preferences_' + self.date,
  3420. filter=filter__
  3421. )
  3422. except TypeError:
  3423. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export FlatCAM Preferences"),
  3424. filter=filter__)
  3425. filename = str(filename)
  3426. defaults_from_file = {}
  3427. if filename == "":
  3428. self.inform.emit('[WARNING_NOTCL] %s' % _("FlatCAM preferences export cancelled."))
  3429. return
  3430. else:
  3431. try:
  3432. f = open(filename, 'w')
  3433. defaults_file_content = f.read()
  3434. f.close()
  3435. except PermissionError:
  3436. self.inform.emit('[WARNING] %s' %
  3437. _("Permission denied, saving not possible.\n"
  3438. "Most likely another app is holding the file open and not accessible."))
  3439. return
  3440. except IOError:
  3441. App.log.debug('Creating a new preferences file ...')
  3442. f = open(filename, 'w')
  3443. json.dump({}, f)
  3444. f.close()
  3445. except Exception:
  3446. e = sys.exc_info()[0]
  3447. App.log.error("Could not load defaults file.")
  3448. App.log.error(str(e))
  3449. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load preferences file."))
  3450. return
  3451. try:
  3452. defaults_from_file = json.loads(defaults_file_content)
  3453. except Exception:
  3454. App.log.warning("Trying to read an empty Preferences file. Continue.")
  3455. # Update options
  3456. self.defaults_read_form()
  3457. defaults_from_file.update(self.defaults)
  3458. self.propagate_defaults(silent=True)
  3459. # Save update options
  3460. try:
  3461. f = open(filename, "w")
  3462. json.dump(defaults_from_file, f, default=to_dict, indent=2, sort_keys=True)
  3463. f.close()
  3464. except Exception:
  3465. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  3466. return
  3467. if self.defaults["global_open_style"] is False:
  3468. self.file_opened.emit("preferences", filename)
  3469. self.file_saved.emit("preferences", filename)
  3470. self.inform.emit('[success] %s: %s' % (_("Exported preferences to"), filename))
  3471. def save_geometry(self, x, y, width, height, notebook_width):
  3472. """
  3473. Will save the application geometry and positions in the defaults discitionary to be restored at the next
  3474. launch of the application.
  3475. :param x: X position of the main window
  3476. :param y: Y position of the main window
  3477. :param width: width of the main window
  3478. :param height: height of the main window
  3479. :param notebook_width: the notebook width is adjustable so it get saved here, too.
  3480. :return: None
  3481. """
  3482. self.defaults["global_def_win_x"] = x
  3483. self.defaults["global_def_win_y"] = y
  3484. self.defaults["global_def_win_w"] = width
  3485. self.defaults["global_def_win_h"] = height
  3486. self.defaults["global_def_notebook_width"] = notebook_width
  3487. self.save_defaults()
  3488. def restore_main_win_geom(self):
  3489. try:
  3490. self.ui.setGeometry(self.defaults["global_def_win_x"],
  3491. self.defaults["global_def_win_y"],
  3492. self.defaults["global_def_win_w"],
  3493. self.defaults["global_def_win_h"])
  3494. self.ui.splitter.setSizes([self.defaults["global_def_notebook_width"], 0])
  3495. except KeyError as e:
  3496. log.debug("App.restore_main_win_geom() --> %s" % str(e))
  3497. def message_dialog(self, title, message, kind="info"):
  3498. """
  3499. Builds and show a custom QMessageBox to be used in FlatCAM.
  3500. :param title: title of the QMessageBox
  3501. :param message: message to be displayed
  3502. :param kind: type of QMessageBox; will display a specific icon.
  3503. :return:
  3504. """
  3505. icon = {"info": QtWidgets.QMessageBox.Information,
  3506. "warning": QtWidgets.QMessageBox.Warning,
  3507. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  3508. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  3509. dlg.setText(message)
  3510. dlg.exec_()
  3511. def register_recent(self, kind, filename):
  3512. """
  3513. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  3514. dictionary.
  3515. :param kind: type of file that was opened
  3516. :param filename: the path and file name for the file that was opened
  3517. :return:
  3518. """
  3519. self.log.debug("register_recent()")
  3520. self.log.debug(" %s" % kind)
  3521. self.log.debug(" %s" % filename)
  3522. record = {'kind': str(kind), 'filename': str(filename)}
  3523. if record in self.recent:
  3524. return
  3525. if record in self.recent_projects:
  3526. return
  3527. if record['kind'] == 'project':
  3528. self.recent_projects.insert(0, record)
  3529. else:
  3530. self.recent.insert(0, record)
  3531. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  3532. self.recent.pop()
  3533. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  3534. self.recent_projects.pop()
  3535. try:
  3536. f = open(self.data_path + '/recent.json', 'w')
  3537. except IOError:
  3538. App.log.error("Failed to open recent items file for writing.")
  3539. self.inform.emit('[ERROR_NOTCL] %s' %
  3540. _('Failed to open recent files file for writing.'))
  3541. return
  3542. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  3543. f.close()
  3544. try:
  3545. fp = open(self.data_path + '/recent_projects.json', 'w')
  3546. except IOError:
  3547. App.log.error("Failed to open recent items file for writing.")
  3548. self.inform.emit('[ERROR_NOTCL] %s' %
  3549. _('Failed to open recent projects file for writing.'))
  3550. return
  3551. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  3552. fp.close()
  3553. # Re-build the recent items menu
  3554. self.setup_recent_items()
  3555. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  3556. """
  3557. Creates a new specialized FlatCAMObj and attaches it to the application,
  3558. this is, updates the GUI accordingly, any other records and plots it.
  3559. This method is thread-safe.
  3560. Notes:
  3561. * If the name is in use, the self.collection will modify it
  3562. when appending it to the collection. There is no need to handle
  3563. name conflicts here.
  3564. :param kind: The kind of object to create. One of 'gerber', 'excellon', 'cncjob' and 'geometry'.
  3565. :type kind: str
  3566. :param name: Name for the object.
  3567. :type name: str
  3568. :param initialize: Function to run after creation of the object but before it is attached to the application.
  3569. The function is called with 2 parameters: the new object and the App instance.
  3570. :type initialize: function
  3571. :param active:
  3572. :param fit:
  3573. :param plot: If to plot the resulting object
  3574. :param autoselected: if the resulting object is autoselected in the Project tab and therefore in the
  3575. self.colleaction
  3576. :return: None
  3577. :rtype: None
  3578. """
  3579. App.log.debug("new_object()")
  3580. obj_plot = plot
  3581. obj_autoselected = autoselected
  3582. t0 = time.time() # Debug
  3583. # ## Create object
  3584. classdict = {
  3585. "gerber": FlatCAMGerber,
  3586. "excellon": FlatCAMExcellon,
  3587. "cncjob": FlatCAMCNCjob,
  3588. "geometry": FlatCAMGeometry,
  3589. "script": FlatCAMScript,
  3590. "document": FlatCAMDocument
  3591. }
  3592. App.log.debug("Calling object constructor...")
  3593. # Object creation/instantiation
  3594. obj = classdict[kind](name)
  3595. obj.units = self.options["units"] # TODO: The constructor should look at defaults.
  3596. # IMPORTANT
  3597. # The key names in defaults and options dictionary's are not random:
  3598. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  3599. # called here, the 'kind' followed by an underline. Above the App default values from self.defaults are
  3600. # copied to self.options. After that, below, depending on the type of
  3601. # object that is created, it will strip the name of the object and the underline (if the original key was
  3602. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  3603. # "toolchange"
  3604. for option in self.options:
  3605. if option.find(kind + "_") == 0:
  3606. oname = option[len(kind) + 1:]
  3607. obj.options[oname] = self.options[option]
  3608. obj.isHovering = False
  3609. obj.notHovering = True
  3610. # Initialize as per user request
  3611. # User must take care to implement initialize
  3612. # in a thread-safe way as is is likely that we
  3613. # have been invoked in a separate thread.
  3614. t1 = time.time()
  3615. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  3616. try:
  3617. return_value = initialize(obj, self)
  3618. except Exception as e:
  3619. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  3620. msg += _("Object ({kind}) failed because: {error} \n\n").format(kind=kind, error=str(e))
  3621. msg += traceback.format_exc()
  3622. self.inform.emit(msg)
  3623. return "fail"
  3624. t2 = time.time()
  3625. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  3626. if return_value == 'fail':
  3627. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  3628. return "fail"
  3629. # Check units and convert if necessary
  3630. # This condition CAN be true because initialize() can change obj.units
  3631. if self.options["units"].upper() != obj.units.upper():
  3632. self.inform.emit('%s: %s' % (_("Converting units to "), self.options["units"]))
  3633. obj.convert_units(self.options["units"])
  3634. t3 = time.time()
  3635. self.log.debug("%f seconds converting units." % (t3 - t2))
  3636. # Create the bounding box for the object and then add the results to the obj.options
  3637. # But not for Scripts or for Documents
  3638. if kind != 'document' and kind != 'script':
  3639. try:
  3640. xmin, ymin, xmax, ymax = obj.bounds()
  3641. obj.options['xmin'] = xmin
  3642. obj.options['ymin'] = ymin
  3643. obj.options['xmax'] = xmax
  3644. obj.options['ymax'] = ymax
  3645. except Exception as e:
  3646. log.warning("App.new_object() -> The object has no bounds properties. %s" % str(e))
  3647. return "fail"
  3648. try:
  3649. if kind == 'excellon':
  3650. obj.fill_color = self.defaults["excellon_plot_fill"]
  3651. obj.outline_color = self.defaults["excellon_plot_line"]
  3652. if kind == 'gerber':
  3653. obj.fill_color = self.defaults["gerber_plot_fill"]
  3654. obj.outline_color = self.defaults["gerber_plot_line"]
  3655. except Exception as e:
  3656. log.warning("App.new_object() -> setting colors error. %s" % str(e))
  3657. # update the KeyWords list with the name of the file
  3658. self.myKeywords.append(obj.options['name'])
  3659. FlatCAMApp.App.log.debug("Moving new object back to main thread.")
  3660. # Move the object to the main thread and let the app know that it is available.
  3661. obj.moveToThread(self.main_thread)
  3662. self.object_created.emit(obj, obj_plot, obj_autoselected)
  3663. return obj
  3664. def new_excellon_object(self):
  3665. """
  3666. Creates a new, blank Excellon object.
  3667. :return: None
  3668. """
  3669. self.report_usage("new_excellon_object()")
  3670. self.new_object('excellon', 'new_exc', lambda x, y: None, plot=False)
  3671. def new_geometry_object(self):
  3672. """
  3673. Creates a new, blank and single-tool Geometry object.
  3674. :return: None
  3675. """
  3676. self.report_usage("new_geometry_object()")
  3677. def initialize(obj, app):
  3678. obj.multitool = False
  3679. self.new_object('geometry', 'new_geo', initialize, plot=False)
  3680. def new_gerber_object(self):
  3681. """
  3682. Creates a new, blank Gerber object.
  3683. :return: None
  3684. """
  3685. self.report_usage("new_gerber_object()")
  3686. def initialize(grb_obj, app):
  3687. grb_obj.multitool = False
  3688. grb_obj.source_file = []
  3689. grb_obj.multigeo = False
  3690. grb_obj.follow = False
  3691. grb_obj.apertures = {}
  3692. grb_obj.solid_geometry = []
  3693. try:
  3694. grb_obj.options['xmin'] = 0
  3695. grb_obj.options['ymin'] = 0
  3696. grb_obj.options['xmax'] = 0
  3697. grb_obj.options['ymax'] = 0
  3698. except KeyError:
  3699. pass
  3700. self.new_object('gerber', 'new_grb', initialize, plot=False)
  3701. def new_script_object(self, name=None, text=None):
  3702. """
  3703. Creates a new, blank TCL Script object.
  3704. :param name: a name for the new object
  3705. :param text: pass a source file to the newly created script to be loaded in it
  3706. :return: None
  3707. """
  3708. self.report_usage("new_script_object()")
  3709. if text is not None:
  3710. new_source_file = text
  3711. else:
  3712. commands_list = "# AddCircle, AddPolygon, AddPolyline, AddRectangle, AlignDrill, " \
  3713. "AlignDrillGrid, Bbox, Bounds, ClearShell, CopperClear,\n"\
  3714. "# Cncjob, Cutout, Delete, Drillcncjob, ExportDXF, ExportExcellon, ExportGcode,\n" \
  3715. "# ExportGerber, ExportSVG, Exteriors, Follow, GeoCutout, GeoUnion, GetNames,\n"\
  3716. "# GetSys, ImportSvg, Interiors, Isolate, JoinExcellon, JoinGeometry, " \
  3717. "ListSys, MillDrills,\n"\
  3718. "# MillSlots, Mirror, New, NewExcellon, NewGeometry, NewGerber, Nregions, " \
  3719. "Offset, OpenExcellon, OpenGCode, OpenGerber, OpenProject,\n"\
  3720. "# Options, Paint, Panelize, PlotAl, PlotObjects, SaveProject, " \
  3721. "SaveSys, Scale, SetActive, SetSys, SetOrigin, Skew, SubtractPoly,\n" \
  3722. "# SubtractRectangle, Version, WriteGCode\n"
  3723. new_source_file = '# %s\n' % _('CREATE A NEW FLATCAM TCL SCRIPT') + \
  3724. '# %s:\n' % _('TCL Tutorial is here') + \
  3725. '# https://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html\n' + '\n\n' + \
  3726. '# %s:\n' % _("FlatCAM commands list")
  3727. new_source_file += commands_list + '\n'
  3728. def initialize(obj, app):
  3729. obj.source_file = deepcopy(new_source_file)
  3730. if name is None:
  3731. outname = 'new_script'
  3732. else:
  3733. outname = name
  3734. self.new_object('script', outname, initialize, plot=False)
  3735. def new_document_object(self):
  3736. """
  3737. Creates a new, blank Document object.
  3738. :return: None
  3739. """
  3740. self.report_usage("new_document_object()")
  3741. def initialize(obj, app):
  3742. obj.source_file = ""
  3743. self.new_object('document', 'new_document', initialize, plot=False)
  3744. def on_object_created(self, obj, plot, auto_select):
  3745. """
  3746. Event callback for object creation.
  3747. It will add the new object to the collection. After that it will plot the object in a threaded way
  3748. :param obj: The newly created FlatCAM object.
  3749. :param plot: if the newly create object t obe plotted
  3750. :param auto_select: if the newly created object to be autoselected after creation
  3751. :return: None
  3752. """
  3753. t0 = time.time() # DEBUG
  3754. self.log.debug("on_object_created()")
  3755. # The Collection might change the name if there is a collision
  3756. self.collection.append(obj)
  3757. # after adding the object to the collection always update the list of objects that are in the collection
  3758. self.all_objects_list = self.collection.get_list()
  3759. # self.inform.emit('[selected] %s created & selected: %s' %
  3760. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  3761. if obj.kind == 'gerber':
  3762. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  3763. kind=obj.kind.capitalize(),
  3764. color='green',
  3765. name=str(obj.options['name']), tx=_("created/selected"))
  3766. )
  3767. elif obj.kind == 'excellon':
  3768. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  3769. kind=obj.kind.capitalize(),
  3770. color='brown',
  3771. name=str(obj.options['name']), tx=_("created/selected"))
  3772. )
  3773. elif obj.kind == 'cncjob':
  3774. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  3775. kind=obj.kind.capitalize(),
  3776. color='blue',
  3777. name=str(obj.options['name']), tx=_("created/selected"))
  3778. )
  3779. elif obj.kind == 'geometry':
  3780. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  3781. kind=obj.kind.capitalize(),
  3782. color='red',
  3783. name=str(obj.options['name']), tx=_("created/selected"))
  3784. )
  3785. elif obj.kind == 'script':
  3786. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  3787. kind=obj.kind.capitalize(),
  3788. color='orange',
  3789. name=str(obj.options['name']), tx=_("created/selected"))
  3790. )
  3791. elif obj.kind == 'document':
  3792. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  3793. kind=obj.kind.capitalize(),
  3794. color='darkCyan',
  3795. name=str(obj.options['name']), tx=_("created/selected"))
  3796. )
  3797. # update the SHELL auto-completer model with the name of the new object
  3798. self.shell._edit.set_model_data(self.myKeywords)
  3799. if auto_select:
  3800. # select the just opened object but deselect the previous ones
  3801. self.collection.set_all_inactive()
  3802. self.collection.set_active(obj.options["name"])
  3803. else:
  3804. self.collection.set_all_inactive()
  3805. # here it is done the object plotting
  3806. def worker_task(t_obj):
  3807. with self.proc_container.new(_("Plotting")):
  3808. if isinstance(t_obj, FlatCAMCNCjob):
  3809. t_obj.plot(kind=self.defaults["cncjob_plot_kind"])
  3810. else:
  3811. t_obj.plot()
  3812. t1 = time.time() # DEBUG
  3813. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  3814. self.object_plotted.emit(t_obj)
  3815. # Send to worker
  3816. # self.worker.add_task(worker_task, [self])
  3817. if plot is True:
  3818. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  3819. def on_object_changed(self, obj):
  3820. """
  3821. Called whenever the geometry of the object was changed in some way.
  3822. This require the update of it's bounding values so it can be the selected on canvas.
  3823. Update the bounding box data from obj.options
  3824. :param obj: the object that was changed
  3825. :return: None
  3826. """
  3827. xmin, ymin, xmax, ymax = obj.bounds()
  3828. obj.options['xmin'] = xmin
  3829. obj.options['ymin'] = ymin
  3830. obj.options['xmax'] = xmax
  3831. obj.options['ymax'] = ymax
  3832. log.debug("Object changed, updating the bounding box data on self.options")
  3833. # delete the old selection shape
  3834. self.delete_selection_shape()
  3835. self.should_we_save = True
  3836. def on_object_plotted(self):
  3837. """
  3838. Callback called whenever the plotted object needs to be fit into the viewport (canvas)
  3839. :return: None
  3840. """
  3841. self.on_zoom_fit(None)
  3842. def on_about(self):
  3843. """
  3844. Displays the "about" dialog found in the Menu --> Help.
  3845. :return: None
  3846. """
  3847. self.report_usage("on_about")
  3848. version = self.version
  3849. version_date = self.version_date
  3850. beta = self.beta
  3851. class AboutDialog(QtWidgets.QDialog):
  3852. def __init__(self, app, parent=None):
  3853. QtWidgets.QDialog.__init__(self, parent)
  3854. self.app = app
  3855. # Icon and title
  3856. self.setWindowIcon(parent.app_icon)
  3857. self.setWindowTitle(_("About FlatCAM"))
  3858. self.resize(600, 200)
  3859. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  3860. # self.setStyleSheet(
  3861. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  3862. # "background-attachment: fixed"
  3863. # )
  3864. # bgimage = QtGui.QImage(self.resource_location + '/flatcam_icon256.png')
  3865. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  3866. # palette = QtGui.QPalette()
  3867. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  3868. # self.setPalette(palette)
  3869. logo = QtWidgets.QLabel()
  3870. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/flatcam_icon256.png'))
  3871. title = QtWidgets.QLabel(
  3872. "<font size=8><B>FlatCAM</B></font><BR>"
  3873. "{title}<BR>"
  3874. "<BR>"
  3875. "<BR>"
  3876. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  3877. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  3878. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  3879. "<B>{issue}</B></a><BR>".format(
  3880. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  3881. devel=_("Development"),
  3882. down=_("DOWNLOAD"),
  3883. issue=_("Issue tracker"))
  3884. )
  3885. title.setOpenExternalLinks(True)
  3886. closebtn = QtWidgets.QPushButton(_("Close"))
  3887. tab_widget = QtWidgets.QTabWidget()
  3888. description_label = QtWidgets.QLabel(
  3889. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  3890. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  3891. version=version,
  3892. beta=('BETA' if beta else ''),
  3893. date=version_date,
  3894. arch=platform.architecture()[0])
  3895. )
  3896. description_label.setOpenExternalLinks(True)
  3897. lic_lbl_header = QtWidgets.QLabel(
  3898. '%s:<br>%s<br>' % (
  3899. _('Licensed under the MIT license'),
  3900. "<a href = \"http://www.opensource.org/licenses/mit-license.php\">"
  3901. "http://www.opensource.org/licenses/mit-license.php</a>"
  3902. )
  3903. )
  3904. lic_lbl_header.setOpenExternalLinks(True)
  3905. lic_lbl_body = QtWidgets.QLabel(
  3906. _(
  3907. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  3908. 'of this software and associated documentation files (the "Software"), to deal\n'
  3909. 'in the Software without restriction, including without limitation the rights\n'
  3910. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  3911. 'copies of the Software, and to permit persons to whom the Software is\n'
  3912. 'furnished to do so, subject to the following conditions:\n\n'
  3913. 'The above copyright notice and this permission notice shall be included in\n'
  3914. 'all copies or substantial portions of the Software.\n\n'
  3915. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  3916. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  3917. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  3918. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  3919. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  3920. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  3921. 'THE SOFTWARE.'
  3922. )
  3923. )
  3924. attributions_label = QtWidgets.QLabel(
  3925. _(
  3926. 'Some of the icons used are from the following sources:<br>'
  3927. '<div>Icons by <a href="https://www.flaticon.com/authors/freepik" '
  3928. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  3929. 'title="Flaticon">www.flaticon.com</a></div>'
  3930. '<div>Icons by <a target="_blank" href="https://icons8.com">Icons8</a></div>'
  3931. 'Icons by <a href="http://www.onlinewebfonts.com">oNline Web Fonts</a>'
  3932. )
  3933. )
  3934. # layouts
  3935. layout1 = QtWidgets.QVBoxLayout()
  3936. layout1_1 = QtWidgets.QHBoxLayout()
  3937. layout1_2 = QtWidgets.QHBoxLayout()
  3938. layout2 = QtWidgets.QHBoxLayout()
  3939. layout3 = QtWidgets.QHBoxLayout()
  3940. self.setLayout(layout1)
  3941. layout1.addLayout(layout1_1)
  3942. layout1.addLayout(layout1_2)
  3943. layout1.addLayout(layout2)
  3944. layout1.addLayout(layout3)
  3945. layout1_1.addStretch()
  3946. layout1_1.addWidget(description_label)
  3947. layout1_2.addWidget(tab_widget)
  3948. self.splash_tab = QtWidgets.QWidget()
  3949. self.splash_tab.setObjectName("splash_about")
  3950. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  3951. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  3952. tab_widget.addTab(self.splash_tab, _("Splash"))
  3953. self.programmmers_tab = QtWidgets.QWidget()
  3954. self.programmmers_tab.setObjectName("programmers_about")
  3955. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  3956. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  3957. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  3958. self.translators_tab = QtWidgets.QWidget()
  3959. self.translators_tab.setObjectName("translators_about")
  3960. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  3961. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  3962. tab_widget.addTab(self.translators_tab, _("Translators"))
  3963. self.license_tab = QtWidgets.QWidget()
  3964. self.license_tab.setObjectName("license_about")
  3965. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  3966. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  3967. tab_widget.addTab(self.license_tab, _("License"))
  3968. self.attributions_tab = QtWidgets.QWidget()
  3969. self.attributions_tab.setObjectName("attributions_about")
  3970. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  3971. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  3972. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  3973. self.splash_tab_layout.addWidget(logo, stretch=0)
  3974. self.splash_tab_layout.addWidget(title, stretch=1)
  3975. pal = QtGui.QPalette()
  3976. pal.setColor(QtGui.QPalette.Background, Qt.white)
  3977. self.prog_grid_lay = QtWidgets.QGridLayout()
  3978. self.prog_grid_lay.setHorizontalSpacing(20)
  3979. self.prog_grid_lay.setColumnStretch(0, 0)
  3980. self.prog_grid_lay.setColumnStretch(2, 1)
  3981. prog_widget = QtWidgets.QWidget()
  3982. prog_widget.setLayout(self.prog_grid_lay)
  3983. prog_scroll = QtWidgets.QScrollArea()
  3984. prog_scroll.setWidget(prog_widget)
  3985. prog_scroll.setWidgetResizable(True)
  3986. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  3987. prog_scroll.setPalette(pal)
  3988. self.programmmers_tab_layout.addWidget(prog_scroll)
  3989. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  3990. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  3991. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  3992. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  3993. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Program Author"), 1, 1)
  3994. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<>"), 1, 2)
  3995. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  3996. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  3997. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  3998. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("BETA Maintainer >= 2019")), 4, 1)
  3999. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 2)
  4000. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 5, 0)
  4001. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Alex Lazar"), 6, 0)
  4002. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 7, 0)
  4003. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Evans"), 8, 0)
  4004. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Victor Benso"), 9, 0)
  4005. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 10, 0)
  4006. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Barnaby Walters"), 11, 0)
  4007. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"), 12, 0)
  4008. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lei Zheng"), 13, 0)
  4009. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marco A Quezada"), 14, 0)
  4010. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 12, 0)
  4011. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Cedric Dussud"), 15, 0)
  4012. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Hemingway"), 16, 0)
  4013. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Damian Wrobel"), 17, 0)
  4014. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Daniel Sallin"), 18, 0)
  4015. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 19, 0)
  4016. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Bruno Vunderl"), 20, 0)
  4017. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Gonzalo Lopez"), 21, 0)
  4018. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jakob Staudt"), 22, 0)
  4019. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Smith"), 23, 0)
  4020. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 24, 0)
  4021. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lubos Medovarsky"), 25, 0)
  4022. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Steve Martina"), 26, 0)
  4023. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Thomas Duffin"), 27, 0)
  4024. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 28, 0)
  4025. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 29, 0)
  4026. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Breneman"), 30, 0)
  4027. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Eric Varsanyi"), 31, 0)
  4028. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 34, 0)
  4029. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Idechix"), 100, 0)
  4030. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@SM"), 101, 0)
  4031. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@grbf"), 102, 0)
  4032. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Symonty"), 103, 0)
  4033. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@mgix"), 104, 0)
  4034. self.translator_grid_lay = QtWidgets.QGridLayout()
  4035. self.translator_grid_lay.setColumnStretch(0, 0)
  4036. self.translator_grid_lay.setColumnStretch(1, 0)
  4037. self.translator_grid_lay.setColumnStretch(2, 1)
  4038. self.translator_grid_lay.setColumnStretch(3, 0)
  4039. # trans_widget = QtWidgets.QWidget()
  4040. # trans_widget.setLayout(self.translator_grid_lay)
  4041. # self.translators_tab_layout.addWidget(trans_widget)
  4042. # self.translators_tab_layout.addStretch()
  4043. trans_widget = QtWidgets.QWidget()
  4044. trans_widget.setLayout(self.translator_grid_lay)
  4045. trans_scroll = QtWidgets.QScrollArea()
  4046. trans_scroll.setWidget(trans_widget)
  4047. trans_scroll.setWidgetResizable(True)
  4048. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  4049. trans_scroll.setPalette(pal)
  4050. self.translators_tab_layout.addWidget(trans_scroll)
  4051. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  4052. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  4053. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Corrections")), 0, 2)
  4054. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 3)
  4055. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "BR - Portuguese"), 1, 0)
  4056. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  4057. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<carlos.stein@gmail.com>"), 1, 3)
  4058. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  4059. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 2, 1)
  4060. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 2, 2)
  4061. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 2, 3)
  4062. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 3, 0)
  4063. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 3, 1)
  4064. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jens Karstedt, Detlef Eckardt"), 3, 2)
  4065. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 3)
  4066. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 4, 0)
  4067. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 1)
  4068. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 3)
  4069. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 5, 0)
  4070. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 5, 1)
  4071. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 5, 3)
  4072. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 6, 0)
  4073. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 6, 1)
  4074. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 6, 2)
  4075. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 6, 3)
  4076. self.translator_grid_lay.setColumnStretch(0, 0)
  4077. self.translators_tab_layout.addStretch()
  4078. self.license_tab_layout.addWidget(lic_lbl_header)
  4079. self.license_tab_layout.addWidget(lic_lbl_body)
  4080. self.license_tab_layout.addStretch()
  4081. self.attributions_tab_layout.addWidget(attributions_label)
  4082. self.attributions_tab_layout.addStretch()
  4083. layout3.addStretch()
  4084. layout3.addWidget(closebtn)
  4085. closebtn.clicked.connect(self.accept)
  4086. AboutDialog(app=self, parent=self.ui).exec_()
  4087. def install_bookmarks(self, book_dict=None):
  4088. """
  4089. Install the bookmarks actions in the Help menu -> Bookmarks
  4090. :param book_dict: a dict having the actions text as keys and the weblinks as the values
  4091. :return: None
  4092. """
  4093. if book_dict is None:
  4094. self.defaults["global_bookmarks"].update(
  4095. {
  4096. '1': ['FlatCAM', "http://flatcam.org"],
  4097. '2': ['Backup Site', ""]
  4098. }
  4099. )
  4100. else:
  4101. self.defaults["global_bookmarks"].clear()
  4102. self.defaults["global_bookmarks"].update(book_dict)
  4103. # first try to disconnect if somehow they get connected from elsewhere
  4104. for act in self.ui.menuhelp_bookmarks.actions():
  4105. try:
  4106. act.triggered.disconnect()
  4107. except TypeError:
  4108. pass
  4109. # clear all actions except the last one who is the Bookmark manager
  4110. if act is self.ui.menuhelp_bookmarks.actions()[-1]:
  4111. pass
  4112. else:
  4113. self.ui.menuhelp_bookmarks.removeAction(act)
  4114. bm_limit = int(self.defaults["global_bookmarks_limit"])
  4115. if self.defaults["global_bookmarks"]:
  4116. # order the self.defaults["global_bookmarks"] dict keys by the value as integer
  4117. # the whole convoluted things is because when serializing the self.defaults (on app close or save)
  4118. # the JSON is first making the keys as strings (therefore I have to use strings too
  4119. # or do the conversion :(
  4120. # )
  4121. # and it is ordering them (actually I want that to make the defaults easy to search within) but making
  4122. # the '10' entry jsut after '1' therefore ordering as strings
  4123. sorted_bookmarks = sorted(list(self.defaults["global_bookmarks"].items())[:bm_limit],
  4124. key=lambda x: int(x[0]))
  4125. for entry, bookmark in sorted_bookmarks:
  4126. title = bookmark[0]
  4127. weblink = bookmark[1]
  4128. act = QtWidgets.QAction(parent=self.ui.menuhelp_bookmarks)
  4129. act.setText(title)
  4130. act.setIcon(QtGui.QIcon(self.resource_location + '/link16.png'))
  4131. # from here: https://stackoverflow.com/questions/20390323/pyqt-dynamic-generate-qmenu-action-and-connect
  4132. if title == 'Backup Site' and weblink == "":
  4133. act.triggered.connect(self.on_backup_site)
  4134. else:
  4135. act.triggered.connect(lambda sig, link=weblink: webbrowser.open(link))
  4136. self.ui.menuhelp_bookmarks.insertAction(self.ui.menuhelp_bookmarks_manager, act)
  4137. self.ui.menuhelp_bookmarks_manager.triggered.connect(self.on_bookmarks_manager)
  4138. def on_bookmarks_manager(self):
  4139. """
  4140. Adds the bookmark manager in a Tab in Plot Area
  4141. :return:
  4142. """
  4143. for idx in range(self.ui.plot_tab_area.count()):
  4144. if self.ui.plot_tab_area.tabText(idx) == _("Bookmarks Manager"):
  4145. # there can be only one instance of Bookmark Manager at one time
  4146. return
  4147. # BookDialog(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui).exec_()
  4148. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui)
  4149. # add the tab if it was closed
  4150. self.ui.plot_tab_area.addTab(self.book_dialog_tab, _("Bookmarks Manager"))
  4151. # delete the absolute and relative position and messages in the infobar
  4152. self.ui.position_label.setText("")
  4153. self.ui.rel_position_label.setText("")
  4154. # Switch plot_area to preferences page
  4155. self.ui.plot_tab_area.setCurrentWidget(self.book_dialog_tab)
  4156. def on_backup_site(self):
  4157. msgbox = QtWidgets.QMessageBox()
  4158. msgbox.setText(_("This entry will resolve to another website if:\n\n"
  4159. "1. FlatCAM.org website is down\n"
  4160. "2. Someone forked FlatCAM project and wants to point\n"
  4161. "to his own website\n\n"
  4162. "If you can't get any informations about FlatCAM beta\n"
  4163. "use the YouTube channel link from the Help menu."))
  4164. msgbox.setWindowTitle(_("Alternative website"))
  4165. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/globe16.png'))
  4166. bt_yes = msgbox.addButton(_('Close'), QtWidgets.QMessageBox.YesRole)
  4167. msgbox.setDefaultButton(bt_yes)
  4168. msgbox.exec_()
  4169. # response = msgbox.clickedButton()
  4170. def on_file_savedefaults(self):
  4171. """
  4172. Callback for menu item File->Save Defaults. Saves application default options
  4173. ``self.defaults`` to current_defaults.FlatConfig.
  4174. :return: None
  4175. """
  4176. self.save_defaults()
  4177. # def on_app_exit(self):
  4178. # self.report_usage("on_app_exit()")
  4179. #
  4180. # if self.collection.get_list():
  4181. # msgbox = QtWidgets.QMessageBox()
  4182. # # msgbox.setText("<B>Save changes ...</B>")
  4183. # msgbox.setText("There are files/objects opened in FlatCAM. "
  4184. # "\n"
  4185. # "Do you want to Save the project?")
  4186. # msgbox.setWindowTitle("Save changes")
  4187. # msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  4188. # msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  4189. # QtWidgets.QMessageBox.Cancel)
  4190. # msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  4191. #
  4192. # response = msgbox.exec_()
  4193. #
  4194. # if response == QtWidgets.QMessageBox.Yes:
  4195. # self.on_file_saveprojectas(thread=False)
  4196. # elif response == QtWidgets.QMessageBox.Cancel:
  4197. # return
  4198. # self.save_defaults()
  4199. # else:
  4200. # self.save_defaults()
  4201. # log.debug("Application defaults saved ... Exit event.")
  4202. # QtWidgets.qApp.quit()
  4203. def save_defaults(self, silent=False, data_path=None, first_time=False):
  4204. """
  4205. Saves application default options
  4206. ``self.defaults`` to current_defaults.FlatConfig file.
  4207. Save the toolbars visibility status to the preferences file (current_defaults.FlatConfig) to be
  4208. used at the next launch of the application.
  4209. :param silent: whether to display a message in status bar or not; boolean
  4210. :param data_path: the path where to save the preferences file (current_defaults.FlatConfig)
  4211. When the application is portable it should be a mobile location.
  4212. :return: None
  4213. """
  4214. self.report_usage("save_defaults")
  4215. if data_path is None:
  4216. data_path = self.data_path
  4217. # Read options from file
  4218. try:
  4219. f = open(data_path + "/current_defaults.FlatConfig")
  4220. defaults_file_content = f.read()
  4221. f.close()
  4222. except Exception:
  4223. e = sys.exc_info()[0]
  4224. App.log.error("Could not load defaults file.")
  4225. App.log.error(str(e))
  4226. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load defaults file."))
  4227. return
  4228. try:
  4229. defaults = json.loads(defaults_file_content)
  4230. except Exception:
  4231. e = sys.exc_info()[0]
  4232. App.log.error("Failed to parse defaults file.")
  4233. App.log.error(str(e))
  4234. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse defaults file."))
  4235. return
  4236. # Update options
  4237. self.defaults_read_form()
  4238. defaults.update(self.defaults)
  4239. self.propagate_defaults(silent=True)
  4240. # Save the toolbar view
  4241. tb_status = 0
  4242. if self.ui.toolbarfile.isVisible():
  4243. tb_status += 1
  4244. if self.ui.toolbargeo.isVisible():
  4245. tb_status += 2
  4246. if self.ui.toolbarview.isVisible():
  4247. tb_status += 4
  4248. if self.ui.toolbartools.isVisible():
  4249. tb_status += 8
  4250. if self.ui.exc_edit_toolbar.isVisible():
  4251. tb_status += 16
  4252. if self.ui.geo_edit_toolbar.isVisible():
  4253. tb_status += 32
  4254. if self.ui.grb_edit_toolbar.isVisible():
  4255. tb_status += 64
  4256. if self.ui.snap_toolbar.isVisible():
  4257. tb_status += 128
  4258. if self.ui.toolbarshell.isVisible():
  4259. tb_status += 256
  4260. if first_time is False:
  4261. self.defaults["global_toolbar_view"] = tb_status
  4262. # Save update options
  4263. filename = data_path + "/current_defaults.FlatConfig"
  4264. try:
  4265. f = open(filename, "w")
  4266. json.dump(defaults, f, default=to_dict, indent=2, sort_keys=True)
  4267. f.close()
  4268. except Exception as e:
  4269. log.debug("App.save_defaults() --> %s" % str(e))
  4270. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  4271. return
  4272. if not silent:
  4273. self.inform.emit('[success] %s' % _("Preferences saved."))
  4274. def save_factory_defaults(self, silent_message=False, data_path=None):
  4275. """
  4276. Saves application factory default options
  4277. ``self.defaults`` to factory_defaults.FlatConfig.
  4278. It's a one time job done just after the first install.
  4279. :param silent_message: whether to display a message in status bar or not; boolean
  4280. :param data_path: the path where to save the default preferences file (factory_defaults.FlatConfig)
  4281. When the application is portable it should be a mobile location.
  4282. :return: None
  4283. """
  4284. self.report_usage("save_factory_defaults")
  4285. if data_path is None:
  4286. data_path = self.data_path
  4287. # Read options from file
  4288. try:
  4289. f_f_def = open(data_path + "/factory_defaults.FlatConfig")
  4290. factory_defaults_file_content = f_f_def.read()
  4291. f_f_def.close()
  4292. except Exception:
  4293. e = sys.exc_info()[0]
  4294. App.log.error("Could not load factory defaults file.")
  4295. App.log.error(str(e))
  4296. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load factory defaults file."))
  4297. return
  4298. try:
  4299. factory_defaults = json.loads(factory_defaults_file_content)
  4300. except Exception:
  4301. e = sys.exc_info()[0]
  4302. App.log.error("Failed to parse factory defaults file.")
  4303. App.log.error(str(e))
  4304. if silent_message is False:
  4305. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse factory defaults file."))
  4306. return
  4307. # Update options
  4308. self.defaults_read_form()
  4309. factory_defaults.update(self.defaults)
  4310. self.propagate_defaults(silent=True)
  4311. # Save update options
  4312. try:
  4313. f_f_def_s = open(data_path + "/factory_defaults.FlatConfig", "w")
  4314. json.dump(factory_defaults, f_f_def_s, default=to_dict, indent=2, sort_keys=True)
  4315. f_f_def_s.close()
  4316. except Exception as e:
  4317. log.debug("App.save_factory_default() save update --> %s" % str(e))
  4318. if silent_message is False:
  4319. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to write factory defaults to file."))
  4320. return
  4321. if silent_message is False:
  4322. self.inform.emit(_("Factory defaults saved."))
  4323. def final_save(self):
  4324. """
  4325. Callback for doing a preferences save to file whenever the application is about to quit.
  4326. If the project has changes, it will ask the user to save the project.
  4327. :return: None
  4328. """
  4329. if self.save_in_progress:
  4330. self.inform.emit('[WARNING_NOTCL] %s' % _("Application is saving the project. Please wait ..."))
  4331. return
  4332. if self.should_we_save and self.collection.get_list():
  4333. msgbox = QtWidgets.QMessageBox()
  4334. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  4335. "\n"
  4336. "Do you want to Save the project?"))
  4337. msgbox.setWindowTitle(_("Save changes"))
  4338. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  4339. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  4340. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  4341. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4342. msgbox.setDefaultButton(bt_yes)
  4343. msgbox.exec_()
  4344. response = msgbox.clickedButton()
  4345. if response == bt_yes:
  4346. try:
  4347. self.trayIcon.hide()
  4348. except Exception:
  4349. pass
  4350. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  4351. elif response == bt_no:
  4352. try:
  4353. self.trayIcon.hide()
  4354. except Exception:
  4355. pass
  4356. self.quit_application()
  4357. elif response == bt_cancel:
  4358. return
  4359. else:
  4360. try:
  4361. self.trayIcon.hide()
  4362. except Exception:
  4363. pass
  4364. self.quit_application()
  4365. def quit_application(self):
  4366. """
  4367. Called (as a pyslot or not) when the application is quit.
  4368. :return: None
  4369. """
  4370. self.save_defaults(silent=True)
  4371. log.debug("App.final_save() --> App Defaults saved.")
  4372. if self.cmd_line_headless != 1:
  4373. # save app state to file
  4374. stgs = QSettings("Open Source", "FlatCAM")
  4375. stgs.setValue('saved_gui_state', self.ui.saveState())
  4376. stgs.setValue('maximized_gui', self.ui.isMaximized())
  4377. stgs.setValue(
  4378. 'language',
  4379. self.ui.general_defaults_form.general_app_group.language_cb.get_value()
  4380. )
  4381. stgs.setValue(
  4382. 'notebook_font_size',
  4383. self.ui.general_defaults_form.general_app_set_group.notebook_font_size_spinner.get_value()
  4384. )
  4385. stgs.setValue(
  4386. 'axis_font_size',
  4387. self.ui.general_defaults_form.general_app_set_group.axis_font_size_spinner.get_value()
  4388. )
  4389. stgs.setValue(
  4390. 'textbox_font_size',
  4391. self.ui.general_defaults_form.general_app_set_group.textbox_font_size_spinner.get_value()
  4392. )
  4393. stgs.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  4394. stgs.setValue(
  4395. 'machinist',
  4396. 1 if self.ui.general_defaults_form.general_app_set_group.machinist_cb.get_value() else 0
  4397. )
  4398. # This will write the setting to the platform specific storage.
  4399. del stgs
  4400. log.debug("App.final_save() --> App UI state saved.")
  4401. # try to quit the QThread that run ArgsThread class
  4402. try:
  4403. self.th.quit()
  4404. except Exception:
  4405. pass
  4406. # try to quit the Socket opened by ArgsThread class
  4407. try:
  4408. self.new_launch.listener.close()
  4409. except Exception:
  4410. pass
  4411. # quit app by signalling for self.kill_app() method
  4412. self.close_app_signal.emit()
  4413. def kill_app(self):
  4414. QtWidgets.qApp.quit()
  4415. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  4416. # we use the following command
  4417. sys.exit(0)
  4418. def on_portable_checked(self, state):
  4419. """
  4420. Callback called when the checkbox in Preferences GUI is checked.
  4421. It will set the application as portable by creating the preferences and recent files in the
  4422. 'config' folder found in the FlatCAM installation folder.
  4423. :param state: boolean, the state of the checkbox when clicked/checked
  4424. :return:
  4425. """
  4426. line_no = 0
  4427. data = None
  4428. if sys.platform != 'win32':
  4429. # this won't work in Linux or MacOS
  4430. return
  4431. # test if the app was frozen and choose the path for the configuration file
  4432. if getattr(sys, "frozen", False) is True:
  4433. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  4434. else:
  4435. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  4436. config_file = current_data_path + '\\configuration.txt'
  4437. try:
  4438. with open(config_file, 'r') as f:
  4439. try:
  4440. data = f.readlines()
  4441. except Exception as e:
  4442. log.debug('App.__init__() -->%s' % str(e))
  4443. return
  4444. except FileNotFoundError:
  4445. pass
  4446. for line in data:
  4447. line = line.strip('\n')
  4448. param = str(line).rpartition('=')
  4449. if param[0] == 'portable':
  4450. break
  4451. line_no += 1
  4452. if state:
  4453. data[line_no] = 'portable=True\n'
  4454. # create the new defauults files
  4455. # create current_defaults.FlatConfig file if there is none
  4456. try:
  4457. f = open(current_data_path + '/current_defaults.FlatConfig')
  4458. f.close()
  4459. except IOError:
  4460. App.log.debug('Creating empty current_defaults.FlatConfig')
  4461. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  4462. json.dump({}, f)
  4463. f.close()
  4464. # create factory_defaults.FlatConfig file if there is none
  4465. try:
  4466. f = open(current_data_path + '/factory_defaults.FlatConfig')
  4467. f.close()
  4468. except IOError:
  4469. App.log.debug('Creating empty factory_defaults.FlatConfig')
  4470. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  4471. json.dump({}, f)
  4472. f.close()
  4473. try:
  4474. f = open(current_data_path + '/recent.json')
  4475. f.close()
  4476. except IOError:
  4477. App.log.debug('Creating empty recent.json')
  4478. f = open(current_data_path + '/recent.json', 'w')
  4479. json.dump([], f)
  4480. f.close()
  4481. try:
  4482. fp = open(current_data_path + '/recent_projects.json')
  4483. fp.close()
  4484. except IOError:
  4485. App.log.debug('Creating empty recent_projects.json')
  4486. fp = open(current_data_path + '/recent_projects.json', 'w')
  4487. json.dump([], fp)
  4488. fp.close()
  4489. # save the current defaults to the new defaults file
  4490. self.save_defaults(silent=True, data_path=current_data_path)
  4491. self.save_factory_defaults(silent_message=True, data_path=current_data_path)
  4492. else:
  4493. data[line_no] = 'portable=False\n'
  4494. with open(config_file, 'w') as f:
  4495. f.writelines(data)
  4496. def on_toggle_shell(self):
  4497. """
  4498. Toggle shell: if is visible close it, if it is closed then open it
  4499. :return: None
  4500. """
  4501. self.report_usage("on_toggle_shell()")
  4502. if self.ui.shell_dock.isVisible():
  4503. self.ui.shell_dock.hide()
  4504. else:
  4505. self.ui.shell_dock.show()
  4506. def on_register_files(self, obj_type=None):
  4507. """
  4508. Called whenever there is a need to register file extensions with FlatCAM.
  4509. Works only in Windows and should be called only when FlatCAM is run in Windows.
  4510. :param obj_type: the type of object to be register for.
  4511. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  4512. :return: None
  4513. """
  4514. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  4515. new_reg_path = 'Software\\Classes\\'
  4516. # find if the current user is admin
  4517. try:
  4518. is_admin = os.getuid() == 0
  4519. except AttributeError:
  4520. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  4521. if is_admin is True:
  4522. root_path = winreg.HKEY_LOCAL_MACHINE
  4523. else:
  4524. root_path = winreg.HKEY_CURRENT_USER
  4525. # create the keys
  4526. def set_reg(name, root_path, new_reg_path, value):
  4527. try:
  4528. winreg.CreateKey(root_path, new_reg_path)
  4529. with winreg.OpenKey(root_path, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  4530. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  4531. return True
  4532. except WindowsError:
  4533. return False
  4534. # delete key in registry
  4535. def delete_reg(root_path, reg_path, key_to_del):
  4536. key_to_del_path = reg_path + key_to_del
  4537. try:
  4538. winreg.DeleteKey(root_path, key_to_del_path)
  4539. return True
  4540. except WindowsError:
  4541. return False
  4542. if obj_type is None or obj_type == 'excellon':
  4543. exc_list = \
  4544. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4545. exc_list = [x for x in exc_list if x != '']
  4546. # register all keys in the Preferences window
  4547. for ext in exc_list:
  4548. new_k = new_reg_path + '.%s' % ext
  4549. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4550. # and unregister those that are no longer in the Preferences windows but are in the file
  4551. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  4552. if ext not in exc_list:
  4553. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4554. # now write the updated extensions to the self.defaults
  4555. # new_ext = ''
  4556. # for ext in exc_list:
  4557. # new_ext = new_ext + ext + ', '
  4558. # self.defaults["fa_excellon"] = new_ext
  4559. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  4560. if obj_type is None or obj_type == 'gcode':
  4561. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4562. gco_list = [x for x in gco_list if x != '']
  4563. # register all keys in the Preferences window
  4564. for ext in gco_list:
  4565. new_k = new_reg_path + '.%s' % ext
  4566. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4567. # and unregister those that are no longer in the Preferences windows but are in the file
  4568. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  4569. if ext not in gco_list:
  4570. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4571. # now write the updated extensions to the self.defaults
  4572. # new_ext = ''
  4573. # for ext in gco_list:
  4574. # new_ext = new_ext + ext + ', '
  4575. # self.defaults["fa_gcode"] = new_ext
  4576. self.inform.emit('[success] %s' %
  4577. _("Selected GCode file extensions registered with FlatCAM."))
  4578. if obj_type is None or obj_type == 'gerber':
  4579. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4580. grb_list = [x for x in grb_list if x != '']
  4581. # register all keys in the Preferences window
  4582. for ext in grb_list:
  4583. new_k = new_reg_path + '.%s' % ext
  4584. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  4585. # and unregister those that are no longer in the Preferences windows but are in the file
  4586. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  4587. if ext not in grb_list:
  4588. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  4589. # now write the updated extensions to the self.defaults
  4590. # new_ext = ''
  4591. # for ext in grb_list:
  4592. # new_ext = new_ext + ext + ', '
  4593. # self.defaults["fa_gerber"] = new_ext
  4594. self.inform.emit('[success] %s' %
  4595. _("Selected Gerber file extensions registered with FlatCAM."))
  4596. def add_extension(self, ext_type):
  4597. """
  4598. Add a file extension to the list for a specific object
  4599. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  4600. :return:
  4601. """
  4602. if ext_type == 'excellon':
  4603. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  4604. if new_ext == '':
  4605. return
  4606. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4607. if new_ext in old_val:
  4608. return
  4609. old_val.append(new_ext)
  4610. old_val.sort()
  4611. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  4612. if ext_type == 'gcode':
  4613. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  4614. if new_ext == '':
  4615. return
  4616. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4617. if new_ext in old_val:
  4618. return
  4619. old_val.append(new_ext)
  4620. old_val.sort()
  4621. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  4622. if ext_type == 'gerber':
  4623. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  4624. if new_ext == '':
  4625. return
  4626. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4627. if new_ext in old_val:
  4628. return
  4629. old_val.append(new_ext)
  4630. old_val.sort()
  4631. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  4632. if ext_type == 'keyword':
  4633. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  4634. if new_kw == '':
  4635. return
  4636. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4637. if new_kw in old_val:
  4638. return
  4639. old_val.append(new_kw)
  4640. old_val.sort()
  4641. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  4642. # update the self.myKeywords so the model is updated
  4643. self.autocomplete_kw_list = \
  4644. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4645. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4646. self.shell._edit.set_model_data(self.myKeywords)
  4647. def del_extension(self, ext_type):
  4648. """
  4649. Remove a file extension from the list for a specific object
  4650. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  4651. :return:
  4652. """
  4653. if ext_type == 'excellon':
  4654. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  4655. if new_ext == '':
  4656. return
  4657. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  4658. if new_ext not in old_val:
  4659. return
  4660. old_val.remove(new_ext)
  4661. old_val.sort()
  4662. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  4663. if ext_type == 'gcode':
  4664. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  4665. if new_ext == '':
  4666. return
  4667. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  4668. if new_ext not in old_val:
  4669. return
  4670. old_val.remove(new_ext)
  4671. old_val.sort()
  4672. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  4673. if ext_type == 'gerber':
  4674. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  4675. if new_ext == '':
  4676. return
  4677. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  4678. if new_ext not in old_val:
  4679. return
  4680. old_val.remove(new_ext)
  4681. old_val.sort()
  4682. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  4683. if ext_type == 'keyword':
  4684. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  4685. if new_kw == '':
  4686. return
  4687. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4688. if new_kw not in old_val:
  4689. return
  4690. old_val.remove(new_kw)
  4691. old_val.sort()
  4692. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  4693. # update the self.myKeywords so the model is updated
  4694. self.autocomplete_kw_list = \
  4695. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  4696. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4697. self.shell._edit.set_model_data(self.myKeywords)
  4698. def restore_extensions(self, ext_type):
  4699. """
  4700. Restore all file extensions associations with FlatCAM, for a specific object
  4701. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  4702. :return:
  4703. """
  4704. if ext_type == 'excellon':
  4705. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  4706. # for the ability to open Excellon files with .txt extension
  4707. new_exc_list = deepcopy(self.exc_list)
  4708. try:
  4709. new_exc_list.remove('txt')
  4710. except ValueError:
  4711. pass
  4712. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  4713. if ext_type == 'gcode':
  4714. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  4715. if ext_type == 'gerber':
  4716. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  4717. if ext_type == 'keyword':
  4718. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  4719. # update the self.myKeywords so the model is updated
  4720. self.autocomplete_kw_list = self.default_keywords
  4721. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  4722. self.shell._edit.set_model_data(self.myKeywords)
  4723. def delete_all_extensions(self, ext_type):
  4724. """
  4725. Delete all file extensions associations with FlatCAM, for a specific object
  4726. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  4727. :return:
  4728. """
  4729. if ext_type == 'excellon':
  4730. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  4731. if ext_type == 'gcode':
  4732. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  4733. if ext_type == 'gerber':
  4734. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  4735. if ext_type == 'keyword':
  4736. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  4737. # update the self.myKeywords so the model is updated
  4738. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  4739. self.shell._edit.set_model_data(self.myKeywords)
  4740. def on_edit_join(self, name=None):
  4741. """
  4742. Callback for Edit->Join. Joins the selected geometry objects into
  4743. a new one.
  4744. :return: None
  4745. """
  4746. self.report_usage("on_edit_join()")
  4747. obj_name_single = str(name) if name else "Combo_SingleGeo"
  4748. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  4749. geo_type_set = set()
  4750. objs = self.collection.get_selected()
  4751. if len(objs) < 2:
  4752. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4753. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4754. return 'fail'
  4755. for obj in objs:
  4756. geo_type_set.add(obj.multigeo)
  4757. # if len(geo_type_list) == 1 means that all list elements are the same
  4758. if len(geo_type_set) != 1:
  4759. self.inform.emit('[ERROR] %s' %
  4760. _("Failed join. The Geometry objects are of different types.\n"
  4761. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  4762. "convert from one to another and retry joining \n"
  4763. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  4764. "the result may not be what was expected. \n"
  4765. "Check the generated GCODE."))
  4766. return
  4767. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  4768. if True in geo_type_set:
  4769. def initialize(geo_obj, app):
  4770. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=geo_obj, multigeo=True)
  4771. app.inform.emit('[success] %s.' % _("Multigeo. Geometry merging finished"))
  4772. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  4773. for v in obj.tools.values():
  4774. v['data']['name'] = obj_name_multi
  4775. self.new_object("geometry", obj_name_multi, initialize)
  4776. else:
  4777. def initialize(geo_obj, app):
  4778. FlatCAMGeometry.merge(self, geo_list=objs, geo_final=geo_obj, multigeo=False)
  4779. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  4780. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  4781. for v in obj.tools.values():
  4782. v['data']['name'] = obj_name_single
  4783. self.new_object("geometry", obj_name_single, initialize)
  4784. self.should_we_save = True
  4785. def on_edit_join_exc(self):
  4786. """
  4787. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  4788. a new Excellon.
  4789. :return: None
  4790. """
  4791. self.report_usage("on_edit_join_exc()")
  4792. objs = self.collection.get_selected()
  4793. for obj in objs:
  4794. if not isinstance(obj, FlatCAMExcellon):
  4795. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Excellon joining works only on Excellon objects."))
  4796. return
  4797. if len(objs) < 2:
  4798. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4799. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4800. return 'fail'
  4801. def initialize(exc_obj, app):
  4802. FlatCAMExcellon.merge(self, exc_list=objs, exc_final=exc_obj)
  4803. app.inform.emit('[success] %s.' % _("Excellon merging finished"))
  4804. self.new_object("excellon", 'Combo_Excellon', initialize)
  4805. self.should_we_save = True
  4806. def on_edit_join_grb(self):
  4807. """
  4808. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  4809. a new Gerber object.
  4810. :return: None
  4811. """
  4812. self.report_usage("on_edit_join_grb()")
  4813. objs = self.collection.get_selected()
  4814. for obj in objs:
  4815. if not isinstance(obj, FlatCAMGerber):
  4816. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Gerber joining works only on Gerber objects."))
  4817. return
  4818. if len(objs) < 2:
  4819. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  4820. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  4821. return 'fail'
  4822. def initialize(grb_obj, app):
  4823. FlatCAMGerber.merge(self, grb_list=objs, grb_final=grb_obj)
  4824. app.inform.emit('[success] %s.' % _("Gerber merging finished"))
  4825. self.new_object("gerber", 'Combo_Gerber', initialize)
  4826. self.should_we_save = True
  4827. def on_convert_singlegeo_to_multigeo(self):
  4828. """
  4829. Called for converting a Geometry object from single-geo to multi-geo.
  4830. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  4831. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  4832. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  4833. the solid-geometry of that tool.
  4834. :return: None
  4835. """
  4836. self.report_usage("on_convert_singlegeo_to_multigeo()")
  4837. obj = self.collection.get_active()
  4838. if obj is None:
  4839. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Select a Geometry Object and try again."))
  4840. return
  4841. if not isinstance(obj, FlatCAMGeometry):
  4842. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Expected a FlatCAMGeometry, got"), type(obj)))
  4843. return
  4844. obj.multigeo = True
  4845. for tooluid, dict_value in obj.tools.items():
  4846. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  4847. if not isinstance(obj.solid_geometry, list):
  4848. obj.solid_geometry = [obj.solid_geometry]
  4849. obj.solid_geometry[:] = []
  4850. obj.plot()
  4851. self.should_we_save = True
  4852. self.inform.emit('[success] %s' % _("A Geometry object was converted to MultiGeo type."))
  4853. def on_convert_multigeo_to_singlegeo(self):
  4854. """
  4855. Called for converting a Geometry object from multi-geo to single-geo.
  4856. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  4857. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  4858. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  4859. the solid-geometry of that tool.
  4860. :return: None
  4861. """
  4862. self.report_usage("on_convert_multigeo_to_singlegeo()")
  4863. obj = self.collection.get_active()
  4864. if obj is None:
  4865. self.inform.emit('[ERROR_NOTCL] %s' %
  4866. _("Failed. Select a Geometry Object and try again."))
  4867. return
  4868. if not isinstance(obj, FlatCAMGeometry):
  4869. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  4870. (_("Expected a FlatCAMGeometry, got"), type(obj)))
  4871. return
  4872. obj.multigeo = False
  4873. total_solid_geometry = []
  4874. for tooluid, dict_value in obj.tools.items():
  4875. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  4876. # clear the original geometry
  4877. dict_value['solid_geometry'][:] = []
  4878. obj.solid_geometry = deepcopy(total_solid_geometry)
  4879. obj.plot()
  4880. self.should_we_save = True
  4881. self.inform.emit('[success] %s' %
  4882. _("A Geometry object was converted to SingleGeo type."))
  4883. def on_defaults_dict_change(self, field):
  4884. """
  4885. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  4886. Edit -> Preferences tab window.
  4887. :param field: the key of the self.defaults dictionary that was changed.
  4888. :return: None
  4889. """
  4890. self.defaults_write_form_field(field)
  4891. if field == "units":
  4892. self.set_screen_units(self.defaults['units'])
  4893. def set_screen_units(self, units):
  4894. """
  4895. Set the FlatCAM units on the status bar.
  4896. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  4897. :return: None
  4898. """
  4899. self.ui.units_label.setText("[" + units.lower() + "]")
  4900. def on_toggle_units_click(self):
  4901. try:
  4902. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  4903. except (TypeError, AttributeError):
  4904. pass
  4905. if self.defaults["units"] == 'MM':
  4906. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  4907. else:
  4908. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  4909. self.on_toggle_units(no_pref=True)
  4910. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  4911. lambda: self.on_toggle_units(no_pref=False))
  4912. def on_toggle_units(self, no_pref=False):
  4913. """
  4914. Callback for the Units radio-button change in the Preferences tab.
  4915. Changes the application's default units adn for the project too.
  4916. If changing the project's units, the change propagates to all of
  4917. the objects in the project.
  4918. :return: None
  4919. """
  4920. self.report_usage("on_toggle_units")
  4921. if self.toggle_units_ignore:
  4922. return
  4923. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  4924. # If option is the same, then ignore
  4925. if new_units == self.defaults["units"].upper():
  4926. self.log.debug("on_toggle_units(): Same as defaults, so ignoring.")
  4927. return
  4928. # Options to scale
  4929. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin', "gerber_isooverlap",
  4930. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f",
  4931. 'excellon_drillz', 'excellon_travelz', "excellon_toolchangexy",
  4932. 'excellon_feedrate', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  4933. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', "excellon_feedrate_probe",
  4934. "excellon_z_pdepth", "excellon_editor_newdia", "excellon_editor_lin_pitch",
  4935. "excellon_editor_slot_lin_pitch",
  4936. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  4937. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  4938. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', "geometry_z_pdepth",
  4939. "geometry_feedrate_probe", "geometry_startz",
  4940. 'cncjob_tooldia',
  4941. 'tools_paintmargin', 'tools_painttooldia', 'tools_paintoverlap',
  4942. "tools_ncctools", "tools_nccoverlap", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia",
  4943. "tools_nccnewdia",
  4944. "tools_2sided_drilldia", "tools_film_boundary",
  4945. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize',
  4946. "tools_panelize_constrainx", "tools_panelize_constrainy",
  4947. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  4948. "tools_transform_skew_x", "tools_transform_skew_y", "tools_transform_offset_x",
  4949. "tools_transform_offset_y",
  4950. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  4951. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  4952. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  4953. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  4954. "tools_cr_trace_size_val", "tools_cr_c2c_val", "tools_cr_c2o_val", "tools_cr_s2s_val",
  4955. "tools_cr_s2sm_val", "tools_cr_s2o_val", "tools_cr_sm2sm_val", "tools_cr_ri_val",
  4956. "tools_cr_h2h_val", "tools_cr_dh_val", "tools_fiducials_dia", "tools_fiducials_margin",
  4957. "tools_fiducials_line_thickness",
  4958. "tools_copper_thieving_clearance", "tools_copper_thieving_margin",
  4959. "tools_copper_thieving_dots_dia", "tools_copper_thieving_dots_spacing",
  4960. "tools_copper_thieving_squares_size", "tools_copper_thieving_squares_spacing",
  4961. "tools_copper_thieving_lines_size", "tools_copper_thieving_lines_spacing",
  4962. "tools_copper_thieving_rb_margin", "tools_copper_thieving_rb_thickness",
  4963. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance",
  4964. 'global_tpdf_bmargin', 'global_tpdf_tmargin', 'global_tpdf_rmargin', 'global_tpdf_lmargin']
  4965. def scale_defaults(sfactor):
  4966. for dim in dimensions:
  4967. if dim == 'excellon_toolchangexy':
  4968. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  4969. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4970. coords_xy[0] *= sfactor
  4971. coords_xy[1] *= sfactor
  4972. self.defaults['excellon_toolchangexy'] = "%.*f, %.*f" % (self.decimals, coords_xy[0],
  4973. self.decimals, coords_xy[1])
  4974. elif dim == 'geometry_toolchangexy':
  4975. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  4976. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  4977. coords_xy[0] *= sfactor
  4978. coords_xy[1] *= sfactor
  4979. self.defaults['geometry_toolchangexy'] = "%.*f, %.*f" % (self.decimals, coords_xy[0],
  4980. self.decimals, coords_xy[1])
  4981. elif dim == 'geometry_cnctooldia':
  4982. if type(self.defaults["geometry_cnctooldia"]) == float:
  4983. tools_diameters = [self.defaults["geometry_cnctooldia"]]
  4984. else:
  4985. try:
  4986. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  4987. tools_diameters = [eval(a) for a in tools_string if a != '']
  4988. except Exception as e:
  4989. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  4990. continue
  4991. self.defaults['geometry_cnctooldia'] = ''
  4992. for t in range(len(tools_diameters)):
  4993. tools_diameters[t] *= sfactor
  4994. self.defaults['geometry_cnctooldia'] += "%.*f," % (self.decimals, tools_diameters[t])
  4995. elif dim == 'tools_ncctools':
  4996. ncctools = list()
  4997. if type(self.defaults["tools_ncctools"]) == float:
  4998. ncctools = [self.defaults["tools_ncctools"]]
  4999. else:
  5000. try:
  5001. tools_string = self.defaults["tools_ncctools"].split(",")
  5002. ncctools = [eval(a) for a in tools_string if a != '']
  5003. except Exception as e:
  5004. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  5005. continue
  5006. self.defaults['tools_ncctools'] = ''
  5007. for t in range(len(ncctools)):
  5008. ncctools[t] *= sfactor
  5009. self.defaults['tools_ncctools'] += "%.*f," % (self.decimals, ncctools[t])
  5010. elif dim == 'tools_solderpaste_tools':
  5011. sptools = list()
  5012. if type(self.defaults["tools_solderpaste_tools"]) == float:
  5013. sptools = [self.defaults["tools_solderpaste_tools"]]
  5014. else:
  5015. try:
  5016. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  5017. sptools = [eval(a) for a in tools_string if a != '']
  5018. except Exception as e:
  5019. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  5020. continue
  5021. self.defaults['tools_solderpaste_tools'] = ""
  5022. for t in range(len(sptools)):
  5023. sptools[t] *= sfactor
  5024. self.defaults['tools_solderpaste_tools'] += "%.*f," % (self.decimals, sptools[t])
  5025. elif dim == 'tools_solderpaste_xy_toolchange':
  5026. try:
  5027. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  5028. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  5029. sp_coords[0] *= sfactor
  5030. sp_coords[1] *= sfactor
  5031. self.defaults['tools_solderpaste_xy_toolchange'] = "%.*f, %.*f" % (self.decimals, sp_coords[0],
  5032. self.decimals, sp_coords[1])
  5033. except Exception as e:
  5034. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  5035. continue
  5036. elif dim == 'global_gridx' or dim == 'global_gridy':
  5037. if new_units == 'IN':
  5038. val = 0.1
  5039. try:
  5040. val = float(self.defaults[dim]) * sfactor
  5041. except Exception as e:
  5042. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  5043. continue
  5044. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  5045. else:
  5046. val = 0.1
  5047. try:
  5048. val = float(self.defaults[dim]) * sfactor
  5049. except Exception as e:
  5050. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  5051. continue
  5052. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  5053. else:
  5054. val = 0.1
  5055. if self.defaults[dim]:
  5056. try:
  5057. val = float(self.defaults[dim]) * sfactor
  5058. except Exception as e:
  5059. log.debug('App.on_toggle_units().scale_defaults() --> Value: %s %s' % (str(dim), str(e)))
  5060. continue
  5061. self.defaults[dim] = val
  5062. # The scaling factor depending on choice of units.
  5063. factor = 25.4 if new_units == 'MM' else 1/25.4
  5064. # Changing project units. Warn user.
  5065. msgbox = QtWidgets.QMessageBox()
  5066. msgbox.setWindowTitle(_("Toggle Units"))
  5067. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/toggle_units32.png'))
  5068. msgbox.setText(_("Changing the units of the project\n"
  5069. "will scale all objects.\n\n"
  5070. "Do you want to continue?"))
  5071. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5072. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  5073. msgbox.setDefaultButton(bt_ok)
  5074. msgbox.exec_()
  5075. response = msgbox.clickedButton()
  5076. if response == bt_ok:
  5077. if no_pref is False:
  5078. self.defaults_read_form()
  5079. scale_defaults(factor)
  5080. self.defaults_write_form(fl_units=new_units)
  5081. self.defaults["units"] = new_units
  5082. # update the defaults from form, some may assume that the conversion is enough and it's not
  5083. self.on_options_app2project()
  5084. # update the objects
  5085. for obj in self.collection.get_list():
  5086. obj.convert_units(new_units)
  5087. # make that the properties stored in the object are also updated
  5088. self.object_changed.emit(obj)
  5089. # rebuild the object UI
  5090. obj.build_ui()
  5091. # change this only if the workspace is active
  5092. if self.defaults['global_workspace'] is True:
  5093. self.plotcanvas.draw_workspace(pagesize=self.defaults['global_workspaceT'])
  5094. # adjust the grid values on the main toolbar
  5095. val_x = float(self.defaults['global_gridx']) * factor
  5096. val_y = val_x if self.ui.grid_gap_link_cb.isChecked() else float(self.defaults['global_gridx']) * factor
  5097. current = self.collection.get_active()
  5098. if current is not None:
  5099. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  5100. if not isinstance(current, FlatCAMGeometry):
  5101. current.to_form()
  5102. # replot all objects
  5103. self.plot_all()
  5104. # set the status labels to reflect the current FlatCAM units
  5105. self.set_screen_units(new_units)
  5106. # signal to the app that we changed the object properties and it shoud save the project
  5107. self.should_we_save = True
  5108. self.inform.emit('[success] %s: %s' % (_("Converted units to"), new_units))
  5109. else:
  5110. # Undo toggling
  5111. self.toggle_units_ignore = True
  5112. if self.defaults['units'].upper() == 'MM':
  5113. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  5114. else:
  5115. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  5116. self.toggle_units_ignore = False
  5117. # store the grid values so they are not changed in the next step
  5118. val_x = float(self.defaults['global_gridx'])
  5119. val_y = float(self.defaults['global_gridy'])
  5120. self.inform.emit('[WARNING_NOTCL]%s' % _("Units conversion cancelled."))
  5121. self.defaults_read_form()
  5122. # the self.defaults_read_form() will update all defaults values in self.defaults from the GUI elements but
  5123. # I don't want it for the grid values, so I update them here
  5124. self.defaults['global_gridx'] = val_x
  5125. self.defaults['global_gridy'] = val_y
  5126. self.ui.grid_gap_x_entry.set_value(val_x, decimals=self.decimals)
  5127. self.ui.grid_gap_y_entry.set_value(val_y, decimals=self.decimals)
  5128. def on_fullscreen(self, disable=False):
  5129. self.report_usage("on_fullscreen()")
  5130. if self.toggle_fscreen is False and disable is False:
  5131. # self.ui.showFullScreen()
  5132. self.ui.setWindowFlags(self.ui.windowFlags() | Qt.FramelessWindowHint)
  5133. a = self.ui.geometry()
  5134. self.x_pos = a.x()
  5135. self.y_pos = a.y()
  5136. self.width = a.width()
  5137. self.height = a.height()
  5138. # set new geometry to full desktop rect
  5139. # Subtracting and adding the pixels below it's hack to bypass a bug in Qt5 and OpenGL that made that a
  5140. # window drawn with OpenGL in fullscreen will not show any other windows on top which means that menus and
  5141. # everything else will not work without this hack. This happen in Windows.
  5142. # https://bugreports.qt.io/browse/QTBUG-41309
  5143. desktop = QtWidgets.QApplication.desktop()
  5144. screen = desktop.screenNumber(QtGui.QCursor.pos())
  5145. rec = desktop.screenGeometry(screen)
  5146. x = rec.x() - 1
  5147. y = rec.y() - 1
  5148. h = rec.height() + 2
  5149. w = rec.width() + 2
  5150. self.ui.setGeometry(x, y, w, h)
  5151. self.ui.show()
  5152. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  5153. tb.setVisible(False)
  5154. self.ui.splitter_left.setVisible(False)
  5155. self.toggle_fscreen = True
  5156. elif self.toggle_fscreen is True or disable is True:
  5157. self.ui.setWindowFlags(self.ui.windowFlags() & ~Qt.FramelessWindowHint)
  5158. self.ui.setGeometry(self.x_pos, self.y_pos, self.width, self.height)
  5159. self.ui.showNormal()
  5160. self.restore_toolbar_view()
  5161. self.ui.splitter_left.setVisible(True)
  5162. self.toggle_fscreen = False
  5163. def on_toggle_plotarea(self):
  5164. self.report_usage("on_toggle_plotarea()")
  5165. try:
  5166. name = self.ui.plot_tab_area.widget(0).objectName()
  5167. except AttributeError:
  5168. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  5169. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  5170. self.ui.plot_tab_area.protectTab(0)
  5171. return
  5172. if name != 'plotarea':
  5173. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  5174. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  5175. self.ui.plot_tab_area.protectTab(0)
  5176. else:
  5177. self.ui.plot_tab_area.closeTab(0)
  5178. def on_toggle_notebook(self):
  5179. if self.ui.splitter.sizes()[0] == 0:
  5180. self.ui.splitter.setSizes([1, 1])
  5181. self.ui.menu_toggle_nb.setChecked(True)
  5182. else:
  5183. self.ui.splitter.setSizes([0, 1])
  5184. self.ui.menu_toggle_nb.setChecked(False)
  5185. def on_toggle_axis(self):
  5186. self.report_usage("on_toggle_axis()")
  5187. if self.toggle_axis is False:
  5188. if self.is_legacy is False:
  5189. self.plotcanvas.v_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=True,
  5190. parent=self.plotcanvas.view.scene)
  5191. self.plotcanvas.h_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=False,
  5192. parent=self.plotcanvas.view.scene)
  5193. else:
  5194. if self.plotcanvas.h_line not in self.plotcanvas.axes.lines and \
  5195. self.plotcanvas.v_line not in self.plotcanvas.axes.lines:
  5196. self.plotcanvas.h_line = self.plotcanvas.axes.axhline(color=(0.70, 0.3, 0.3), linewidth=2)
  5197. self.plotcanvas.v_line = self.plotcanvas.axes.axvline(color=(0.70, 0.3, 0.3), linewidth=2)
  5198. self.plotcanvas.canvas.draw()
  5199. self.toggle_axis = True
  5200. else:
  5201. if self.is_legacy is False:
  5202. self.plotcanvas.v_line.parent = None
  5203. self.plotcanvas.h_line.parent = None
  5204. else:
  5205. if self.plotcanvas.h_line in self.plotcanvas.axes.lines and \
  5206. self.plotcanvas.v_line in self.plotcanvas.axes.lines:
  5207. self.plotcanvas.axes.lines.remove(self.plotcanvas.h_line)
  5208. self.plotcanvas.axes.lines.remove(self.plotcanvas.v_line)
  5209. self.plotcanvas.canvas.draw()
  5210. self.toggle_axis = False
  5211. def on_toggle_grid(self):
  5212. self.report_usage("on_toggle_grid()")
  5213. self.ui.grid_snap_btn.trigger()
  5214. self.on_grid_snap_triggered(state=True)
  5215. def on_toggle_grid_lines(self):
  5216. self.report_usage("on_toggle_grd_lines()")
  5217. tt_settings = QtCore.QSettings("Open Source", "FlatCAM")
  5218. if tt_settings.contains("theme"):
  5219. theme = tt_settings.value('theme', type=str)
  5220. else:
  5221. theme = 'white'
  5222. if self.toggle_grid_lines is False:
  5223. if self.is_legacy is False:
  5224. if theme == 'white':
  5225. self.plotcanvas.grid._grid_color_fn['color'] = Color('dimgray').rgba
  5226. else:
  5227. self.plotcanvas.grid._grid_color_fn['color'] = Color('#dededeff').rgba
  5228. else:
  5229. self.plotcanvas.axes.grid(True)
  5230. try:
  5231. self.plotcanvas.canvas.draw()
  5232. except IndexError:
  5233. pass
  5234. pass
  5235. self.toggle_grid_lines = True
  5236. else:
  5237. if self.is_legacy is False:
  5238. if theme == 'white':
  5239. self.plotcanvas.grid._grid_color_fn['color'] = Color('#ffffffff').rgba
  5240. else:
  5241. self.plotcanvas.grid._grid_color_fn['color'] = Color('#000000FF').rgba
  5242. else:
  5243. self.plotcanvas.axes.grid(False)
  5244. try:
  5245. self.plotcanvas.canvas.draw()
  5246. except IndexError:
  5247. pass
  5248. self.toggle_grid_lines = False
  5249. if self.is_legacy is False:
  5250. # HACK: enabling/disabling the cursor seams to somehow update the shapes on screen
  5251. # - perhaps is a bug in VisPy implementation
  5252. if self.grid_status() is True:
  5253. self.app_cursor.enabled = False
  5254. self.app_cursor.enabled = True
  5255. else:
  5256. self.app_cursor.enabled = True
  5257. self.app_cursor.enabled = False
  5258. def show_preferences_gui(self):
  5259. """
  5260. Called to initialize and show the Preferences GUI
  5261. :return: None
  5262. """
  5263. self.gen_form = self.ui.general_defaults_form
  5264. self.ger_form = self.ui.gerber_defaults_form
  5265. self.exc_form = self.ui.excellon_defaults_form
  5266. self.geo_form = self.ui.geometry_defaults_form
  5267. self.cnc_form = self.ui.cncjob_defaults_form
  5268. self.tools_form = self.ui.tools_defaults_form
  5269. self.tools2_form = self.ui.tools2_defaults_form
  5270. self.fa_form = self.ui.util_defaults_form
  5271. try:
  5272. self.ui.general_scroll_area.takeWidget()
  5273. except Exception:
  5274. self.log.debug("Nothing to remove")
  5275. self.ui.general_scroll_area.setWidget(self.gen_form)
  5276. self.gen_form.show()
  5277. try:
  5278. self.ui.gerber_scroll_area.takeWidget()
  5279. except Exception:
  5280. self.log.debug("Nothing to remove")
  5281. self.ui.gerber_scroll_area.setWidget(self.ger_form)
  5282. self.ger_form.show()
  5283. try:
  5284. self.ui.excellon_scroll_area.takeWidget()
  5285. except Exception:
  5286. self.log.debug("Nothing to remove")
  5287. self.ui.excellon_scroll_area.setWidget(self.exc_form)
  5288. self.exc_form.show()
  5289. try:
  5290. self.ui.geometry_scroll_area.takeWidget()
  5291. except Exception:
  5292. self.log.debug("Nothing to remove")
  5293. self.ui.geometry_scroll_area.setWidget(self.geo_form)
  5294. self.geo_form.show()
  5295. try:
  5296. self.ui.cncjob_scroll_area.takeWidget()
  5297. except Exception:
  5298. self.log.debug("Nothing to remove")
  5299. self.ui.cncjob_scroll_area.setWidget(self.cnc_form)
  5300. self.cnc_form.show()
  5301. try:
  5302. self.ui.tools_scroll_area.takeWidget()
  5303. except Exception:
  5304. self.log.debug("Nothing to remove")
  5305. self.ui.tools_scroll_area.setWidget(self.tools_form)
  5306. self.tools_form.show()
  5307. try:
  5308. self.ui.tools2_scroll_area.takeWidget()
  5309. except Exception:
  5310. self.log.debug("Nothing to remove")
  5311. self.ui.tools2_scroll_area.setWidget(self.tools2_form)
  5312. self.tools2_form.show()
  5313. try:
  5314. self.ui.fa_scroll_area.takeWidget()
  5315. except Exception:
  5316. self.log.debug("Nothing to remove")
  5317. self.ui.fa_scroll_area.setWidget(self.fa_form)
  5318. self.fa_form.show()
  5319. self.log.debug("Finished Preferences GUI form initialization.")
  5320. # self.options2form()
  5321. def init_color_pickers_in_preferences_gui(self):
  5322. # Init Gerber Plot Colors
  5323. self.ui.gerber_defaults_form.gerber_gen_group.pf_color_entry.set_value(self.defaults['gerber_plot_fill'])
  5324. self.ui.gerber_defaults_form.gerber_gen_group.pf_color_button.setStyleSheet(
  5325. "background-color:%s;"
  5326. "border-color: dimgray" % str(self.defaults['gerber_plot_fill'])[:7])
  5327. self.ui.gerber_defaults_form.gerber_gen_group.pf_color_alpha_spinner.set_value(
  5328. int(self.defaults['gerber_plot_fill'][7:9], 16))
  5329. self.ui.gerber_defaults_form.gerber_gen_group.pf_color_alpha_slider.setValue(
  5330. int(self.defaults['gerber_plot_fill'][7:9], 16))
  5331. self.ui.gerber_defaults_form.gerber_gen_group.pl_color_entry.set_value(self.defaults['gerber_plot_line'])
  5332. self.ui.gerber_defaults_form.gerber_gen_group.pl_color_button.setStyleSheet(
  5333. "background-color:%s;"
  5334. "border-color: dimgray" % str(self.defaults['gerber_plot_line'])[:7])
  5335. # Init Excellon Plot Colors
  5336. self.ui.excellon_defaults_form.excellon_gen_group.fill_color_entry.set_value(
  5337. self.defaults['excellon_plot_fill'])
  5338. self.ui.excellon_defaults_form.excellon_gen_group.fill_color_button.setStyleSheet(
  5339. "background-color:%s;"
  5340. "border-color: dimgray" % str(self.defaults['excellon_plot_fill'])[:7])
  5341. self.ui.excellon_defaults_form.excellon_gen_group.color_alpha_spinner.set_value(
  5342. int(self.defaults['excellon_plot_fill'][7:9], 16))
  5343. self.ui.excellon_defaults_form.excellon_gen_group.color_alpha_slider.setValue(
  5344. int(self.defaults['excellon_plot_fill'][7:9], 16))
  5345. self.ui.excellon_defaults_form.excellon_gen_group.line_color_entry.set_value(
  5346. self.defaults['excellon_plot_line'])
  5347. self.ui.excellon_defaults_form.excellon_gen_group.line_color_button.setStyleSheet(
  5348. "background-color:%s;"
  5349. "border-color: dimgray" % str(self.defaults['excellon_plot_line'])[:7])
  5350. # Init Geometry Plot Colors
  5351. self.ui.geometry_defaults_form.geometry_gen_group.line_color_entry.set_value(
  5352. self.defaults['geometry_plot_line'])
  5353. self.ui.geometry_defaults_form.geometry_gen_group.line_color_button.setStyleSheet(
  5354. "background-color:%s;"
  5355. "border-color: dimgray" % str(self.defaults['geometry_plot_line'])[:7])
  5356. # Init CNCJob Travel Line Colors
  5357. self.ui.cncjob_defaults_form.cncjob_gen_group.tfill_color_entry.set_value(
  5358. self.defaults['cncjob_travel_fill'])
  5359. self.ui.cncjob_defaults_form.cncjob_gen_group.tfill_color_button.setStyleSheet(
  5360. "background-color:%s;"
  5361. "border-color: dimgray" % str(self.defaults['cncjob_travel_fill'])[:7])
  5362. self.ui.cncjob_defaults_form.cncjob_gen_group.tcolor_alpha_spinner.set_value(
  5363. int(self.defaults['cncjob_travel_fill'][7:9], 16))
  5364. self.ui.cncjob_defaults_form.cncjob_gen_group.tcolor_alpha_slider.setValue(
  5365. int(self.defaults['cncjob_travel_fill'][7:9], 16))
  5366. self.ui.cncjob_defaults_form.cncjob_gen_group.tline_color_entry.set_value(
  5367. self.defaults['cncjob_travel_line'])
  5368. self.ui.cncjob_defaults_form.cncjob_gen_group.tline_color_button.setStyleSheet(
  5369. "background-color:%s;"
  5370. "border-color: dimgray" % str(self.defaults['cncjob_travel_line'])[:7])
  5371. # Init CNCJob Plot Colors
  5372. self.ui.cncjob_defaults_form.cncjob_gen_group.fill_color_entry.set_value(
  5373. self.defaults['cncjob_plot_fill'])
  5374. self.ui.cncjob_defaults_form.cncjob_gen_group.fill_color_button.setStyleSheet(
  5375. "background-color:%s;"
  5376. "border-color: dimgray" % str(self.defaults['cncjob_plot_fill'])[:7])
  5377. self.ui.cncjob_defaults_form.cncjob_gen_group.line_color_entry.set_value(
  5378. self.defaults['cncjob_plot_line'])
  5379. self.ui.cncjob_defaults_form.cncjob_gen_group.line_color_button.setStyleSheet(
  5380. "background-color:%s;"
  5381. "border-color: dimgray" % str(self.defaults['cncjob_plot_line'])[:7])
  5382. # Init Left-Right Selection colors
  5383. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(self.defaults['global_sel_fill'])
  5384. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  5385. "background-color:%s;"
  5386. "border-color: dimgray" % str(self.defaults['global_sel_fill'])[:7])
  5387. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.set_value(
  5388. int(self.defaults['global_sel_fill'][7:9], 16))
  5389. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(
  5390. int(self.defaults['global_sel_fill'][7:9], 16))
  5391. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(self.defaults['global_sel_line'])
  5392. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  5393. "background-color:%s;"
  5394. "border-color: dimgray" % str(self.defaults['global_sel_line'])[:7])
  5395. # Init Right-Left Selection colors
  5396. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(
  5397. self.defaults['global_alt_sel_fill'])
  5398. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  5399. "background-color:%s;"
  5400. "border-color: dimgray" % str(self.defaults['global_alt_sel_fill'])[:7])
  5401. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.set_value(
  5402. int(self.defaults['global_sel_fill'][7:9], 16))
  5403. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(
  5404. int(self.defaults['global_sel_fill'][7:9], 16))
  5405. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(
  5406. self.defaults['global_alt_sel_line'])
  5407. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  5408. "background-color:%s;"
  5409. "border-color: dimgray" % str(self.defaults['global_alt_sel_line'])[:7])
  5410. # Init Draw color and Selection Draw Color
  5411. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(
  5412. self.defaults['global_draw_color'])
  5413. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  5414. "background-color:%s;"
  5415. "border-color: dimgray" % str(self.defaults['global_draw_color'])[:7])
  5416. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(
  5417. self.defaults['global_sel_draw_color'])
  5418. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  5419. "background-color:%s;"
  5420. "border-color: dimgray" % str(self.defaults['global_sel_draw_color'])[:7])
  5421. # Init Project Items color
  5422. self.ui.general_defaults_form.general_gui_group.proj_color_entry.set_value(
  5423. self.defaults['global_proj_item_color'])
  5424. self.ui.general_defaults_form.general_gui_group.proj_color_button.setStyleSheet(
  5425. "background-color:%s;"
  5426. "border-color: dimgray" % str(self.defaults['global_proj_item_color'])[:7])
  5427. # Init Project Disabled Items color
  5428. self.ui.general_defaults_form.general_gui_group.proj_color_dis_entry.set_value(
  5429. self.defaults['global_proj_item_dis_color'])
  5430. self.ui.general_defaults_form.general_gui_group.proj_color_dis_button.setStyleSheet(
  5431. "background-color:%s;"
  5432. "border-color: dimgray" % str(self.defaults['global_proj_item_dis_color'])[:7])
  5433. # Init Project Disabled Items color
  5434. self.ui.general_defaults_form.general_app_set_group.mouse_cursor_entry.set_value(
  5435. self.defaults['global_cursor_color'])
  5436. self.ui.general_defaults_form.general_app_set_group.mouse_cursor_button.setStyleSheet(
  5437. "background-color:%s;"
  5438. "border-color: dimgray" % str(self.defaults['global_cursor_color'])[:7])
  5439. # Init the Annotation CNC Job color
  5440. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_entry.set_value(
  5441. self.defaults['cncjob_annotation_fontcolor'])
  5442. self.ui.cncjob_defaults_form.cncjob_adv_opt_group.annotation_fontcolor_button.setStyleSheet(
  5443. "background-color:%s;"
  5444. "border-color: dimgray" % str(self.defaults['cncjob_annotation_fontcolor'])[:7])
  5445. # Init the Tool Film color
  5446. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(
  5447. self.defaults['tools_film_color'])
  5448. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  5449. "background-color:%s;"
  5450. "border-color: dimgray" % str(self.defaults['tools_film_color'])[:7]
  5451. )
  5452. # Init the Tool QRCode colors
  5453. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.set_value(
  5454. self.defaults['tools_qrcode_fill_color'])
  5455. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  5456. "background-color:%s;"
  5457. "border-color: dimgray" % str(self.defaults['tools_qrcode_fill_color'])[:7])
  5458. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.set_value(
  5459. self.defaults['tools_qrcode_back_color'])
  5460. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  5461. "background-color:%s;"
  5462. "border-color: dimgray" % str(self.defaults['tools_qrcode_back_color'])[:7])
  5463. def on_update_exc_export(self, state):
  5464. """
  5465. This is handling the update of Excellon Export parameters based on the ones in the Excellon General but only
  5466. if the update_excellon_cb checkbox is checked
  5467. :param state: state of the checkbox whose signals is tied to his slot
  5468. :return:
  5469. """
  5470. if state:
  5471. # first try to disconnect
  5472. try:
  5473. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed.\
  5474. disconnect(self.on_excellon_format_changed)
  5475. except TypeError:
  5476. pass
  5477. try:
  5478. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed.\
  5479. disconnect(self.on_excellon_format_changed)
  5480. except TypeError:
  5481. pass
  5482. try:
  5483. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed.\
  5484. disconnect(self.on_excellon_format_changed)
  5485. except TypeError:
  5486. pass
  5487. try:
  5488. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed.\
  5489. disconnect(self.on_excellon_format_changed)
  5490. except TypeError:
  5491. pass
  5492. try:
  5493. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.\
  5494. disconnect(self.on_excellon_zeros_changed)
  5495. except TypeError:
  5496. pass
  5497. try:
  5498. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.\
  5499. disconnect(self.on_excellon_zeros_changed)
  5500. except TypeError:
  5501. pass
  5502. # the connect them
  5503. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed.connect(
  5504. self.on_excellon_format_changed)
  5505. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed.connect(
  5506. self.on_excellon_format_changed)
  5507. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed.connect(
  5508. self.on_excellon_format_changed)
  5509. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed.connect(
  5510. self.on_excellon_format_changed)
  5511. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.connect(
  5512. self.on_excellon_zeros_changed)
  5513. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.connect(
  5514. self.on_excellon_units_changed)
  5515. else:
  5516. # disconnect the signals
  5517. try:
  5518. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed. \
  5519. disconnect(self.on_excellon_format_changed)
  5520. except TypeError:
  5521. pass
  5522. try:
  5523. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed. \
  5524. disconnect(self.on_excellon_format_changed)
  5525. except TypeError:
  5526. pass
  5527. try:
  5528. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed. \
  5529. disconnect(self.on_excellon_format_changed)
  5530. except TypeError:
  5531. pass
  5532. try:
  5533. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed. \
  5534. disconnect(self.on_excellon_format_changed)
  5535. except TypeError:
  5536. pass
  5537. try:
  5538. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  5539. disconnect(self.on_excellon_zeros_changed)
  5540. except TypeError:
  5541. pass
  5542. try:
  5543. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  5544. disconnect(self.on_excellon_zeros_changed)
  5545. except TypeError:
  5546. pass
  5547. def on_excellon_format_changed(self):
  5548. """
  5549. Slot activated when the user changes the Excellon format values in Preferences -> Excellon -> Excellon General
  5550. :return: None
  5551. """
  5552. if self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value().upper() == 'METRIC':
  5553. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  5554. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.get_value()
  5555. )
  5556. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  5557. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.get_value()
  5558. )
  5559. else:
  5560. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  5561. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.get_value()
  5562. )
  5563. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  5564. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.get_value()
  5565. )
  5566. def on_excellon_zeros_changed(self):
  5567. """
  5568. Slot activated when the user changes the Excellon zeros values in Preferences -> Excellon -> Excellon General
  5569. :return: None
  5570. """
  5571. self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio.set_value(
  5572. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.get_value() + 'Z'
  5573. )
  5574. def on_excellon_units_changed(self):
  5575. """
  5576. Slot activated when the user changes the Excellon unit values in Preferences -> Excellon -> Excellon General
  5577. :return: None
  5578. """
  5579. self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio.set_value(
  5580. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value()
  5581. )
  5582. self.on_excellon_format_changed()
  5583. def on_film_color_entry(self):
  5584. self.defaults['tools_film_color'] = \
  5585. self.ui.tools_defaults_form.tools_film_group.film_color_entry.get_value()
  5586. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  5587. "background-color:%s;"
  5588. "border-color: dimgray" % str(self.defaults['tools_film_color'])
  5589. )
  5590. def on_film_color_button(self):
  5591. current_color = QtGui.QColor(self.defaults['tools_film_color'])
  5592. c_dialog = QtWidgets.QColorDialog()
  5593. film_color = c_dialog.getColor(initial=current_color)
  5594. if film_color.isValid() is False:
  5595. return
  5596. # if new color is different then mark that the Preferences are changed
  5597. if film_color != current_color:
  5598. self.on_preferences_edited()
  5599. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  5600. "background-color:%s;"
  5601. "border-color: dimgray" % str(film_color.name())
  5602. )
  5603. new_val_sel = str(film_color.name())
  5604. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(new_val_sel)
  5605. self.defaults['tools_film_color'] = new_val_sel
  5606. def on_qrcode_fill_color_entry(self):
  5607. self.defaults['tools_qrcode_fill_color'] = \
  5608. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.get_value()
  5609. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  5610. "background-color:%s;"
  5611. "border-color: dimgray" % str(self.defaults['tools_qrcode_fill_color'])
  5612. )
  5613. def on_qrcode_fill_color_button(self):
  5614. current_color = QtGui.QColor(self.defaults['tools_qrcode_fill_color'])
  5615. c_dialog = QtWidgets.QColorDialog()
  5616. fill_color = c_dialog.getColor(initial=current_color)
  5617. if fill_color.isValid() is False:
  5618. return
  5619. # if new color is different then mark that the Preferences are changed
  5620. if fill_color != current_color:
  5621. self.on_preferences_edited()
  5622. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  5623. "background-color:%s;"
  5624. "border-color: dimgray" % str(fill_color.name())
  5625. )
  5626. new_val_sel = str(fill_color.name())
  5627. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.set_value(new_val_sel)
  5628. self.defaults['tools_qrcode_fill_color'] = new_val_sel
  5629. def on_qrcode_back_color_entry(self):
  5630. self.defaults['tools_qrcode_back_color'] = \
  5631. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.get_value()
  5632. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  5633. "background-color:%s;"
  5634. "border-color: dimgray" % str(self.defaults['tools_qrcode_back_color'])
  5635. )
  5636. def on_qrcode_back_color_button(self):
  5637. current_color = QtGui.QColor(self.defaults['tools_qrcode_back_color'])
  5638. c_dialog = QtWidgets.QColorDialog()
  5639. back_color = c_dialog.getColor(initial=current_color)
  5640. if back_color.isValid() is False:
  5641. return
  5642. # if new color is different then mark that the Preferences are changed
  5643. if back_color != current_color:
  5644. self.on_preferences_edited()
  5645. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  5646. "background-color:%s;"
  5647. "border-color: dimgray" % str(back_color.name())
  5648. )
  5649. new_val_sel = str(back_color.name())
  5650. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.set_value(new_val_sel)
  5651. self.defaults['tools_qrcode_back_color'] = new_val_sel
  5652. def on_tab_rmb_click(self, checked):
  5653. self.ui.notebook.set_detachable(val=checked)
  5654. self.defaults["global_tabs_detachable"] = checked
  5655. self.ui.plot_tab_area.set_detachable(val=checked)
  5656. self.defaults["global_tabs_detachable"] = checked
  5657. def on_tab_setup_context_menu(self):
  5658. initial_checked = self.defaults["global_tabs_detachable"]
  5659. action_name = str(_("Detachable Tabs"))
  5660. action = QtWidgets.QAction(self)
  5661. action.setCheckable(True)
  5662. action.setText(action_name)
  5663. action.setChecked(initial_checked)
  5664. self.ui.notebook.tabBar.addAction(action)
  5665. self.ui.plot_tab_area.tabBar.addAction(action)
  5666. try:
  5667. action.triggered.disconnect()
  5668. except TypeError:
  5669. pass
  5670. action.triggered.connect(self.on_tab_rmb_click)
  5671. def on_deselect_all(self):
  5672. self.collection.set_all_inactive()
  5673. self.delete_selection_shape()
  5674. def on_workspace_modified(self):
  5675. # self.save_defaults(silent=True)
  5676. if self.is_legacy is True:
  5677. self.plotcanvas.delete_workspace()
  5678. self.defaults_read_form()
  5679. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  5680. def on_workspace(self):
  5681. if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value():
  5682. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  5683. else:
  5684. self.plotcanvas.delete_workspace()
  5685. self.defaults_read_form()
  5686. # self.save_defaults(silent=True)
  5687. def on_workspace_toggle(self):
  5688. state = False if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value() else True
  5689. try:
  5690. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.disconnect(self.on_workspace)
  5691. except TypeError:
  5692. pass
  5693. self.ui.general_defaults_form.general_app_set_group.workspace_cb.set_value(state)
  5694. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  5695. self.on_workspace()
  5696. def on_layout(self, index=None, lay=None):
  5697. """
  5698. Set the toolbars layout (location)
  5699. :param index:
  5700. :param lay: type of layout to be set on the toolbard
  5701. :return: None
  5702. """
  5703. self.report_usage("on_layout()")
  5704. if lay:
  5705. current_layout = lay
  5706. else:
  5707. current_layout = self.ui.general_defaults_form.general_gui_group.layout_combo.get_value()
  5708. lay_settings = QSettings("Open Source", "FlatCAM")
  5709. lay_settings.setValue('layout', current_layout)
  5710. # This will write the setting to the platform specific storage.
  5711. del lay_settings
  5712. # first remove the toolbars:
  5713. try:
  5714. self.ui.removeToolBar(self.ui.toolbarfile)
  5715. self.ui.removeToolBar(self.ui.toolbargeo)
  5716. self.ui.removeToolBar(self.ui.toolbarview)
  5717. self.ui.removeToolBar(self.ui.toolbarshell)
  5718. self.ui.removeToolBar(self.ui.toolbartools)
  5719. self.ui.removeToolBar(self.ui.exc_edit_toolbar)
  5720. self.ui.removeToolBar(self.ui.geo_edit_toolbar)
  5721. self.ui.removeToolBar(self.ui.grb_edit_toolbar)
  5722. self.ui.removeToolBar(self.ui.snap_toolbar)
  5723. self.ui.removeToolBar(self.ui.toolbarshell)
  5724. except Exception:
  5725. pass
  5726. if current_layout == 'standard':
  5727. # ## TOOLBAR INSTALLATION # ##
  5728. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  5729. self.ui.toolbarfile.setObjectName('File_TB')
  5730. self.ui.addToolBar(self.ui.toolbarfile)
  5731. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  5732. self.ui.toolbargeo.setObjectName('Edit_TB')
  5733. self.ui.addToolBar(self.ui.toolbargeo)
  5734. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  5735. self.ui.toolbarview.setObjectName('View_TB')
  5736. self.ui.addToolBar(self.ui.toolbarview)
  5737. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  5738. self.ui.toolbarshell.setObjectName('Shell_TB')
  5739. self.ui.addToolBar(self.ui.toolbarshell)
  5740. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  5741. self.ui.toolbartools.setObjectName('Tools_TB')
  5742. self.ui.addToolBar(self.ui.toolbartools)
  5743. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  5744. # self.ui.exc_edit_toolbar.setVisible(False)
  5745. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  5746. self.ui.addToolBar(self.ui.exc_edit_toolbar)
  5747. self.ui.addToolBarBreak()
  5748. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  5749. # self.ui.geo_edit_toolbar.setVisible(False)
  5750. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  5751. self.ui.addToolBar(self.ui.geo_edit_toolbar)
  5752. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  5753. # self.ui.grb_edit_toolbar.setVisible(False)
  5754. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  5755. self.ui.addToolBar(self.ui.grb_edit_toolbar)
  5756. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  5757. self.ui.snap_toolbar.setObjectName('Snap_TB')
  5758. # self.ui.snap_toolbar.setMaximumHeight(30)
  5759. self.ui.addToolBar(self.ui.snap_toolbar)
  5760. self.ui.corner_snap_btn.setVisible(False)
  5761. self.ui.snap_magnet.setVisible(False)
  5762. elif current_layout == 'compact':
  5763. # ## TOOLBAR INSTALLATION # ##
  5764. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  5765. self.ui.toolbarfile.setObjectName('File_TB')
  5766. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarfile)
  5767. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  5768. self.ui.toolbargeo.setObjectName('Edit_TB')
  5769. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbargeo)
  5770. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  5771. self.ui.toolbarshell.setObjectName('Shell_TB')
  5772. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarshell)
  5773. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  5774. self.ui.toolbartools.setObjectName('Tools_TB')
  5775. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbartools)
  5776. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  5777. # self.ui.geo_edit_toolbar.setVisible(False)
  5778. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  5779. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.geo_edit_toolbar)
  5780. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  5781. self.ui.toolbarview.setObjectName('View_TB')
  5782. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.toolbarview)
  5783. self.ui.addToolBarBreak(area=Qt.RightToolBarArea)
  5784. self.ui.grb_edit_toolbar = QtWidgets.QToolBar('Gerber Editor Toolbar')
  5785. # self.ui.grb_edit_toolbar.setVisible(False)
  5786. self.ui.grb_edit_toolbar.setObjectName('GrbEditor_TB')
  5787. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.grb_edit_toolbar)
  5788. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  5789. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  5790. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.exc_edit_toolbar)
  5791. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  5792. self.ui.snap_toolbar.setObjectName('Snap_TB')
  5793. self.ui.snap_toolbar.setMaximumHeight(30)
  5794. self.ui.splitter_left.addWidget(self.ui.snap_toolbar)
  5795. self.ui.corner_snap_btn.setVisible(True)
  5796. self.ui.snap_magnet.setVisible(True)
  5797. # add all the actions to the toolbars
  5798. self.ui.populate_toolbars()
  5799. # reconnect all the signals to the toolbar actions
  5800. self.connect_toolbar_signals()
  5801. self.ui.grid_snap_btn.setChecked(True)
  5802. self.on_grid_snap_triggered(state=True)
  5803. self.ui.grid_gap_x_entry.setText(str(self.defaults["global_gridx"]))
  5804. self.ui.grid_gap_y_entry.setText(str(self.defaults["global_gridy"]))
  5805. self.ui.snap_max_dist_entry.setText(str(self.defaults["global_snap_max"]))
  5806. self.ui.grid_gap_link_cb.setChecked(True)
  5807. def on_cursor_type(self, val):
  5808. """
  5809. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  5810. :return: None
  5811. """
  5812. self.app_cursor.enabled = False
  5813. if val == 'small':
  5814. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(False)
  5815. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(False)
  5816. self.app_cursor = self.plotcanvas.new_cursor()
  5817. else:
  5818. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(True)
  5819. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(True)
  5820. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  5821. if self.ui.grid_snap_btn.isChecked():
  5822. self.app_cursor.enabled = True
  5823. else:
  5824. self.app_cursor.enabled = False
  5825. def on_save_button(self, save_to_file=True):
  5826. log.debug("App.on_save_button() --> Applying preferences to file.")
  5827. # Preferences saved, update flag
  5828. self.preferences_changed_flag = False
  5829. # Preferences save, update the color of the Preferences Tab text
  5830. for idx in range(self.ui.plot_tab_area.count()):
  5831. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  5832. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('black'))
  5833. # restore the default stylesheet by setting a blank one
  5834. self.ui.pref_apply_button.setStyleSheet("")
  5835. self.inform.emit('%s' % _("Preferences applied."))
  5836. # make sure we update the self.current_defaults dict used to undo changes to self.defaults
  5837. self.current_defaults.update(self.defaults)
  5838. if save_to_file:
  5839. self.save_defaults(silent=False)
  5840. # load the defaults so they are updated into the app
  5841. self.load_defaults(filename='current_defaults')
  5842. # Re-fresh project options
  5843. self.on_options_app2project()
  5844. settgs = QSettings("Open Source", "FlatCAM")
  5845. # save the notebook font size
  5846. fsize = self.ui.general_defaults_form.general_app_set_group.notebook_font_size_spinner.get_value()
  5847. settgs.setValue('notebook_font_size', fsize)
  5848. # save the axis font size
  5849. g_fsize = self.ui.general_defaults_form.general_app_set_group.axis_font_size_spinner.get_value()
  5850. settgs.setValue('axis_font_size', g_fsize)
  5851. # save the textbox font size
  5852. tb_fsize = self.ui.general_defaults_form.general_app_set_group.textbox_font_size_spinner.get_value()
  5853. settgs.setValue('textbox_font_size', tb_fsize)
  5854. settgs.setValue(
  5855. 'machinist',
  5856. 1 if self.ui.general_defaults_form.general_app_set_group.machinist_cb.get_value() else 0
  5857. )
  5858. # This will write the setting to the platform specific storage.
  5859. del settgs
  5860. def on_pref_close_button(self):
  5861. # Preferences saved, update flag
  5862. self.preferences_changed_flag = False
  5863. try:
  5864. self.ui.plot_tab_area.tab_closed_signal.disconnect(self.on_plot_area_tab_closed)
  5865. except TypeError:
  5866. pass
  5867. try:
  5868. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  5869. except (TypeError, AttributeError):
  5870. pass
  5871. self.defaults_write_form(source_dict=self.current_defaults)
  5872. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  5873. lambda: self.on_toggle_units(no_pref=False))
  5874. self.defaults.update(self.current_defaults)
  5875. # shared_items = {k: self.defaults[k] for k in self.defaults if k in self.current_defaults and
  5876. # self.defaults[k] == self.current_defaults[k]}
  5877. # print(len(self.defaults), len(shared_items))
  5878. # Preferences save, update the color of the Preferences Tab text
  5879. for idx in range(self.ui.plot_tab_area.count()):
  5880. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  5881. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('black'))
  5882. self.ui.plot_tab_area.closeTab(idx)
  5883. break
  5884. self.inform.emit('%s' % _("Preferences closed without saving."))
  5885. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  5886. def on_tool_add_keypress(self):
  5887. # ## Current application units in Upper Case
  5888. self.units = self.defaults['units'].upper()
  5889. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  5890. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  5891. if notebook_widget_name == 'selected_tab':
  5892. if self.collection.get_active().kind == 'geometry':
  5893. # Tool add works for Geometry only if Advanced is True in Preferences
  5894. if self.defaults["global_app_level"] == 'a':
  5895. tool_add_popup = FCInputDialog(title="New Tool ...",
  5896. text='Enter a Tool Diameter:',
  5897. min=0.0000, max=99.9999, decimals=4)
  5898. tool_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/letter_t_32.png'))
  5899. val, ok = tool_add_popup.get_value()
  5900. if ok:
  5901. if float(val) == 0:
  5902. self.inform.emit('[WARNING_NOTCL] %s' %
  5903. _("Please enter a tool diameter with non-zero value, in Float format."))
  5904. return
  5905. self.collection.get_active().on_tool_add(dia=float(val))
  5906. else:
  5907. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  5908. else:
  5909. msgbox = QtWidgets.QMessageBox()
  5910. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  5911. "Go to Preferences -> General - Show Advanced Options."))
  5912. msgbox.setWindowTitle("Tool adding ...")
  5913. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/warning.png'))
  5914. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5915. msgbox.setDefaultButton(bt_ok)
  5916. msgbox.exec_()
  5917. # work only if the notebook tab on focus is the Tools_Tab
  5918. if notebook_widget_name == 'tool_tab':
  5919. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  5920. # and only if the tool is NCC Tool
  5921. if tool_widget == self.ncclear_tool.toolName:
  5922. self.ncclear_tool.on_add_tool_by_key()
  5923. # and only if the tool is Paint Area Tool
  5924. elif tool_widget == self.paint_tool.toolName:
  5925. self.paint_tool.on_add_tool_by_key()
  5926. # and only if the tool is Solder Paste Dispensing Tool
  5927. elif tool_widget == self.paste_tool.toolName:
  5928. self.paste_tool.on_add_tool_by_key()
  5929. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  5930. # See description bellow.
  5931. def on_delete_keypress(self):
  5932. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  5933. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  5934. if notebook_widget_name == 'selected_tab':
  5935. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  5936. self.collection.get_active().on_tool_delete()
  5937. # work only if the notebook tab on focus is the Tools_Tab
  5938. elif notebook_widget_name == 'tool_tab':
  5939. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  5940. # and only if the tool is NCC Tool
  5941. if tool_widget == self.ncclear_tool.toolName:
  5942. self.ncclear_tool.on_tool_delete()
  5943. # and only if the tool is Paint Tool
  5944. elif tool_widget == self.paint_tool.toolName:
  5945. self.paint_tool.on_tool_delete()
  5946. # and only if the tool is Solder Paste Dispensing Tool
  5947. elif tool_widget == self.paste_tool.toolName:
  5948. self.paste_tool.on_tool_delete()
  5949. else:
  5950. self.on_delete()
  5951. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  5952. # some screens you have to be careful where you hover with your mouse.
  5953. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  5954. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  5955. # Complicated, I know :)
  5956. def on_delete(self):
  5957. """
  5958. Delete the currently selected FlatCAMObjs.
  5959. :return: None
  5960. """
  5961. self.report_usage("on_delete()")
  5962. response = None
  5963. bt_ok = None
  5964. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  5965. # a geometry object before we update it.
  5966. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  5967. and self.grb_editor.editor_active is False:
  5968. if self.defaults["global_delete_confirmation"] is True:
  5969. msgbox = QtWidgets.QMessageBox()
  5970. msgbox.setWindowTitle(_("Delete objects"))
  5971. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/deleteshape32.png'))
  5972. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  5973. msgbox.setText(_("Are you sure you want to permanently delete\n"
  5974. "the selected objects?"))
  5975. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  5976. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  5977. msgbox.setDefaultButton(bt_ok)
  5978. msgbox.exec_()
  5979. response = msgbox.clickedButton()
  5980. if response == bt_ok or self.defaults["global_delete_confirmation"] is False:
  5981. if self.collection.get_active():
  5982. self.log.debug("App.on_delete()")
  5983. while self.collection.get_active():
  5984. obj_active = self.collection.get_active()
  5985. # if the deleted object is FlatCAMGerber then make sure to delete the possible mark shapes
  5986. if isinstance(obj_active, FlatCAMGerber):
  5987. for el in obj_active.mark_shapes:
  5988. obj_active.mark_shapes[el].clear(update=True)
  5989. obj_active.mark_shapes[el].enabled = False
  5990. # obj_active.mark_shapes[el] = None
  5991. del el
  5992. elif isinstance(obj_active, FlatCAMCNCjob):
  5993. try:
  5994. obj_active.annotation.clear(update=True)
  5995. obj_active.annotation.enabled = False
  5996. except AttributeError:
  5997. pass
  5998. self.delete_first_selected()
  5999. self.inform.emit('%s...' % _("Object(s) deleted"))
  6000. # make sure that the selection shape is deleted, too
  6001. self.delete_selection_shape()
  6002. else:
  6003. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  6004. else:
  6005. self.inform.emit(_("Save the work in Editor and try again ..."))
  6006. def delete_first_selected(self):
  6007. # Keep this for later
  6008. try:
  6009. sel_obj = self.collection.get_active()
  6010. name = sel_obj.options["name"]
  6011. isPlotted = sel_obj.options["plot"]
  6012. except AttributeError:
  6013. self.log.debug("Nothing selected for deletion")
  6014. return
  6015. if self.is_legacy is True:
  6016. # Remove plot only if the object was plotted otherwise delaxes will fail
  6017. if isPlotted:
  6018. try:
  6019. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  6020. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  6021. except Exception as e:
  6022. log.debug("App.delete_first_selected() --> %s" % str(e))
  6023. self.plotcanvas.auto_adjust_axes()
  6024. # Remove from dictionary
  6025. self.collection.delete_active()
  6026. # Clear form
  6027. self.setup_component_editor()
  6028. self.inform.emit('%s: %s' %
  6029. (_("Object deleted"), name))
  6030. def on_set_origin(self):
  6031. """
  6032. Set the origin to the left mouse click position
  6033. :return: None
  6034. """
  6035. # display the message for the user
  6036. # and ask him to click on the desired position
  6037. self.report_usage("on_set_origin()")
  6038. def origin_replot():
  6039. def worker_task():
  6040. with self.proc_container.new('%s...' % _("Plotting")):
  6041. for obj in self.collection.get_list():
  6042. obj.plot()
  6043. self.plotcanvas.fit_view()
  6044. if self.is_legacy:
  6045. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  6046. else:
  6047. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  6048. self.worker_task.emit({'fcn': worker_task, 'params': []})
  6049. self.inform.emit(_('Click to set the origin ...'))
  6050. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  6051. # first disconnect it as it may have been used by something else
  6052. try:
  6053. self.replot_signal.disconnect()
  6054. except TypeError:
  6055. pass
  6056. self.replot_signal[list].connect(origin_replot)
  6057. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  6058. """
  6059. :param event:
  6060. :param location:
  6061. :param noplot:
  6062. :param use_thread:
  6063. :return:
  6064. """
  6065. noplot_sig = noplot
  6066. def worker_task():
  6067. with self.proc_container.new(_("Setting Origin...")):
  6068. for obj in self.collection.get_list():
  6069. obj.offset((x, y))
  6070. self.object_changed.emit(obj)
  6071. # Update the object bounding box options
  6072. a, b, c, d = obj.bounds()
  6073. obj.options['xmin'] = a
  6074. obj.options['ymin'] = b
  6075. obj.options['xmax'] = c
  6076. obj.options['ymax'] = d
  6077. self.inform.emit('[success] %s...' % _('Origin set'))
  6078. if noplot_sig is False:
  6079. self.replot_signal.emit([])
  6080. if location is not None:
  6081. if len(location) != 2:
  6082. self.inform.emit('[ERROR_NOTCL] %s...' % _("Origin coordinates specified but incomplete."))
  6083. return 'fail'
  6084. x, y = location
  6085. if use_thread is True:
  6086. self.worker_task.emit({'fcn': worker_task, 'params': []})
  6087. else:
  6088. worker_task()
  6089. self.should_we_save = True
  6090. return
  6091. if event.button == 1:
  6092. if self.is_legacy is False:
  6093. event_pos = event.pos
  6094. else:
  6095. event_pos = (event.xdata, event.ydata)
  6096. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  6097. if self.grid_status() == True:
  6098. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  6099. else:
  6100. pos = pos_canvas
  6101. x = 0 - pos[0]
  6102. y = 0 - pos[1]
  6103. if use_thread is True:
  6104. self.worker_task.emit({'fcn': worker_task, 'params': []})
  6105. else:
  6106. worker_task()
  6107. self.should_we_save = True
  6108. def on_jump_to(self, custom_location=None, fit_center=True):
  6109. """
  6110. Jump to a location by setting the mouse cursor location
  6111. :return:
  6112. """
  6113. self.report_usage("on_jump_to()")
  6114. if not custom_location:
  6115. dia_box_location = None
  6116. try:
  6117. dia_box_location = eval(self.clipboard.text())
  6118. except Exception:
  6119. pass
  6120. if type(dia_box_location) == tuple:
  6121. dia_box_location = str(dia_box_location)
  6122. else:
  6123. dia_box_location = None
  6124. # dia_box = Dialog_box(title=_("Jump to ..."),
  6125. # label=_("Enter the coordinates in format X,Y:"),
  6126. # icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  6127. # initial_text=dia_box_location)
  6128. dia_box = DialogBoxRadio(title=_("Jump to ..."),
  6129. label=_("Enter the coordinates in format X,Y:"),
  6130. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  6131. initial_text=dia_box_location,
  6132. reference=self.defaults['global_jump_ref'])
  6133. if dia_box.ok is True:
  6134. try:
  6135. location = eval(dia_box.location)
  6136. if not isinstance(location, tuple):
  6137. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  6138. return
  6139. if dia_box.reference == 'rel':
  6140. rel_x = self.mouse[0] + location[0]
  6141. rel_y = self.mouse[1] + location[1]
  6142. location = (rel_x, rel_y)
  6143. self.defaults['global_jump_ref'] = dia_box.reference
  6144. except Exception:
  6145. return
  6146. else:
  6147. return
  6148. else:
  6149. location = custom_location
  6150. self.jump_signal.emit(location)
  6151. if fit_center:
  6152. self.plotcanvas.fit_center(loc=location)
  6153. cursor = QtGui.QCursor()
  6154. if self.is_legacy is False:
  6155. # I don't know where those differences come from but they are constant for the current
  6156. # execution of the application and they are multiples of a value around 0.0263mm.
  6157. # In a random way sometimes they are more sometimes they are less
  6158. # if units == 'MM':
  6159. # cal_factor = 0.0263
  6160. # else:
  6161. # cal_factor = 0.0263 / 25.4
  6162. cal_location = (location[0], location[1])
  6163. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  6164. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  6165. j_pos = (
  6166. int(canvas_origin.x() + round(jump_loc[0])),
  6167. int(canvas_origin.y() + round(jump_loc[1]))
  6168. )
  6169. cursor.setPos(j_pos[0], j_pos[1])
  6170. else:
  6171. # find the canvas origin which is in the top left corner
  6172. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  6173. # determine the coordinates for the lowest left point of the canvas
  6174. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  6175. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  6176. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  6177. # canvas) and the point (width, height) is in the top-right location
  6178. loc = self.plotcanvas.axes.transData.transform_point(location)
  6179. j_pos = (
  6180. int(x0 + loc[0]),
  6181. int(y0 - loc[1])
  6182. )
  6183. cursor.setPos(j_pos[0], j_pos[1])
  6184. self.plotcanvas.mouse = [location[0], location[1]]
  6185. if self.defaults["global_cursor_color_enabled"] is True:
  6186. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  6187. else:
  6188. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  6189. if self.grid_status():
  6190. # Update cursor
  6191. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  6192. symbol='++', edge_color=self.cursor_color_3D,
  6193. edge_width=self.defaults["global_cursor_width"],
  6194. size=self.defaults["global_cursor_size"])
  6195. # Set the position label
  6196. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  6197. "<b>Y</b>: %.4f" % (location[0], location[1]))
  6198. # Set the relative position label
  6199. dx = location[0] - float(self.rel_point1[0])
  6200. dy = location[1] - float(self.rel_point1[1])
  6201. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  6202. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  6203. self.inform.emit('[success] %s' % _("Done."))
  6204. return location
  6205. def on_locate(self, obj, fit_center=True):
  6206. """
  6207. Jump to one of the corners (or center) of an object by setting the mouse cursor location
  6208. :return:
  6209. """
  6210. self.report_usage("on_locate()")
  6211. if obj is None:
  6212. self.inform.emit('[WARNING_NOTCL] %s' % _("There is no object selected..."))
  6213. return 'fail'
  6214. class DialogBoxChoice(QtWidgets.QDialog):
  6215. def __init__(self, title=None, icon=None, choice='bl'):
  6216. """
  6217. :param title: string with the window title
  6218. """
  6219. super(DialogBoxChoice, self).__init__()
  6220. self.ok = False
  6221. self.setWindowIcon(icon)
  6222. self.setWindowTitle(str(title))
  6223. self.form = QtWidgets.QFormLayout(self)
  6224. self.ref_radio = RadioSet([
  6225. {"label": _("Bottom-Left"), "value": "bl"},
  6226. {"label": _("Top-Left"), "value": "tl"},
  6227. {"label": _("Bottom-Right"), "value": "br"},
  6228. {"label": _("Top-Right"), "value": "tr"},
  6229. {"label": _("Center"), "value": "c"}
  6230. ], orientation='vertical', stretch=False)
  6231. self.ref_radio.set_value(choice)
  6232. self.form.addRow(self.ref_radio)
  6233. self.button_box = QtWidgets.QDialogButtonBox(
  6234. QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,
  6235. Qt.Horizontal, parent=self)
  6236. self.form.addRow(self.button_box)
  6237. self.button_box.accepted.connect(self.accept)
  6238. self.button_box.rejected.connect(self.reject)
  6239. if self.exec_() == QtWidgets.QDialog.Accepted:
  6240. self.ok = True
  6241. self.location_point = self.ref_radio.get_value()
  6242. else:
  6243. self.ok = False
  6244. self.location_point = None
  6245. dia_box = DialogBoxChoice(title=_("Locate ..."),
  6246. icon=QtGui.QIcon(self.resource_location + '/locate16.png'),
  6247. choice=self.defaults['global_locate_pt'])
  6248. if dia_box.ok is True:
  6249. try:
  6250. location_point = dia_box.location_point
  6251. self.defaults['global_locate_pt'] = dia_box.location_point
  6252. except Exception:
  6253. return
  6254. else:
  6255. return
  6256. loc_b = obj.bounds()
  6257. if location_point == 'bl':
  6258. location = (loc_b[0], loc_b[1])
  6259. elif location_point == 'tl':
  6260. location = (loc_b[0], loc_b[3])
  6261. elif location_point == 'br':
  6262. location = (loc_b[2], loc_b[1])
  6263. elif location_point == 'tr':
  6264. location = (loc_b[2], loc_b[3])
  6265. else:
  6266. # center
  6267. cx = loc_b[0] + ((loc_b[2] - loc_b[0]) / 2)
  6268. cy = loc_b[1] + ((loc_b[3] - loc_b[1]) / 2)
  6269. location = (cx, cy)
  6270. self.locate_signal.emit(location, location_point)
  6271. if fit_center:
  6272. self.plotcanvas.fit_center(loc=location)
  6273. cursor = QtGui.QCursor()
  6274. if self.is_legacy is False:
  6275. # I don't know where those differences come from but they are constant for the current
  6276. # execution of the application and they are multiples of a value around 0.0263mm.
  6277. # In a random way sometimes they are more sometimes they are less
  6278. # if units == 'MM':
  6279. # cal_factor = 0.0263
  6280. # else:
  6281. # cal_factor = 0.0263 / 25.4
  6282. cal_location = (location[0], location[1])
  6283. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  6284. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  6285. j_pos = (
  6286. int(canvas_origin.x() + round(jump_loc[0])),
  6287. int(canvas_origin.y() + round(jump_loc[1]))
  6288. )
  6289. cursor.setPos(j_pos[0], j_pos[1])
  6290. else:
  6291. # find the canvas origin which is in the top left corner
  6292. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  6293. # determine the coordinates for the lowest left point of the canvas
  6294. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  6295. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  6296. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  6297. # canvas) and the point (width, height) is in the top-right location
  6298. loc = self.plotcanvas.axes.transData.transform_point(location)
  6299. j_pos = (
  6300. int(x0 + loc[0]),
  6301. int(y0 - loc[1])
  6302. )
  6303. cursor.setPos(j_pos[0], j_pos[1])
  6304. self.plotcanvas.mouse = [location[0], location[1]]
  6305. if self.defaults["global_cursor_color_enabled"] is True:
  6306. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  6307. else:
  6308. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  6309. if self.grid_status():
  6310. # Update cursor
  6311. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  6312. symbol='++', edge_color=self.cursor_color_3D,
  6313. edge_width=self.defaults["global_cursor_width"],
  6314. size=self.defaults["global_cursor_size"])
  6315. # Set the position label
  6316. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  6317. "<b>Y</b>: %.4f" % (location[0], location[1]))
  6318. # Set the relative position label
  6319. dx = location[0] - float(self.rel_point1[0])
  6320. dy = location[1] - float(self.rel_point1[1])
  6321. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  6322. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  6323. self.inform.emit('[success] %s' % _("Done."))
  6324. return location
  6325. def on_copy_command(self):
  6326. self.report_usage("on_copy_command()")
  6327. def initialize(obj_init, app):
  6328. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  6329. try:
  6330. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  6331. except AttributeError:
  6332. pass
  6333. try:
  6334. obj_init.apertures = deepcopy(obj.apertures)
  6335. except AttributeError:
  6336. pass
  6337. try:
  6338. if obj.tools:
  6339. obj_init.tools = deepcopy(obj.tools)
  6340. except Exception as e:
  6341. log.debug("App.on_copy_command() --> %s" % str(e))
  6342. try:
  6343. obj_init.source_file = deepcopy(obj.source_file)
  6344. except (AttributeError, TypeError):
  6345. pass
  6346. def initialize_excellon(obj_init, app):
  6347. obj_init.source_file = deepcopy(obj.source_file)
  6348. obj_init.tools = deepcopy(obj.tools)
  6349. # drills are offset, so they need to be deep copied
  6350. obj_init.drills = deepcopy(obj.drills)
  6351. # slots are offset, so they need to be deep copied
  6352. obj_init.slots = deepcopy(obj.slots)
  6353. obj_init.create_geometry()
  6354. def initialize_script(obj_init, app_obj):
  6355. obj_init.source_file = deepcopy(obj.source_file)
  6356. def initialize_document(obj_init, app_obj):
  6357. obj_init.source_file = deepcopy(obj.source_file)
  6358. for obj in self.collection.get_selected():
  6359. obj_name = obj.options["name"]
  6360. try:
  6361. if isinstance(obj, FlatCAMExcellon):
  6362. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  6363. elif isinstance(obj, FlatCAMGerber):
  6364. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  6365. elif isinstance(obj, FlatCAMGeometry):
  6366. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  6367. elif isinstance(obj, FlatCAMScript):
  6368. self.new_object("script", str(obj_name) + "_copy", initialize_script)
  6369. elif isinstance(obj, FlatCAMDocument):
  6370. self.new_object("document", str(obj_name) + "_copy", initialize_document)
  6371. except Exception as e:
  6372. return "Operation failed: %s" % str(e)
  6373. def on_paste_command(self):
  6374. pass
  6375. def on_copy_object2(self, custom_name):
  6376. def initialize_geometry(obj_init, app):
  6377. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  6378. try:
  6379. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  6380. except AttributeError:
  6381. pass
  6382. try:
  6383. obj_init.apertures = deepcopy(obj.apertures)
  6384. except AttributeError:
  6385. pass
  6386. try:
  6387. if obj.tools:
  6388. obj_init.tools = deepcopy(obj.tools)
  6389. except Exception as ee:
  6390. log.debug("on_copy_object2() --> %s" % str(ee))
  6391. def initialize_gerber(obj_init, app):
  6392. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  6393. obj_init.apertures = deepcopy(obj.apertures)
  6394. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  6395. def initialize_excellon(obj_init, app):
  6396. obj_init.tools = deepcopy(obj.tools)
  6397. # drills are offset, so they need to be deep copied
  6398. obj_init.drills = deepcopy(obj.drills)
  6399. # slots are offset, so they need to be deep copied
  6400. obj_init.slots = deepcopy(obj.slots)
  6401. obj_init.create_geometry()
  6402. for obj in self.collection.get_selected():
  6403. obj_name = obj.options["name"]
  6404. try:
  6405. if isinstance(obj, FlatCAMExcellon):
  6406. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  6407. elif isinstance(obj, FlatCAMGerber):
  6408. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  6409. elif isinstance(obj, FlatCAMGeometry):
  6410. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  6411. except Exception as e:
  6412. return "Operation failed: %s" % str(e)
  6413. def on_rename_object(self, text):
  6414. self.report_usage("on_rename_object()")
  6415. named_obj = self.collection.get_active()
  6416. for obj in named_obj:
  6417. if obj is list:
  6418. self.on_rename_object(text)
  6419. else:
  6420. try:
  6421. obj.options['name'] = text
  6422. except Exception as e:
  6423. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  6424. def convert_any2geo(self):
  6425. self.report_usage("convert_any2geo()")
  6426. def initialize(obj_init, app):
  6427. obj_init.solid_geometry = obj.solid_geometry
  6428. try:
  6429. obj_init.follow_geometry = obj.follow_geometry
  6430. except AttributeError:
  6431. pass
  6432. try:
  6433. obj_init.apertures = obj.apertures
  6434. except AttributeError:
  6435. pass
  6436. try:
  6437. if obj.tools:
  6438. obj_init.tools = obj.tools
  6439. except AttributeError:
  6440. pass
  6441. def initialize_excellon(obj_init, app):
  6442. # objs = self.collection.get_selected()
  6443. # FlatCAMGeometry.merge(objs, obj)
  6444. solid_geo = []
  6445. for tool in obj.tools:
  6446. for geo in obj.tools[tool]['solid_geometry']:
  6447. solid_geo.append(geo)
  6448. obj_init.solid_geometry = deepcopy(solid_geo)
  6449. if not self.collection.get_selected():
  6450. log.warning("App.convert_any2geo --> No object selected")
  6451. self.inform.emit('[WARNING_NOTCL] %s' %
  6452. _("No object is selected. Select an object and try again."))
  6453. return
  6454. for obj in self.collection.get_selected():
  6455. obj_name = obj.options["name"]
  6456. try:
  6457. if isinstance(obj, FlatCAMExcellon):
  6458. self.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  6459. else:
  6460. self.new_object("geometry", str(obj_name) + "_conv", initialize)
  6461. except Exception as e:
  6462. return "Operation failed: %s" % str(e)
  6463. def convert_any2gerber(self):
  6464. self.report_usage("convert_any2gerber()")
  6465. def initialize_geometry(obj_init, app):
  6466. apertures = {}
  6467. apid = 0
  6468. apertures[str(apid)] = {}
  6469. apertures[str(apid)]['geometry'] = []
  6470. for obj_orig in obj.solid_geometry:
  6471. new_elem = dict()
  6472. new_elem['solid'] = obj_orig
  6473. try:
  6474. new_elem['follow'] = obj_orig.exterior
  6475. except AttributeError:
  6476. pass
  6477. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  6478. apertures[str(apid)]['size'] = 0.0
  6479. apertures[str(apid)]['type'] = 'C'
  6480. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  6481. obj_init.apertures = deepcopy(apertures)
  6482. def initialize_excellon(obj_init, app):
  6483. apertures = {}
  6484. apid = 10
  6485. for tool in obj.tools:
  6486. apertures[str(apid)] = {}
  6487. apertures[str(apid)]['geometry'] = []
  6488. for geo in obj.tools[tool]['solid_geometry']:
  6489. new_el = dict()
  6490. new_el['solid'] = geo
  6491. new_el['follow'] = geo.exterior
  6492. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  6493. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  6494. apertures[str(apid)]['type'] = 'C'
  6495. apid += 1
  6496. # create solid_geometry
  6497. solid_geometry = []
  6498. for apid in apertures:
  6499. for geo_el in apertures[apid]['geometry']:
  6500. solid_geometry.append(geo_el['solid'])
  6501. solid_geometry = MultiPolygon(solid_geometry)
  6502. solid_geometry = solid_geometry.buffer(0.0000001)
  6503. obj_init.solid_geometry = deepcopy(solid_geometry)
  6504. obj_init.apertures = deepcopy(apertures)
  6505. # clear the working objects (perhaps not necessary due of Python GC)
  6506. apertures.clear()
  6507. if not self.collection.get_selected():
  6508. log.warning("App.convert_any2gerber --> No object selected")
  6509. self.inform.emit('[WARNING_NOTCL] %s' %
  6510. _("No object is selected. Select an object and try again."))
  6511. return
  6512. for obj in self.collection.get_selected():
  6513. obj_name = obj.options["name"]
  6514. try:
  6515. if isinstance(obj, FlatCAMExcellon):
  6516. self.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  6517. elif isinstance(obj, FlatCAMGeometry):
  6518. self.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  6519. else:
  6520. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  6521. except Exception as e:
  6522. return "Operation failed: %s" % str(e)
  6523. def abort_all_tasks(self):
  6524. if self.abort_flag is False:
  6525. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  6526. self.abort_flag = True
  6527. def app_is_idle(self):
  6528. if self.abort_flag:
  6529. self.inform.emit('[WARNING_NOTCL] %s' %
  6530. _("The current task was gracefully closed on user request..."))
  6531. self.abort_flag = False
  6532. def on_selectall(self):
  6533. self.report_usage("on_selectall()")
  6534. # delete the possible selection box around a possible selected object
  6535. self.delete_selection_shape()
  6536. for name in self.collection.get_names():
  6537. self.collection.set_active(name)
  6538. curr_sel_obj = self.collection.get_by_name(name)
  6539. # create the selection box around the selected object
  6540. if self.defaults['global_selection_shape'] is True:
  6541. self.draw_selection_shape(curr_sel_obj)
  6542. def on_preferences(self):
  6543. """
  6544. Adds the Preferences in a Tab in Plot Area
  6545. :return:
  6546. """
  6547. # add the tab if it was closed
  6548. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  6549. # delete the absolute and relative position and messages in the infobar
  6550. self.ui.position_label.setText("")
  6551. self.ui.rel_position_label.setText("")
  6552. # Switch plot_area to preferences page
  6553. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  6554. # self.ui.show()
  6555. # detect changes in the preferences
  6556. for idx in range(self.ui.pref_tab_area.count()):
  6557. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  6558. try:
  6559. try:
  6560. tb.textEdited.disconnect(self.on_preferences_edited)
  6561. except (TypeError, AttributeError):
  6562. pass
  6563. tb.textEdited.connect(self.on_preferences_edited)
  6564. except AttributeError:
  6565. pass
  6566. try:
  6567. try:
  6568. tb.modificationChanged.disconnect(self.on_preferences_edited)
  6569. except (TypeError, AttributeError):
  6570. pass
  6571. tb.modificationChanged.connect(self.on_preferences_edited)
  6572. except AttributeError:
  6573. pass
  6574. try:
  6575. try:
  6576. tb.toggled.disconnect(self.on_preferences_edited)
  6577. except (TypeError, AttributeError):
  6578. pass
  6579. tb.toggled.connect(self.on_preferences_edited)
  6580. except AttributeError:
  6581. pass
  6582. try:
  6583. try:
  6584. tb.valueChanged.disconnect(self.on_preferences_edited)
  6585. except (TypeError, AttributeError):
  6586. pass
  6587. tb.valueChanged.connect(self.on_preferences_edited)
  6588. except AttributeError:
  6589. pass
  6590. try:
  6591. try:
  6592. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  6593. except (TypeError, AttributeError):
  6594. pass
  6595. tb.currentIndexChanged.connect(self.on_preferences_edited)
  6596. except AttributeError:
  6597. pass
  6598. def on_preferences_edited(self):
  6599. if self.preferences_changed_flag is False:
  6600. self.inform.emit('[WARNING_NOTCL] %s' % _("Preferences edited but not saved."))
  6601. for idx in range(self.ui.plot_tab_area.count()):
  6602. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  6603. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  6604. self.ui.pref_apply_button.setStyleSheet("QPushButton {color: red;}")
  6605. self.preferences_changed_flag = True
  6606. def on_tools_database(self):
  6607. """
  6608. Adds the Tools Database in a Tab in Plot Area
  6609. :return:
  6610. """
  6611. for idx in range(self.ui.plot_tab_area.count()):
  6612. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  6613. # there can be only one instance of Tools Database at one time
  6614. return
  6615. self.tools_db_tab = ToolsDB(
  6616. app=self,
  6617. parent=self.ui,
  6618. callback_on_edited=self.on_tools_db_edited,
  6619. callback_on_tool_request=self.on_geometry_tool_add_from_db_executed
  6620. )
  6621. # add the tab if it was closed
  6622. self.ui.plot_tab_area.addTab(self.tools_db_tab, _("Tools Database"))
  6623. self.tools_db_tab.setObjectName("database_tab")
  6624. # delete the absolute and relative position and messages in the infobar
  6625. self.ui.position_label.setText("")
  6626. self.ui.rel_position_label.setText("")
  6627. # Switch plot_area to preferences page
  6628. self.ui.plot_tab_area.setCurrentWidget(self.tools_db_tab)
  6629. # detect changes in the Tools in Tools DB, connect signals from table widget in tab
  6630. self.tools_db_tab.ui_connect()
  6631. def on_tools_db_edited(self):
  6632. self.inform.emit('[WARNING_NOTCL] %s' % _("Tools in Tools Database edited but not saved."))
  6633. for idx in range(self.ui.plot_tab_area.count()):
  6634. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  6635. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  6636. self.tools_db_changed_flag = True
  6637. def on_geometry_tool_add_from_db_executed(self, tool):
  6638. """
  6639. Here add the tool from DB in the selected geometry object
  6640. :return:
  6641. """
  6642. tool_from_db = deepcopy(tool)
  6643. obj = self.collection.get_active()
  6644. if isinstance(obj, FlatCAMGeometry):
  6645. obj.on_tool_from_db_inserted(tool=tool_from_db)
  6646. for idx in range(self.ui.plot_tab_area.count()):
  6647. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  6648. wdg = self.ui.plot_tab_area.widget(idx)
  6649. wdg.deleteLater()
  6650. self.ui.plot_tab_area.removeTab(idx)
  6651. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  6652. else:
  6653. self.inform.emit('[ERROR_NOTCL] %s' % _("Adding tool from DB is not allowed for this object."))
  6654. def on_plot_area_tab_closed(self, title):
  6655. if title == _("Preferences"):
  6656. # disconnect
  6657. for idx in range(self.ui.pref_tab_area.count()):
  6658. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  6659. try:
  6660. tb.textEdited.disconnect(self.on_preferences_edited)
  6661. except (TypeError, AttributeError):
  6662. pass
  6663. try:
  6664. tb.modificationChanged.disconnect(self.on_preferences_edited)
  6665. except (TypeError, AttributeError):
  6666. pass
  6667. try:
  6668. tb.toggled.disconnect(self.on_preferences_edited)
  6669. except (TypeError, AttributeError):
  6670. pass
  6671. try:
  6672. tb.valueChanged.disconnect(self.on_preferences_edited)
  6673. except (TypeError, AttributeError):
  6674. pass
  6675. try:
  6676. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  6677. except (TypeError, AttributeError):
  6678. pass
  6679. if self.preferences_changed_flag is True:
  6680. msgbox = QtWidgets.QMessageBox()
  6681. msgbox.setText(_("One or more values are changed.\n"
  6682. "Do you want to save the Preferences?"))
  6683. msgbox.setWindowTitle(_("Save Preferences"))
  6684. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  6685. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  6686. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  6687. msgbox.setDefaultButton(bt_yes)
  6688. msgbox.exec_()
  6689. response = msgbox.clickedButton()
  6690. if response == bt_yes:
  6691. self.on_save_button(save_to_file=True)
  6692. self.inform.emit('[success] %s' % _("Preferences saved."))
  6693. else:
  6694. self.preferences_changed_flag = False
  6695. self.inform.emit('')
  6696. return
  6697. if title == _("Tools Database"):
  6698. # disconnect the signals from the table widget in tab
  6699. self.tools_db_tab.ui_disconnect()
  6700. if self.tools_db_changed_flag is True:
  6701. msgbox = QtWidgets.QMessageBox()
  6702. msgbox.setText(_("One or more Tools are edited.\n"
  6703. "Do you want to update the Tools Database?"))
  6704. msgbox.setWindowTitle(_("Save Tools Database"))
  6705. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  6706. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  6707. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  6708. msgbox.setDefaultButton(bt_yes)
  6709. msgbox.exec_()
  6710. response = msgbox.clickedButton()
  6711. if response == bt_yes:
  6712. self.tools_db_tab.on_save_tools_db()
  6713. self.inform.emit('[success] %s' % "Tools DB saved to file.")
  6714. else:
  6715. self.tools_db_changed_flag = False
  6716. self.inform.emit('')
  6717. return
  6718. self.tools_db_tab.deleteLater()
  6719. if title == _("Code Editor"):
  6720. self.toggle_codeeditor = False
  6721. if title == _("Bookmarks Manager"):
  6722. self.book_dialog_tab.rebuild_actions()
  6723. self.book_dialog_tab.deleteLater()
  6724. def on_flipy(self):
  6725. self.report_usage("on_flipy()")
  6726. obj_list = self.collection.get_selected()
  6727. xminlist = []
  6728. yminlist = []
  6729. xmaxlist = []
  6730. ymaxlist = []
  6731. if not obj_list:
  6732. self.inform.emit('[WARNING_NOTCL] %s' %
  6733. _("No object selected to Flip on Y axis."))
  6734. else:
  6735. try:
  6736. # first get a bounding box to fit all
  6737. for obj in obj_list:
  6738. xmin, ymin, xmax, ymax = obj.bounds()
  6739. xminlist.append(xmin)
  6740. yminlist.append(ymin)
  6741. xmaxlist.append(xmax)
  6742. ymaxlist.append(ymax)
  6743. # get the minimum x,y and maximum x,y for all objects selected
  6744. xminimal = min(xminlist)
  6745. yminimal = min(yminlist)
  6746. xmaximal = max(xmaxlist)
  6747. ymaximal = max(ymaxlist)
  6748. px = 0.5 * (xminimal + xmaximal)
  6749. py = 0.5 * (yminimal + ymaximal)
  6750. # execute mirroring
  6751. for obj in obj_list:
  6752. obj.mirror('X', [px, py])
  6753. obj.plot()
  6754. self.object_changed.emit(obj)
  6755. self.inform.emit('[success] %s' %
  6756. _("Flip on Y axis done."))
  6757. except Exception as e:
  6758. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  6759. return
  6760. def on_flipx(self):
  6761. self.report_usage("on_flipx()")
  6762. obj_list = self.collection.get_selected()
  6763. xminlist = []
  6764. yminlist = []
  6765. xmaxlist = []
  6766. ymaxlist = []
  6767. if not obj_list:
  6768. self.inform.emit('[WARNING_NOTCL] %s' %
  6769. _("No object selected to Flip on X axis."))
  6770. else:
  6771. try:
  6772. # first get a bounding box to fit all
  6773. for obj in obj_list:
  6774. xmin, ymin, xmax, ymax = obj.bounds()
  6775. xminlist.append(xmin)
  6776. yminlist.append(ymin)
  6777. xmaxlist.append(xmax)
  6778. ymaxlist.append(ymax)
  6779. # get the minimum x,y and maximum x,y for all objects selected
  6780. xminimal = min(xminlist)
  6781. yminimal = min(yminlist)
  6782. xmaximal = max(xmaxlist)
  6783. ymaximal = max(ymaxlist)
  6784. px = 0.5 * (xminimal + xmaximal)
  6785. py = 0.5 * (yminimal + ymaximal)
  6786. # execute mirroring
  6787. for obj in obj_list:
  6788. obj.mirror('Y', [px, py])
  6789. obj.plot()
  6790. self.object_changed.emit(obj)
  6791. self.inform.emit('[success] %s' %
  6792. _("Flip on X axis done."))
  6793. except Exception as e:
  6794. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  6795. return
  6796. def on_rotate(self, silent=False, preset=None):
  6797. self.report_usage("on_rotate()")
  6798. obj_list = self.collection.get_selected()
  6799. xminlist = []
  6800. yminlist = []
  6801. xmaxlist = []
  6802. ymaxlist = []
  6803. if not obj_list:
  6804. self.inform.emit('[WARNING_NOTCL] %s' %
  6805. _("No object selected to Rotate."))
  6806. else:
  6807. if silent is False:
  6808. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6809. min=-360, max=360, decimals=4,
  6810. init_val=float(self.defaults['tools_transform_rotate']))
  6811. num, ok = rotatebox.get_value()
  6812. else:
  6813. num = preset
  6814. ok = True
  6815. if ok:
  6816. try:
  6817. # first get a bounding box to fit all
  6818. for obj in obj_list:
  6819. xmin, ymin, xmax, ymax = obj.bounds()
  6820. xminlist.append(xmin)
  6821. yminlist.append(ymin)
  6822. xmaxlist.append(xmax)
  6823. ymaxlist.append(ymax)
  6824. # get the minimum x,y and maximum x,y for all objects selected
  6825. xminimal = min(xminlist)
  6826. yminimal = min(yminlist)
  6827. xmaximal = max(xmaxlist)
  6828. ymaximal = max(ymaxlist)
  6829. px = 0.5 * (xminimal + xmaximal)
  6830. py = 0.5 * (yminimal + ymaximal)
  6831. for sel_obj in obj_list:
  6832. sel_obj.rotate(-float(num), point=(px, py))
  6833. sel_obj.plot()
  6834. self.object_changed.emit(sel_obj)
  6835. self.inform.emit('[success] %s' %
  6836. _("Rotation done."))
  6837. except Exception as e:
  6838. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Rotation movement was not executed."), str(e)))
  6839. return
  6840. def on_skewx(self):
  6841. self.report_usage("on_skewx()")
  6842. obj_list = self.collection.get_selected()
  6843. xminlist = []
  6844. yminlist = []
  6845. if not obj_list:
  6846. self.inform.emit('[WARNING_NOTCL] %s' %
  6847. _("No object selected to Skew/Shear on X axis."))
  6848. else:
  6849. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6850. min=-360, max=360, decimals=4,
  6851. init_val=float(self.defaults['tools_transform_skew_x']))
  6852. num, ok = skewxbox.get_value()
  6853. if ok:
  6854. # first get a bounding box to fit all
  6855. for obj in obj_list:
  6856. xmin, ymin, xmax, ymax = obj.bounds()
  6857. xminlist.append(xmin)
  6858. yminlist.append(ymin)
  6859. # get the minimum x,y and maximum x,y for all objects selected
  6860. xminimal = min(xminlist)
  6861. yminimal = min(yminlist)
  6862. for obj in obj_list:
  6863. obj.skew(num, 0, point=(xminimal, yminimal))
  6864. obj.plot()
  6865. self.object_changed.emit(obj)
  6866. self.inform.emit('[success] %s' %
  6867. _("Skew on X axis done."))
  6868. def on_skewy(self):
  6869. self.report_usage("on_skewy()")
  6870. obj_list = self.collection.get_selected()
  6871. xminlist = []
  6872. yminlist = []
  6873. if not obj_list:
  6874. self.inform.emit('[WARNING_NOTCL] %s' %
  6875. _("No object selected to Skew/Shear on Y axis."))
  6876. else:
  6877. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  6878. min=-360, max=360, decimals=4,
  6879. init_val=float(self.defaults['tools_transform_skew_y']))
  6880. num, ok = skewybox.get_value()
  6881. if ok:
  6882. # first get a bounding box to fit all
  6883. for obj in obj_list:
  6884. xmin, ymin, xmax, ymax = obj.bounds()
  6885. xminlist.append(xmin)
  6886. yminlist.append(ymin)
  6887. # get the minimum x,y and maximum x,y for all objects selected
  6888. xminimal = min(xminlist)
  6889. yminimal = min(yminlist)
  6890. for obj in obj_list:
  6891. obj.skew(0, num, point=(xminimal, yminimal))
  6892. obj.plot()
  6893. self.object_changed.emit(obj)
  6894. self.inform.emit('[success] %s' %
  6895. _("Skew on Y axis done."))
  6896. def on_plots_updated(self):
  6897. """
  6898. Callback used to report when the plots have changed.
  6899. Adjust axes and zooms to fit.
  6900. :return: None
  6901. """
  6902. if self.is_legacy is False:
  6903. self.plotcanvas.update() # TODO: Need update canvas?
  6904. else:
  6905. self.plotcanvas.auto_adjust_axes()
  6906. self.on_zoom_fit(None)
  6907. self.collection.update_view()
  6908. # self.inform.emit(_("Plots updated ..."))
  6909. # TODO: Rework toolbar 'clear', 'replot' functions
  6910. def on_toolbar_replot(self):
  6911. """
  6912. Callback for toolbar button. Re-plots all objects.
  6913. :return: None
  6914. """
  6915. self.report_usage("on_toolbar_replot")
  6916. self.log.debug("on_toolbar_replot()")
  6917. try:
  6918. self.collection.get_active().read_form()
  6919. except AttributeError:
  6920. self.log.debug("on_toolbar_replot(): AttributeError")
  6921. pass
  6922. self.plot_all()
  6923. def on_row_activated(self, index):
  6924. if index.isValid():
  6925. if index.internalPointer().parent_item != self.collection.root_item:
  6926. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  6927. self.collection.on_item_activated(index)
  6928. def on_row_selected(self, obj_name):
  6929. # this is a special string; when received it will make all entries unchecked
  6930. # it mean we clicked outside of the items and deselected all
  6931. if obj_name == 'none':
  6932. for act in self.ui.menuobjects.actions():
  6933. act.setChecked(False)
  6934. return
  6935. # get the name of the selected objects and add them to a list
  6936. name_list = list()
  6937. for obj in self.collection.get_selected():
  6938. name_list.append(obj.options['name'])
  6939. # set all actions as unchecked but the ones selected make them checked
  6940. for act in self.ui.menuobjects.actions():
  6941. act.setChecked(False)
  6942. if act.text() in name_list:
  6943. act.setChecked(True)
  6944. def on_collection_updated(self, obj, state, old_name):
  6945. """
  6946. Create a menu from the object loaded in the collection.
  6947. TODO: should use the collection model to do this
  6948. :param obj: object that was changd (added, deleted, renamed)
  6949. :param state: what was done with the objectCand be: added, deleted, delete_all, renamed
  6950. :param old_name: the old name of the object before the action that triggered this slot happened
  6951. :return: None
  6952. """
  6953. icon_files = {
  6954. "gerber": self.resource_location + "/flatcam_icon16.png",
  6955. "excellon": self.resource_location + "/drill16.png",
  6956. "cncjob": self.resource_location + "/cnc16.png",
  6957. "geometry": self.resource_location + "/geometry16.png",
  6958. "script": self.resource_location + "/script_new16.png",
  6959. "document": self.resource_location + "/notes16_1.png"
  6960. }
  6961. if state == 'append':
  6962. for act in self.ui.menuobjects.actions():
  6963. try:
  6964. act.triggered.disconnect()
  6965. except TypeError:
  6966. pass
  6967. self.ui.menuobjects.clear()
  6968. gerber_list = list()
  6969. exc_list = list()
  6970. cncjob_list = list()
  6971. geo_list = list()
  6972. script_list = list()
  6973. doc_list = list()
  6974. for name in self.collection.get_names():
  6975. obj_named = self.collection.get_by_name(name)
  6976. if obj_named.kind == 'gerber':
  6977. gerber_list.append(name)
  6978. elif obj_named.kind == 'excellon':
  6979. exc_list.append(name)
  6980. elif obj_named.kind == 'cncjob':
  6981. cncjob_list.append(name)
  6982. elif obj_named.kind == 'geometry':
  6983. geo_list.append(name)
  6984. elif obj_named.kind == 'script':
  6985. script_list.append(name)
  6986. elif obj_named.kind == 'document':
  6987. doc_list.append(name)
  6988. def add_act(o_name):
  6989. obj_for_icon = self.collection.get_by_name(o_name)
  6990. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  6991. add_action.setCheckable(True)
  6992. add_action.setText(o_name)
  6993. add_action.setIcon(QtGui.QIcon(icon_files[obj_for_icon.kind]))
  6994. add_action.triggered.connect(
  6995. lambda: self.collection.set_active(o_name) if add_action.isChecked() is True else
  6996. self.collection.set_inactive(o_name))
  6997. self.ui.menuobjects.addAction(add_action)
  6998. for name in gerber_list:
  6999. add_act(name)
  7000. self.ui.menuobjects.addSeparator()
  7001. for name in exc_list:
  7002. add_act(name)
  7003. self.ui.menuobjects.addSeparator()
  7004. for name in cncjob_list:
  7005. add_act(name)
  7006. self.ui.menuobjects.addSeparator()
  7007. for name in geo_list:
  7008. add_act(name)
  7009. self.ui.menuobjects.addSeparator()
  7010. for name in script_list:
  7011. add_act(name)
  7012. self.ui.menuobjects.addSeparator()
  7013. for name in doc_list:
  7014. add_act(name)
  7015. self.ui.menuobjects.addSeparator()
  7016. self.ui.menuobjects_selall = self.ui.menuobjects.addAction(
  7017. QtGui.QIcon(self.resource_location + '/select_all.png'),
  7018. _('Select All')
  7019. )
  7020. self.ui.menuobjects_unselall = self.ui.menuobjects.addAction(
  7021. QtGui.QIcon(self.resource_location + '/deselect_all32.png'),
  7022. _('Deselect All')
  7023. )
  7024. self.ui.menuobjects_selall.triggered.connect(lambda: self.on_objects_selection(True))
  7025. self.ui.menuobjects_unselall.triggered.connect(lambda: self.on_objects_selection(False))
  7026. elif state == 'delete':
  7027. for act in self.ui.menuobjects.actions():
  7028. if act.text() == obj.options['name']:
  7029. try:
  7030. act.triggered.disconnect()
  7031. except TypeError:
  7032. pass
  7033. self.ui.menuobjects.removeAction(act)
  7034. break
  7035. elif state == 'rename':
  7036. for act in self.ui.menuobjects.actions():
  7037. if act.text() == old_name:
  7038. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  7039. add_action.setText(obj.options['name'])
  7040. add_action.setIcon(QtGui.QIcon(icon_files[obj.kind]))
  7041. add_action.triggered.connect(
  7042. lambda: self.collection.set_active(obj.options['name']) if add_action.isChecked() is True else
  7043. self.collection.set_inactive(obj.options['name']))
  7044. self.ui.menuobjects.insertAction(act, add_action)
  7045. try:
  7046. act.triggered.disconnect()
  7047. except TypeError:
  7048. pass
  7049. self.ui.menuobjects.removeAction(act)
  7050. break
  7051. elif state == 'delete_all':
  7052. for act in self.ui.menuobjects.actions():
  7053. try:
  7054. act.triggered.disconnect()
  7055. except TypeError:
  7056. pass
  7057. self.ui.menuobjects.clear()
  7058. self.ui.menuobjects.addSeparator()
  7059. self.ui.menuobjects_selall = self.ui.menuobjects.addAction(
  7060. QtGui.QIcon(self.resource_location + '/select_all.png'),
  7061. _('Select All')
  7062. )
  7063. self.ui.menuobjects_unselall = self.ui.menuobjects.addAction(
  7064. QtGui.QIcon(self.resource_location + '/deselect_all32.png'),
  7065. _('Deselect All')
  7066. )
  7067. self.ui.menuobjects_selall.triggered.connect(lambda: self.on_objects_selection(True))
  7068. self.ui.menuobjects_unselall.triggered.connect(lambda: self.on_objects_selection(False))
  7069. def on_objects_selection(self, on_off):
  7070. obj_list = self.collection.get_names()
  7071. if on_off is True:
  7072. self.collection.set_all_active()
  7073. for act in self.ui.menuobjects.actions():
  7074. try:
  7075. act.setChecked(True)
  7076. except Exception:
  7077. pass
  7078. if obj_list:
  7079. self.inform.emit('[selected] %s' % _("All objects are selected."))
  7080. else:
  7081. self.collection.set_all_inactive()
  7082. for act in self.ui.menuobjects.actions():
  7083. try:
  7084. act.setChecked(False)
  7085. except Exception:
  7086. pass
  7087. if obj_list:
  7088. self.inform.emit('%s' % _("Objects selection is cleared."))
  7089. else:
  7090. self.inform.emit('')
  7091. def grid_status(self):
  7092. if self.ui.grid_snap_btn.isChecked():
  7093. return True
  7094. else:
  7095. return False
  7096. def populate_cmenu_grids(self):
  7097. units = self.defaults['units'].lower()
  7098. for act in self.ui.cmenu_gridmenu.actions():
  7099. act.triggered.disconnect()
  7100. self.ui.cmenu_gridmenu.clear()
  7101. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  7102. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  7103. _("Grid On/Off"))
  7104. grid_toggle.setCheckable(True)
  7105. grid_toggle.setChecked(True) if self.grid_status() else grid_toggle.setChecked(False)
  7106. self.ui.cmenu_gridmenu.addSeparator()
  7107. for grid in sorted_list:
  7108. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  7109. "%s" % str(grid))
  7110. action.triggered.connect(self.set_grid)
  7111. self.ui.cmenu_gridmenu.addSeparator()
  7112. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/plus32.png'),
  7113. _("Add"))
  7114. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/delete32.png'),
  7115. _("Delete"))
  7116. grid_add.triggered.connect(self.on_grid_add)
  7117. grid_delete.triggered.connect(self.on_grid_delete)
  7118. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  7119. def set_grid(self):
  7120. self.ui.grid_gap_x_entry.setText(self.sender().text())
  7121. self.ui.grid_gap_y_entry.setText(self.sender().text())
  7122. def on_grid_add(self):
  7123. # ## Current application units in lower Case
  7124. units = self.defaults['units'].lower()
  7125. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  7126. text=_('Enter a Grid Value:'),
  7127. min=0.0000, max=99.9999, decimals=4)
  7128. grid_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/plus32.png'))
  7129. val, ok = grid_add_popup.get_value()
  7130. if ok:
  7131. if float(val) == 0:
  7132. self.inform.emit('[WARNING_NOTCL] %s' %
  7133. _("Please enter a grid value with non-zero value, in Float format."))
  7134. return
  7135. else:
  7136. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  7137. self.defaults["global_grid_context_menu"][str(units)].append(val)
  7138. self.inform.emit('[success] %s...' %
  7139. _("New Grid added"))
  7140. else:
  7141. self.inform.emit('[WARNING_NOTCL] %s...' %
  7142. _("Grid already exists"))
  7143. else:
  7144. self.inform.emit('[WARNING_NOTCL] %s...' %
  7145. _("Adding New Grid cancelled"))
  7146. def on_grid_delete(self):
  7147. # ## Current application units in lower Case
  7148. units = self.defaults['units'].lower()
  7149. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  7150. text='Enter a Grid Value:',
  7151. min=0.0000, max=99.9999, decimals=4)
  7152. grid_del_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/delete32.png'))
  7153. val, ok = grid_del_popup.get_value()
  7154. if ok:
  7155. if float(val) == 0:
  7156. self.inform.emit('[WARNING_NOTCL] %s' %
  7157. _("Please enter a grid value with non-zero value, in Float format."))
  7158. return
  7159. else:
  7160. try:
  7161. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  7162. except ValueError:
  7163. self.inform.emit('[ERROR_NOTCL]%s...' %
  7164. _(" Grid Value does not exist"))
  7165. return
  7166. self.inform.emit('[success] %s...' %
  7167. _("Grid Value deleted"))
  7168. else:
  7169. self.inform.emit('[WARNING_NOTCL] %s...' %
  7170. _("Delete Grid value cancelled"))
  7171. def on_shortcut_list(self):
  7172. self.report_usage("on_shortcut_list()")
  7173. # add the tab if it was closed
  7174. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  7175. # delete the absolute and relative position and messages in the infobar
  7176. self.ui.position_label.setText("")
  7177. self.ui.rel_position_label.setText("")
  7178. # Switch plot_area to preferences page
  7179. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  7180. # self.ui.show()
  7181. def on_select_tab(self, name):
  7182. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  7183. if self.ui.splitter.sizes()[0] == 0:
  7184. self.ui.splitter.setSizes([1, 1])
  7185. else:
  7186. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  7187. self.ui.splitter.setSizes([0, 1])
  7188. if name == 'project':
  7189. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  7190. elif name == 'selected':
  7191. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  7192. elif name == 'tool':
  7193. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  7194. def on_copy_name(self):
  7195. self.report_usage("on_copy_name()")
  7196. obj = self.collection.get_active()
  7197. try:
  7198. name = obj.options["name"]
  7199. except AttributeError:
  7200. log.debug("on_copy_name() --> No object selected to copy it's name")
  7201. self.inform.emit('[WARNING_NOTCL]%s' %
  7202. _(" No object selected to copy it's name"))
  7203. return
  7204. self.clipboard.setText(name)
  7205. self.inform.emit(_("Name copied on clipboard ..."))
  7206. def on_mouse_click_over_plot(self, event):
  7207. """
  7208. Default actions are:
  7209. :param event: Contains information about the event, like which button
  7210. was clicked, the pixel coordinates and the axes coordinates.
  7211. :return: None
  7212. """
  7213. self.pos = list()
  7214. if self.is_legacy is False:
  7215. event_pos = event.pos
  7216. pan_button = 2 if self.defaults["global_pan_button"] == '2'else 3
  7217. # Set the mouse button for panning
  7218. self.plotcanvas.view.camera.pan_button_setting = pan_button
  7219. else:
  7220. event_pos = (event.xdata, event.ydata)
  7221. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  7222. pan_button = 3 if self.defaults["global_pan_button"] == '2'else 2
  7223. # So it can receive key presses
  7224. self.plotcanvas.native.setFocus()
  7225. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  7226. if self.grid_status() == True:
  7227. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  7228. else:
  7229. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  7230. try:
  7231. if event.button == 1:
  7232. # Reset here the relative coordinates so there is a new reference on the click position
  7233. if self.rel_point1 is None:
  7234. self.rel_point1 = self.pos
  7235. else:
  7236. self.rel_point2 = copy(self.rel_point1)
  7237. self.rel_point1 = self.pos
  7238. self.on_mouse_move_over_plot(event, origin_click=True)
  7239. except Exception as e:
  7240. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  7241. def on_mouse_double_click_over_plot(self, event):
  7242. if event.button == 1:
  7243. self.doubleclick = True
  7244. def on_mouse_move_over_plot(self, event, origin_click=None):
  7245. """
  7246. Callback for the mouse motion event over the plot.
  7247. :param event: Contains information about the event.
  7248. :param origin_click
  7249. :return: None
  7250. """
  7251. if self.is_legacy is False:
  7252. event_pos = event.pos
  7253. if self.defaults["global_pan_button"] == '2':
  7254. pan_button = 2
  7255. else:
  7256. pan_button = 3
  7257. self.event_is_dragging = event.is_dragging
  7258. else:
  7259. event_pos = (event.xdata, event.ydata)
  7260. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  7261. if self.defaults["global_pan_button"] == '2':
  7262. pan_button = 3
  7263. else:
  7264. pan_button = 2
  7265. self.event_is_dragging = self.plotcanvas.is_dragging
  7266. # So it can receive key presses
  7267. self.plotcanvas.native.setFocus()
  7268. self.pos_jump = event_pos
  7269. self.ui.popMenu.mouse_is_panning = False
  7270. if not origin_click:
  7271. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  7272. if event.button == pan_button and self.event_is_dragging == 1:
  7273. self.ui.popMenu.mouse_is_panning = True
  7274. return
  7275. if self.rel_point1 is not None:
  7276. try: # May fail in case mouse not within axes
  7277. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  7278. if self.grid_status() == True:
  7279. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  7280. # Update cursor
  7281. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  7282. symbol='++', edge_color=self.cursor_color_3D,
  7283. edge_width=self.defaults["global_cursor_width"],
  7284. size=self.defaults["global_cursor_size"])
  7285. else:
  7286. pos = (pos_canvas[0], pos_canvas[1])
  7287. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  7288. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  7289. dx = pos[0] - float(self.rel_point1[0])
  7290. dy = pos[1] - float(self.rel_point1[1])
  7291. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  7292. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  7293. self.mouse = [pos[0], pos[1]]
  7294. # if the mouse is moved and the LMB is clicked then the action is a selection
  7295. if self.event_is_dragging == 1 and event.button == 1:
  7296. self.delete_selection_shape()
  7297. if dx < 0:
  7298. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  7299. face_color=self.defaults['global_alt_sel_fill'])
  7300. self.selection_type = False
  7301. elif dx >= 0:
  7302. self.draw_moving_selection_shape(self.pos, pos)
  7303. self.selection_type = True
  7304. else:
  7305. self.selection_type = None
  7306. # hover effect - enabled in Preferences -> General -> GUI Settings
  7307. if self.defaults['global_hover']:
  7308. for obj in self.collection.get_list():
  7309. try:
  7310. # select the object(s) only if it is enabled (plotted)
  7311. if obj.options['plot']:
  7312. if obj not in self.collection.get_selected():
  7313. poly_obj = Polygon(
  7314. [(obj.options['xmin'], obj.options['ymin']),
  7315. (obj.options['xmax'], obj.options['ymin']),
  7316. (obj.options['xmax'], obj.options['ymax']),
  7317. (obj.options['xmin'], obj.options['ymax'])]
  7318. )
  7319. if Point(pos).within(poly_obj):
  7320. if obj.isHovering is False:
  7321. obj.isHovering = True
  7322. obj.notHovering = True
  7323. # create the selection box around the selected object
  7324. self.draw_hover_shape(obj, color='#d1e0e0FF')
  7325. else:
  7326. if obj.notHovering is True:
  7327. obj.notHovering = False
  7328. obj.isHovering = False
  7329. self.delete_hover_shape()
  7330. except Exception:
  7331. # the Exception here will happen if we try to select on screen and we have an
  7332. # newly (and empty) just created Geometry or Excellon object that do not have the
  7333. # xmin, xmax, ymin, ymax options.
  7334. # In this case poly_obj creation (see above) will fail
  7335. pass
  7336. except Exception:
  7337. self.ui.position_label.setText("")
  7338. self.ui.rel_position_label.setText("")
  7339. self.mouse = None
  7340. def on_mouse_click_release_over_plot(self, event):
  7341. """
  7342. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  7343. and has been registered in ''self.__init__()''.
  7344. :param event: contains information about the event.
  7345. :return:
  7346. """
  7347. if self.is_legacy is False:
  7348. event_pos = event.pos
  7349. right_button = 2
  7350. else:
  7351. event_pos = (event.xdata, event.ydata)
  7352. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  7353. right_button = 3
  7354. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  7355. if self.grid_status() == True:
  7356. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  7357. else:
  7358. pos = (pos_canvas[0], pos_canvas[1])
  7359. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  7360. # canvas menu
  7361. if event.button == right_button and self.ui.popMenu.mouse_is_panning is False: # right click
  7362. self.cursor = QtGui.QCursor()
  7363. self.populate_cmenu_grids()
  7364. self.ui.popMenu.popup(self.cursor.pos())
  7365. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  7366. # selection and then select a type of selection ("enclosing" or "touching")
  7367. if event.button == 1: # left click
  7368. modifiers = QtWidgets.QApplication.keyboardModifiers()
  7369. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  7370. if modifiers == QtCore.Qt.ShiftModifier:
  7371. # do not auto open the Project Tab
  7372. self.click_noproject = True
  7373. self.clipboard.setText(
  7374. self.defaults["global_point_clipboard_format"] %
  7375. (self.decimals, self.pos[0], self.decimals, self.pos[1])
  7376. )
  7377. self.inform.emit('[success] %s' % _("Coordinates copied to clipboard."))
  7378. return
  7379. if self.doubleclick is True:
  7380. self.doubleclick = False
  7381. if self.collection.get_selected():
  7382. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  7383. if self.ui.splitter.sizes()[0] == 0:
  7384. self.ui.splitter.setSizes([1, 1])
  7385. try:
  7386. # delete the selection shape(S) as it may be in the way
  7387. self.delete_selection_shape()
  7388. self.delete_hover_shape()
  7389. except Exception as e:
  7390. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() double click --> Error: %s" % str(e))
  7391. return
  7392. else:
  7393. if self.selection_type is not None:
  7394. try:
  7395. self.selection_area_handler(self.pos, pos, self.selection_type)
  7396. self.selection_type = None
  7397. except Exception as e:
  7398. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select area --> Error: %s" % str(e))
  7399. return
  7400. else:
  7401. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  7402. if key_modifier == QtCore.Qt.ShiftModifier:
  7403. mod_key = 'Shift'
  7404. elif key_modifier == QtCore.Qt.ControlModifier:
  7405. mod_key = 'Control'
  7406. else:
  7407. mod_key = None
  7408. try:
  7409. if mod_key == self.defaults["global_mselect_key"]:
  7410. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  7411. # deselect, and if it's not selected then it will be selected
  7412. # If there is no active command (self.command_active is None) then we check if we clicked
  7413. # on a object by checking the bounding limits against mouse click position
  7414. if self.command_active is None:
  7415. self.select_objects(key='CTRL')
  7416. self.delete_hover_shape()
  7417. else:
  7418. # If there is no active command (self.command_active is None) then we check if we clicked
  7419. # on a object by checking the bounding limits against mouse click position
  7420. if self.command_active is None:
  7421. self.select_objects()
  7422. self.delete_hover_shape()
  7423. except Exception as e:
  7424. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select click --> Error: %s" % str(e))
  7425. return
  7426. def selection_area_handler(self, start_pos, end_pos, sel_type):
  7427. """
  7428. :param start_pos: mouse position when the selection LMB click was done
  7429. :param end_pos: mouse position when the left mouse button is released
  7430. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  7431. :return:
  7432. """
  7433. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  7434. # delete previous selection shape
  7435. self.delete_selection_shape()
  7436. # make all objects inactive
  7437. self.collection.set_all_inactive()
  7438. for obj in self.collection.get_list():
  7439. try:
  7440. # select the object(s) only if it is enabled (plotted)
  7441. if obj.options['plot']:
  7442. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  7443. (obj.options['xmax'], obj.options['ymin']),
  7444. (obj.options['xmax'], obj.options['ymax']),
  7445. (obj.options['xmin'], obj.options['ymax'])])
  7446. if sel_type is True:
  7447. if poly_obj.within(poly_selection):
  7448. # create the selection box around the selected object
  7449. if self.defaults['global_selection_shape'] is True:
  7450. self.draw_selection_shape(obj)
  7451. self.collection.set_active(obj.options['name'])
  7452. else:
  7453. if poly_selection.intersects(poly_obj):
  7454. # create the selection box around the selected object
  7455. if self.defaults['global_selection_shape'] is True:
  7456. self.draw_selection_shape(obj)
  7457. self.collection.set_active(obj.options['name'])
  7458. obj.selection_shape_drawn = True
  7459. except Exception as e:
  7460. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  7461. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  7462. # In this case poly_obj creation (see above) will fail
  7463. log.debug("App.selection_area_handler() --> %s" % str(e))
  7464. def select_objects(self, key=None):
  7465. """
  7466. Will select objects clicked on canvas
  7467. :param key: for future use in cumulative selection
  7468. :return:
  7469. """
  7470. # list where we store the overlapped objects under our mouse left click position
  7471. objects_under_the_click_list = []
  7472. # Populate the list with the overlapped objects on the click position
  7473. curr_x, curr_y = self.pos
  7474. for obj in self.all_objects_list:
  7475. # FlatCAMScript and FlatCAMDocument objects can't be selected
  7476. if isinstance(obj, FlatCAMScript) or isinstance(obj, FlatCAMDocument):
  7477. continue
  7478. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  7479. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  7480. if obj.options['name'] not in objects_under_the_click_list:
  7481. if obj.options['plot']:
  7482. # add objects to the objects_under_the_click list only if the object is plotted
  7483. # (active and not disabled)
  7484. objects_under_the_click_list.append(obj.options['name'])
  7485. try:
  7486. if objects_under_the_click_list:
  7487. curr_sel_obj = self.collection.get_active()
  7488. # case when there is only an object under the click and we toggle it
  7489. if len(objects_under_the_click_list) == 1:
  7490. if curr_sel_obj is None:
  7491. self.collection.set_active(objects_under_the_click_list[0])
  7492. curr_sel_obj = self.collection.get_active()
  7493. # create the selection box around the selected object
  7494. if self.defaults['global_selection_shape'] is True:
  7495. self.draw_selection_shape(curr_sel_obj)
  7496. curr_sel_obj.selection_shape_drawn = True
  7497. elif curr_sel_obj.options['name'] not in objects_under_the_click_list:
  7498. self.on_objects_selection(False)
  7499. self.delete_selection_shape()
  7500. curr_sel_obj.selection_shape_drawn = False
  7501. self.collection.set_active(objects_under_the_click_list[0])
  7502. curr_sel_obj = self.collection.get_active()
  7503. # create the selection box around the selected object
  7504. if self.defaults['global_selection_shape'] is True:
  7505. self.draw_selection_shape(curr_sel_obj)
  7506. curr_sel_obj.selection_shape_drawn = True
  7507. self.selected_message(curr_sel_obj=curr_sel_obj)
  7508. elif curr_sel_obj.selection_shape_drawn is False:
  7509. if self.defaults['global_selection_shape'] is True:
  7510. self.draw_selection_shape(curr_sel_obj)
  7511. curr_sel_obj.selection_shape_drawn = True
  7512. else:
  7513. self.on_objects_selection(False)
  7514. self.delete_selection_shape()
  7515. if self.call_source != 'app':
  7516. self.call_source = 'app'
  7517. self.selected_message(curr_sel_obj=curr_sel_obj)
  7518. else:
  7519. # If there is no selected object
  7520. # make active the first element of the overlapped objects list
  7521. if self.collection.get_active() is None:
  7522. self.collection.set_active(objects_under_the_click_list[0])
  7523. self.collection.get_by_name(objects_under_the_click_list[0]).selection_shape_drawn = True
  7524. name_sel_obj = self.collection.get_active().options['name']
  7525. # In case that there is a selected object but it is not in the overlapped object list
  7526. # make that object inactive and activate the first element in the overlapped object list
  7527. if name_sel_obj not in objects_under_the_click_list:
  7528. self.collection.set_inactive(name_sel_obj)
  7529. name_sel_obj = objects_under_the_click_list[0]
  7530. self.collection.set_active(name_sel_obj)
  7531. else:
  7532. sel_idx = objects_under_the_click_list.index(name_sel_obj)
  7533. self.collection.set_all_inactive()
  7534. self.collection.set_active(objects_under_the_click_list[(sel_idx + 1) %
  7535. len(objects_under_the_click_list)])
  7536. curr_sel_obj = self.collection.get_active()
  7537. # delete the possible selection box around a possible selected object
  7538. self.delete_selection_shape()
  7539. curr_sel_obj.selection_shape_drawn = False
  7540. # create the selection box around the selected object
  7541. if self.defaults['global_selection_shape'] is True:
  7542. self.draw_selection_shape(curr_sel_obj)
  7543. curr_sel_obj.selection_shape_drawn = True
  7544. self.selected_message(curr_sel_obj=curr_sel_obj)
  7545. else:
  7546. # deselect everything
  7547. self.on_objects_selection(False)
  7548. # delete the possible selection box around a possible selected object
  7549. self.delete_selection_shape()
  7550. for o in self.collection.get_list():
  7551. o.selection_shape_drawn = False
  7552. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  7553. # only when working on App
  7554. if self.call_source == 'app':
  7555. if self.click_noproject is False:
  7556. # if the Tool Tab is in focus don't change focus to Project Tab
  7557. if not self.ui.notebook.currentWidget() is self.ui.tool_tab:
  7558. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  7559. else:
  7560. # restore auto open the Project Tab
  7561. self.click_noproject = False
  7562. # delete any text in the status bar, implicitly the last object name that was selected
  7563. # self.inform.emit("")
  7564. else:
  7565. self.call_source = 'app'
  7566. except Exception as e:
  7567. log.error("[ERROR] Something went bad in App.select_objects(). %s" % str(e))
  7568. def selected_message(self, curr_sel_obj):
  7569. if curr_sel_obj:
  7570. if curr_sel_obj.kind == 'gerber':
  7571. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  7572. color='green',
  7573. name=str(curr_sel_obj.options['name']),
  7574. tx=_("selected"))
  7575. )
  7576. elif curr_sel_obj.kind == 'excellon':
  7577. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  7578. color='brown',
  7579. name=str(curr_sel_obj.options['name']),
  7580. tx=_("selected"))
  7581. )
  7582. elif curr_sel_obj.kind == 'cncjob':
  7583. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  7584. color='blue',
  7585. name=str(curr_sel_obj.options['name']),
  7586. tx=_("selected"))
  7587. )
  7588. elif curr_sel_obj.kind == 'geometry':
  7589. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  7590. color='red',
  7591. name=str(curr_sel_obj.options['name']),
  7592. tx=_("selected"))
  7593. )
  7594. def delete_hover_shape(self):
  7595. self.hover_shapes.clear()
  7596. self.hover_shapes.redraw()
  7597. def draw_hover_shape(self, sel_obj, color=None):
  7598. """
  7599. :param sel_obj: the object for which the hover shape must be drawn
  7600. :return:
  7601. """
  7602. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  7603. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  7604. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  7605. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  7606. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  7607. if self.defaults['units'].upper() == 'MM':
  7608. hover_rect = hover_rect.buffer(-0.1)
  7609. hover_rect = hover_rect.buffer(0.2)
  7610. else:
  7611. hover_rect = hover_rect.buffer(-0.00393)
  7612. hover_rect = hover_rect.buffer(0.00787)
  7613. # if color:
  7614. # face = Color(color)
  7615. # face.alpha = 0.2
  7616. # outline = Color(color, alpha=0.8)
  7617. # else:
  7618. # face = Color(self.defaults['global_sel_fill'])
  7619. # face.alpha = 0.2
  7620. # outline = self.defaults['global_sel_line']
  7621. if color:
  7622. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  7623. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  7624. else:
  7625. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  7626. outline = self.defaults['global_sel_line']
  7627. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  7628. if self.is_legacy is True:
  7629. self.hover_shapes.redraw()
  7630. def delete_selection_shape(self):
  7631. self.move_tool.sel_shapes.clear()
  7632. self.move_tool.sel_shapes.redraw()
  7633. def draw_selection_shape(self, sel_obj, color=None):
  7634. """
  7635. :param sel_obj: the object for which the selection shape must be drawn
  7636. :return:
  7637. """
  7638. if sel_obj is None:
  7639. return
  7640. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  7641. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  7642. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  7643. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  7644. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  7645. if self.defaults['units'].upper() == 'MM':
  7646. sel_rect = sel_rect.buffer(-0.1)
  7647. sel_rect = sel_rect.buffer(0.2)
  7648. else:
  7649. sel_rect = sel_rect.buffer(-0.00393)
  7650. sel_rect = sel_rect.buffer(0.00787)
  7651. if color:
  7652. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  7653. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  7654. else:
  7655. if self.is_legacy is False:
  7656. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  7657. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  7658. else:
  7659. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  7660. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  7661. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  7662. color=outline,
  7663. face_color=face,
  7664. update=True,
  7665. layer=0,
  7666. tolerance=None))
  7667. if self.is_legacy is True:
  7668. self.move_tool.sel_shapes.redraw()
  7669. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  7670. """
  7671. :param old_coords: old coordinates
  7672. :param coords: new coordinates
  7673. :return:
  7674. """
  7675. if 'color' in kwargs:
  7676. color = kwargs['color']
  7677. else:
  7678. color = self.defaults['global_sel_line']
  7679. if 'face_color' in kwargs:
  7680. face_color = kwargs['face_color']
  7681. else:
  7682. face_color = self.defaults['global_sel_fill']
  7683. if 'face_alpha' in kwargs:
  7684. face_alpha = kwargs['face_alpha']
  7685. else:
  7686. face_alpha = 0.3
  7687. x0, y0 = old_coords
  7688. x1, y1 = coords
  7689. pt1 = (x0, y0)
  7690. pt2 = (x1, y0)
  7691. pt3 = (x1, y1)
  7692. pt4 = (x0, y1)
  7693. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  7694. # color_t = Color(face_color)
  7695. # color_t.alpha = face_alpha
  7696. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  7697. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  7698. layer=0, tolerance=None)
  7699. if self.is_legacy is True:
  7700. self.move_tool.sel_shapes.redraw()
  7701. def on_file_new_click(self):
  7702. if self.collection.get_list() and self.should_we_save:
  7703. msgbox = QtWidgets.QMessageBox()
  7704. # msgbox.setText("<B>Save changes ...</B>")
  7705. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  7706. "Creating a New project will delete them.\n"
  7707. "Do you want to Save the project?"))
  7708. msgbox.setWindowTitle(_("Save changes"))
  7709. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  7710. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  7711. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  7712. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  7713. msgbox.setDefaultButton(bt_yes)
  7714. msgbox.exec_()
  7715. response = msgbox.clickedButton()
  7716. if response == bt_yes:
  7717. self.on_file_saveprojectas()
  7718. elif response == bt_cancel:
  7719. return
  7720. elif response == bt_no:
  7721. self.on_file_new()
  7722. else:
  7723. self.on_file_new()
  7724. self.inform.emit('[success] %s...' %
  7725. _("New Project created"))
  7726. def on_file_new(self, cli=None):
  7727. """
  7728. Callback for menu item File -> New. Returns the application to its
  7729. startup state. This method is thread-safe.
  7730. :return: None
  7731. """
  7732. self.report_usage("on_file_new")
  7733. # Remove everything from memory
  7734. App.log.debug("on_file_new()")
  7735. if self.call_source != 'app':
  7736. self.editor2object(cleanup=True)
  7737. # ## EDITOR section
  7738. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  7739. self.exc_editor = FlatCAMExcEditor(self)
  7740. self.grb_editor = FlatCAMGrbEditor(self)
  7741. # Clear pool
  7742. self.clear_pool()
  7743. for obj in self.collection.get_list():
  7744. # delete shapes left drawn from mark shape_collections, if any
  7745. if isinstance(obj, FlatCAMGerber):
  7746. try:
  7747. obj.mark_shapes.enabled = False
  7748. obj.mark_shapes.clear(update=True)
  7749. except AttributeError:
  7750. pass
  7751. # also delete annotation shapes, if any
  7752. elif isinstance(obj, FlatCAMCNCjob):
  7753. try:
  7754. obj.annotation.enabled = False
  7755. obj.annotation.clear(update=True)
  7756. except AttributeError:
  7757. pass
  7758. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  7759. self.init_tcl()
  7760. self.delete_selection_shape()
  7761. self.collection.delete_all()
  7762. self.setup_component_editor()
  7763. # Clear project filename
  7764. self.project_filename = None
  7765. # Load the application defaults
  7766. self.load_defaults(filename='current_defaults')
  7767. # Re-fresh project options
  7768. self.on_options_app2project()
  7769. # Init Tools
  7770. self.init_tools()
  7771. if cli is None:
  7772. # Close any Tabs opened in the Plot Tab Area section
  7773. for index in range(self.ui.plot_tab_area.count()):
  7774. self.ui.plot_tab_area.closeTab(index)
  7775. # for whatever reason previous command does not close the last tab so I do it manually
  7776. self.ui.plot_tab_area.closeTab(0)
  7777. # # And then add again the Plot Area
  7778. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  7779. self.ui.plot_tab_area.protectTab(0)
  7780. # take the focus of the Notebook on Project Tab.
  7781. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  7782. self.set_ui_title(name=_("New Project - Not saved"))
  7783. def obj_properties(self):
  7784. """
  7785. Will launch the object Properties Tool
  7786. :return:
  7787. """
  7788. self.report_usage("obj_properties()")
  7789. self.properties_tool.run(toggle=False)
  7790. def on_project_context_save(self):
  7791. """
  7792. Wrapper, will save the object function of it's type
  7793. :return:
  7794. """
  7795. obj = self.collection.get_active()
  7796. if type(obj) == FlatCAMGeometry:
  7797. self.on_file_exportdxf()
  7798. elif type(obj) == FlatCAMExcellon:
  7799. self.on_file_saveexcellon()
  7800. elif type(obj) == FlatCAMCNCjob:
  7801. obj.on_exportgcode_button_click()
  7802. elif type(obj) == FlatCAMGerber:
  7803. self.on_file_savegerber()
  7804. elif type(obj) == FlatCAMScript:
  7805. self.on_file_savescript()
  7806. elif type(obj) == FlatCAMDocument:
  7807. self.on_file_savedocument()
  7808. def obj_move(self):
  7809. self.report_usage("obj_move()")
  7810. self.move_tool.run(toggle=False)
  7811. def on_fileopengerber(self, signal: bool = None, name=None):
  7812. """
  7813. File menu callback for opening a Gerber.
  7814. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7815. :return: None
  7816. """
  7817. self.report_usage("on_fileopengerber")
  7818. App.log.debug("on_fileopengerber()")
  7819. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  7820. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  7821. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd *.gb*);;" \
  7822. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  7823. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  7824. "*.mil);;" \
  7825. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  7826. "Allegro Files (*.art);;" \
  7827. "Mentor Files (*.pho *.gdo);;" \
  7828. "All Files (*.*)"
  7829. if name is None:
  7830. try:
  7831. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  7832. directory=self.get_last_folder(),
  7833. filter=_filter_)
  7834. except TypeError:
  7835. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  7836. filenames = [str(filename) for filename in filenames]
  7837. else:
  7838. filenames = [name]
  7839. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7840. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7841. _("Opening Gerber file.")),
  7842. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7843. color=QtGui.QColor("gray"))
  7844. if len(filenames) == 0:
  7845. self.inform.emit('[WARNING_NOTCL] %s' %
  7846. _("Open Gerber cancelled."))
  7847. else:
  7848. for filename in filenames:
  7849. if filename != '':
  7850. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  7851. def on_fileopenexcellon(self, signal: bool = None, name=None):
  7852. """
  7853. File menu callback for opening an Excellon file.
  7854. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7855. :return: None
  7856. """
  7857. self.report_usage("on_fileopenexcellon")
  7858. App.log.debug("on_fileopenexcellon()")
  7859. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  7860. "All Files (*.*)"
  7861. if name is None:
  7862. try:
  7863. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  7864. directory=self.get_last_folder(),
  7865. filter=_filter_)
  7866. except TypeError:
  7867. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  7868. filenames = [str(filename) for filename in filenames]
  7869. else:
  7870. filenames = [str(name)]
  7871. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7872. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7873. _("Opening Excellon file.")),
  7874. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7875. color=QtGui.QColor("gray"))
  7876. if len(filenames) == 0:
  7877. self.inform.emit('[WARNING_NOTCL]%s' %
  7878. _(" Open Excellon cancelled."))
  7879. else:
  7880. for filename in filenames:
  7881. if filename != '':
  7882. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  7883. def on_fileopengcode(self, signal: bool = None, name=None):
  7884. """
  7885. File menu call back for opening gcode.
  7886. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7887. :return: None
  7888. """
  7889. self.report_usage("on_fileopengcode")
  7890. App.log.debug("on_fileopengcode()")
  7891. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  7892. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  7893. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.sbp *.mpf);;" \
  7894. "All Files (*.*)"
  7895. if name is None:
  7896. try:
  7897. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  7898. directory=self.get_last_folder(),
  7899. filter=_filter_)
  7900. except TypeError:
  7901. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  7902. filenames = [str(filename) for filename in filenames]
  7903. else:
  7904. filenames = [name]
  7905. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7906. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7907. _("Opening G-Code file.")),
  7908. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7909. color=QtGui.QColor("gray"))
  7910. if len(filenames) == 0:
  7911. self.inform.emit('[WARNING_NOTCL] %s' %
  7912. _("Open G-Code cancelled."))
  7913. else:
  7914. for filename in filenames:
  7915. if filename != '':
  7916. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename, None, True]})
  7917. def on_file_openproject(self, signal: bool = None):
  7918. """
  7919. File menu callback for opening a project.
  7920. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7921. :return: None
  7922. """
  7923. self.report_usage("on_file_openproject")
  7924. App.log.debug("on_file_openproject()")
  7925. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  7926. try:
  7927. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  7928. directory=self.get_last_folder(), filter=_filter_)
  7929. except TypeError:
  7930. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  7931. # The Qt methods above will return a QString which can cause problems later.
  7932. # So far json.dump() will fail to serialize it.
  7933. # TODO: Improve the serialization methods and remove this fix.
  7934. filename = str(filename)
  7935. if filename == "":
  7936. self.inform.emit('[WARNING_NOTCL] %s' %
  7937. _("Open Project cancelled."))
  7938. else:
  7939. # self.worker_task.emit({'fcn': self.open_project,
  7940. # 'params': [filename]})
  7941. # The above was failing because open_project() is not
  7942. # thread safe. The new_project()
  7943. self.open_project(filename)
  7944. def on_fileopenhpgl2(self, signal: bool = None, name=None):
  7945. """
  7946. File menu callback for opening a HPGL2.
  7947. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7948. :return: None
  7949. """
  7950. self.report_usage("on_fileopenhpgl2")
  7951. App.log.debug("on_fileopenhpgl2()")
  7952. _filter_ = "HPGL2 Files (*.plt);;" \
  7953. "All Files (*.*)"
  7954. if name is None:
  7955. try:
  7956. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"),
  7957. directory=self.get_last_folder(),
  7958. filter=_filter_)
  7959. except TypeError:
  7960. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"), filter=_filter_)
  7961. filenames = [str(filename) for filename in filenames]
  7962. else:
  7963. filenames = [name]
  7964. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7965. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7966. _("Opening HPGL2 file.")),
  7967. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7968. color=QtGui.QColor("gray"))
  7969. if len(filenames) == 0:
  7970. self.inform.emit('[WARNING_NOTCL] %s' % _("Open HPGL2 file cancelled."))
  7971. else:
  7972. for filename in filenames:
  7973. if filename != '':
  7974. self.worker_task.emit({'fcn': self.open_hpgl2, 'params': [filename]})
  7975. def on_file_openconfig(self, signal: bool = None):
  7976. """
  7977. File menu callback for opening a config file.
  7978. :param signal: required because clicking the entry will generate a checked signal which needs a container
  7979. :return: None
  7980. """
  7981. self.report_usage("on_file_openconfig")
  7982. App.log.debug("on_file_openconfig()")
  7983. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  7984. try:
  7985. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  7986. directory=self.data_path, filter=_filter_)
  7987. except TypeError:
  7988. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  7989. filter=_filter_)
  7990. if filename == "":
  7991. self.inform.emit('[WARNING_NOTCL] %s' %
  7992. _("Open Config cancelled."))
  7993. else:
  7994. self.open_config_file(filename)
  7995. def on_file_exportsvg(self):
  7996. """
  7997. Callback for menu item File->Export SVG.
  7998. :return: None
  7999. """
  8000. self.report_usage("on_file_exportsvg")
  8001. App.log.debug("on_file_exportsvg()")
  8002. obj = self.collection.get_active()
  8003. if obj is None:
  8004. self.inform.emit('[WARNING_NOTCL] %s' %
  8005. _("No object selected."))
  8006. msg = _("Please Select a Geometry object to export")
  8007. msgbox = QtWidgets.QMessageBox()
  8008. msgbox.setInformativeText(msg)
  8009. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  8010. msgbox.setDefaultButton(bt_ok)
  8011. msgbox.exec_()
  8012. return
  8013. # Check for more compatible types and add as required
  8014. if (not isinstance(obj, FlatCAMGeometry)
  8015. and not isinstance(obj, FlatCAMGerber)
  8016. and not isinstance(obj, FlatCAMCNCjob)
  8017. and not isinstance(obj, FlatCAMExcellon)):
  8018. msg = '[ERROR_NOTCL] %s' % \
  8019. _("Only Geometry, Gerber and CNCJob objects can be used.")
  8020. msgbox = QtWidgets.QMessageBox()
  8021. msgbox.setInformativeText(msg)
  8022. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  8023. msgbox.setDefaultButton(bt_ok)
  8024. msgbox.exec_()
  8025. return
  8026. name = obj.options["name"]
  8027. _filter = "SVG File (*.svg);;All Files (*.*)"
  8028. try:
  8029. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  8030. caption=_("Export SVG"),
  8031. directory=self.get_last_save_folder() + '/' + str(name) + '_svg',
  8032. filter=_filter)
  8033. except TypeError:
  8034. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export SVG"), filter=_filter)
  8035. filename = str(filename)
  8036. if filename == "":
  8037. self.inform.emit('[WARNING_NOTCL]%s' %
  8038. _(" Export SVG cancelled."))
  8039. return
  8040. else:
  8041. self.export_svg(name, filename)
  8042. if self.defaults["global_open_style"] is False:
  8043. self.file_opened.emit("SVG", filename)
  8044. self.file_saved.emit("SVG", filename)
  8045. def on_file_exportpng(self):
  8046. self.report_usage("on_file_exportpng")
  8047. App.log.debug("on_file_exportpng()")
  8048. self.date = str(datetime.today()).rpartition('.')[0]
  8049. self.date = ''.join(c for c in self.date if c not in ':-')
  8050. self.date = self.date.replace(' ', '_')
  8051. if self.is_legacy is False:
  8052. image = _screenshot()
  8053. data = np.asarray(image)
  8054. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  8055. self.inform.emit('[[WARNING_NOTCL]] %s' %
  8056. _('Data must be a 3D array with last dimension 3 or 4'))
  8057. return
  8058. filter_ = "PNG File (*.png);;All Files (*.*)"
  8059. try:
  8060. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  8061. caption=_("Export PNG Image"),
  8062. directory=self.get_last_save_folder() + '/png_' + self.date,
  8063. filter=filter_)
  8064. except TypeError:
  8065. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export PNG Image"), filter=filter_)
  8066. filename = str(filename)
  8067. if filename == "":
  8068. self.inform.emit(_("Export PNG cancelled."))
  8069. return
  8070. else:
  8071. if self.is_legacy is False:
  8072. write_png(filename, data)
  8073. else:
  8074. self.plotcanvas.figure.savefig(filename)
  8075. if self.defaults["global_open_style"] is False:
  8076. self.file_opened.emit("png", filename)
  8077. self.file_saved.emit("png", filename)
  8078. def on_file_savegerber(self):
  8079. """
  8080. Callback for menu item in Project context menu.
  8081. :return: None
  8082. """
  8083. self.report_usage("on_file_savegerber")
  8084. App.log.debug("on_file_savegerber()")
  8085. obj = self.collection.get_active()
  8086. if obj is None:
  8087. self.inform.emit('[WARNING_NOTCL] %s' %
  8088. _("No object selected. Please select an Gerber object to export."))
  8089. return
  8090. # Check for more compatible types and add as required
  8091. if not isinstance(obj, FlatCAMGerber):
  8092. self.inform.emit('[ERROR_NOTCL] %s' %
  8093. _("Failed. Only Gerber objects can be saved as Gerber files..."))
  8094. return
  8095. name = self.collection.get_active().options["name"]
  8096. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  8097. try:
  8098. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  8099. caption="Save Gerber source file",
  8100. directory=self.get_last_save_folder() + '/' + name,
  8101. filter=_filter)
  8102. except TypeError:
  8103. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Gerber source file"), filter=_filter)
  8104. filename = str(filename)
  8105. if filename == "":
  8106. self.inform.emit('[WARNING_NOTCL] %s' %
  8107. _("Save Gerber source file cancelled."))
  8108. return
  8109. else:
  8110. self.save_source_file(name, filename)
  8111. if self.defaults["global_open_style"] is False:
  8112. self.file_opened.emit("Gerber", filename)
  8113. self.file_saved.emit("Gerber", filename)
  8114. def on_file_savescript(self):
  8115. """
  8116. Callback for menu item in Project context menu.
  8117. :return: None
  8118. """
  8119. self.report_usage("on_file_savescript")
  8120. App.log.debug("on_file_savescript()")
  8121. obj = self.collection.get_active()
  8122. if obj is None:
  8123. self.inform.emit('[WARNING_NOTCL] %s' %
  8124. _("No object selected. Please select an Script object to export."))
  8125. return
  8126. # Check for more compatible types and add as required
  8127. if not isinstance(obj, FlatCAMScript):
  8128. self.inform.emit('[ERROR_NOTCL] %s' %
  8129. _("Failed. Only Script objects can be saved as TCL Script files..."))
  8130. return
  8131. name = self.collection.get_active().options["name"]
  8132. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  8133. try:
  8134. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  8135. caption="Save Script source file",
  8136. directory=self.get_last_save_folder() + '/' + name,
  8137. filter=_filter)
  8138. except TypeError:
  8139. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Script source file"), filter=_filter)
  8140. filename = str(filename)
  8141. if filename == "":
  8142. self.inform.emit('[WARNING_NOTCL] %s' %
  8143. _("Save Script source file cancelled."))
  8144. return
  8145. else:
  8146. self.save_source_file(name, filename)
  8147. if self.defaults["global_open_style"] is False:
  8148. self.file_opened.emit("Script", filename)
  8149. self.file_saved.emit("Script", filename)
  8150. def on_file_savedocument(self):
  8151. """
  8152. Callback for menu item in Project context menu.
  8153. :return: None
  8154. """
  8155. self.report_usage("on_file_savedocument")
  8156. App.log.debug("on_file_savedocument()")
  8157. obj = self.collection.get_active()
  8158. if obj is None:
  8159. self.inform.emit('[WARNING_NOTCL] %s' %
  8160. _("No object selected. Please select an Document object to export."))
  8161. return
  8162. # Check for more compatible types and add as required
  8163. if not isinstance(obj, FlatCAMScript):
  8164. self.inform.emit('[ERROR_NOTCL] %s' %
  8165. _("Failed. Only Document objects can be saved as Document files..."))
  8166. return
  8167. name = self.collection.get_active().options["name"]
  8168. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  8169. try:
  8170. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  8171. caption="Save Document source file",
  8172. directory=self.get_last_save_folder() + '/' + name,
  8173. filter=_filter)
  8174. except TypeError:
  8175. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Document source file"), filter=_filter)
  8176. filename = str(filename)
  8177. if filename == "":
  8178. self.inform.emit('[WARNING_NOTCL] %s' %
  8179. _("Save Document source file cancelled."))
  8180. return
  8181. else:
  8182. self.save_source_file(name, filename)
  8183. if self.defaults["global_open_style"] is False:
  8184. self.file_opened.emit("Document", filename)
  8185. self.file_saved.emit("Document", filename)
  8186. def on_file_saveexcellon(self):
  8187. """
  8188. Callback for menu item in project context menu.
  8189. :return: None
  8190. """
  8191. self.report_usage("on_file_saveexcellon")
  8192. App.log.debug("on_file_saveexcellon()")
  8193. obj = self.collection.get_active()
  8194. if obj is None:
  8195. self.inform.emit('[WARNING_NOTCL] %s' %
  8196. _("No object selected. Please select an Excellon object to export."))
  8197. return
  8198. # Check for more compatible types and add as required
  8199. if not isinstance(obj, FlatCAMExcellon):
  8200. self.inform.emit('[ERROR_NOTCL] %s' %
  8201. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  8202. return
  8203. name = self.collection.get_active().options["name"]
  8204. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  8205. try:
  8206. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  8207. caption=_("Save Excellon source file"),
  8208. directory=self.get_last_save_folder() + '/' + name,
  8209. filter=_filter)
  8210. except TypeError:
  8211. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Excellon source file"), filter=_filter)
  8212. filename = str(filename)
  8213. if filename == "":
  8214. self.inform.emit('[WARNING_NOTCL] %s' %
  8215. _("Saving Excellon source file cancelled."))
  8216. return
  8217. else:
  8218. self.save_source_file(name, filename)
  8219. if self.defaults["global_open_style"] is False:
  8220. self.file_opened.emit("Excellon", filename)
  8221. self.file_saved.emit("Excellon", filename)
  8222. def on_file_exportexcellon(self):
  8223. """
  8224. Callback for menu item File->Export->Excellon.
  8225. :return: None
  8226. """
  8227. self.report_usage("on_file_exportexcellon")
  8228. App.log.debug("on_file_exportexcellon()")
  8229. obj = self.collection.get_active()
  8230. if obj is None:
  8231. self.inform.emit('[WARNING_NOTCL] %s' %
  8232. _("No object selected. Please Select an Excellon object to export."))
  8233. return
  8234. # Check for more compatible types and add as required
  8235. if not isinstance(obj, FlatCAMExcellon):
  8236. self.inform.emit('[ERROR_NOTCL] %s' %
  8237. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  8238. return
  8239. name = self.collection.get_active().options["name"]
  8240. _filter = self.defaults["excellon_save_filters"]
  8241. try:
  8242. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  8243. caption=_("Export Excellon"),
  8244. directory=self.get_last_save_folder() + '/' + name,
  8245. filter=_filter)
  8246. except TypeError:
  8247. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Excellon"), filter=_filter)
  8248. filename = str(filename)
  8249. if filename == "":
  8250. self.inform.emit('[WARNING_NOTCL] %s' %
  8251. _("Export Excellon cancelled."))
  8252. return
  8253. else:
  8254. used_extension = filename.rpartition('.')[2]
  8255. obj.update_filters(last_ext=used_extension, filter_string='excellon_save_filters')
  8256. self.export_excellon(name, filename)
  8257. if self.defaults["global_open_style"] is False:
  8258. self.file_opened.emit("Excellon", filename)
  8259. self.file_saved.emit("Excellon", filename)
  8260. def on_file_exportgerber(self):
  8261. """
  8262. Callback for menu item File->Export->Gerber.
  8263. :return: None
  8264. """
  8265. self.report_usage("on_file_exportgerber")
  8266. App.log.debug("on_file_exportgerber()")
  8267. obj = self.collection.get_active()
  8268. if obj is None:
  8269. self.inform.emit('[WARNING_NOTCL] %s' %
  8270. _("No object selected. Please Select an Gerber object to export."))
  8271. return
  8272. # Check for more compatible types and add as required
  8273. if not isinstance(obj, FlatCAMGerber):
  8274. self.inform.emit('[ERROR_NOTCL] %s' %
  8275. _("Failed. Only Gerber objects can be saved as Gerber files..."))
  8276. return
  8277. name = self.collection.get_active().options["name"]
  8278. _filter_ = self.defaults['gerber_save_filters']
  8279. try:
  8280. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  8281. caption=_("Export Gerber"),
  8282. directory=self.get_last_save_folder() + '/' + name,
  8283. filter=_filter_)
  8284. except TypeError:
  8285. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export Gerber"), filter=_filter_)
  8286. filename = str(filename)
  8287. if filename == "":
  8288. self.inform.emit('[WARNING_NOTCL] %s' %
  8289. _("Export Gerber cancelled."))
  8290. return
  8291. else:
  8292. used_extension = filename.rpartition('.')[2]
  8293. obj.update_filters(last_ext=used_extension, filter_string='gerber_save_filters')
  8294. self.export_gerber(name, filename)
  8295. if self.defaults["global_open_style"] is False:
  8296. self.file_opened.emit("Gerber", filename)
  8297. self.file_saved.emit("Gerber", filename)
  8298. def on_file_exportdxf(self):
  8299. """
  8300. Callback for menu item File->Export DXF.
  8301. :return: None
  8302. """
  8303. self.report_usage("on_file_exportdxf")
  8304. App.log.debug("on_file_exportdxf()")
  8305. obj = self.collection.get_active()
  8306. if obj is None:
  8307. self.inform.emit('[WARNING_NOTCL] %s' %
  8308. _("No object selected."))
  8309. msg = _("Please Select a Geometry object to export")
  8310. msgbox = QtWidgets.QMessageBox()
  8311. msgbox.setInformativeText(msg)
  8312. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  8313. msgbox.setDefaultButton(bt_ok)
  8314. msgbox.exec_()
  8315. return
  8316. # Check for more compatible types and add as required
  8317. if not isinstance(obj, FlatCAMGeometry):
  8318. msg = '[ERROR_NOTCL] %s' % \
  8319. _("Only Geometry objects can be used.")
  8320. msgbox = QtWidgets.QMessageBox()
  8321. msgbox.setInformativeText(msg)
  8322. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  8323. msgbox.setDefaultButton(bt_ok)
  8324. msgbox.exec_()
  8325. return
  8326. name = self.collection.get_active().options["name"]
  8327. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  8328. try:
  8329. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  8330. caption=_("Export DXF"),
  8331. directory=self.get_last_save_folder() + '/' + name,
  8332. filter=_filter_)
  8333. except TypeError:
  8334. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Export DXF"),
  8335. filter=_filter_)
  8336. filename = str(filename)
  8337. if filename == "":
  8338. self.inform.emit('[WARNING_NOTCL] %s' %
  8339. _("Export DXF cancelled."))
  8340. return
  8341. else:
  8342. self.export_dxf(name, filename)
  8343. if self.defaults["global_open_style"] is False:
  8344. self.file_opened.emit("DXF", filename)
  8345. self.file_saved.emit("DXF", filename)
  8346. def on_file_importsvg(self, type_of_obj):
  8347. """
  8348. Callback for menu item File->Import SVG.
  8349. :param type_of_obj: to import the SVG as Geometry or as Gerber
  8350. :type type_of_obj: str
  8351. :return: None
  8352. """
  8353. self.report_usage("on_file_importsvg")
  8354. App.log.debug("on_file_importsvg()")
  8355. _filter_ = "SVG File (*.svg);;All Files (*.*)"
  8356. try:
  8357. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  8358. directory=self.get_last_folder(), filter=_filter_)
  8359. except TypeError:
  8360. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  8361. filter=_filter_)
  8362. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  8363. type_of_obj = "geometry"
  8364. filenames = [str(filename) for filename in filenames]
  8365. if len(filenames) == 0:
  8366. self.inform.emit('[WARNING_NOTCL] %s' %
  8367. _("Open SVG cancelled."))
  8368. else:
  8369. for filename in filenames:
  8370. if filename != '':
  8371. self.worker_task.emit({'fcn': self.import_svg,
  8372. 'params': [filename, type_of_obj]})
  8373. def on_file_importdxf(self, type_of_obj):
  8374. """
  8375. Callback for menu item File->Import DXF.
  8376. :param type_of_obj: to import the DXF as Geometry or as Gerber
  8377. :type type_of_obj: str
  8378. :return: None
  8379. """
  8380. self.report_usage("on_file_importdxf")
  8381. App.log.debug("on_file_importdxf()")
  8382. _filter_ = "DXF File (*.DXF);;All Files (*.*)"
  8383. try:
  8384. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  8385. directory=self.get_last_folder(),
  8386. filter=_filter_)
  8387. except TypeError:
  8388. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  8389. filter=_filter_)
  8390. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  8391. type_of_obj = "geometry"
  8392. filenames = [str(filename) for filename in filenames]
  8393. if len(filenames) == 0:
  8394. self.inform.emit('[WARNING_NOTCL] %s' %
  8395. _("Open DXF cancelled."))
  8396. else:
  8397. for filename in filenames:
  8398. if filename != '':
  8399. self.worker_task.emit({'fcn': self.import_dxf,
  8400. 'params': [filename, type_of_obj]})
  8401. # ###############################################################################################################
  8402. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  8403. # ###############################################################################################################
  8404. def init_code_editor(self, name):
  8405. self.text_editor_tab = TextEditor(app=self, plain_text=True)
  8406. # add the tab if it was closed
  8407. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  8408. self.text_editor_tab.setObjectName('text_editor_tab')
  8409. # delete the absolute and relative position and messages in the infobar
  8410. self.ui.position_label.setText("")
  8411. self.ui.rel_position_label.setText("")
  8412. # first clear previous text in text editor (if any)
  8413. self.text_editor_tab.code_editor.clear()
  8414. self.text_editor_tab.code_editor.setReadOnly(False)
  8415. self.toggle_codeeditor = True
  8416. self.text_editor_tab.code_editor.completer_enable = False
  8417. self.text_editor_tab.buttonRun.hide()
  8418. # make sure to keep a reference to the code editor
  8419. self.reference_code_editor = self.text_editor_tab.code_editor
  8420. # Switch plot_area to CNCJob tab
  8421. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  8422. def on_view_source(self):
  8423. """
  8424. Called when the user wants to see the source file of the selected object
  8425. :return:
  8426. """
  8427. self.inform.emit('%s' % _("Viewing the source code of the selected object."))
  8428. self.proc_container.view.set_busy(_("Loading..."))
  8429. try:
  8430. obj = self.collection.get_active()
  8431. except Exception as e:
  8432. log.debug("App.on_view_source() --> %s" % str(e))
  8433. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  8434. return 'fail'
  8435. if obj is None:
  8436. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  8437. return 'fail'
  8438. flt = "All Files (*.*)"
  8439. if obj.kind == 'gerber':
  8440. flt = "Gerber Files (*.GBR);;PDF Files (*.PDF);;All Files (*.*)"
  8441. elif obj.kind == 'excellon':
  8442. flt = "Excellon Files (*.DRL);;PDF Files (*.PDF);;All Files (*.*)"
  8443. elif obj.kind == 'cncjob':
  8444. flt = "GCode Files (*.NC);;PDF Files (*.PDF);;All Files (*.*)"
  8445. self.source_editor_tab = TextEditor(app=self, plain_text=True)
  8446. # add the tab if it was closed
  8447. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  8448. self.source_editor_tab.setObjectName('source_editor_tab')
  8449. # delete the absolute and relative position and messages in the infobar
  8450. self.ui.position_label.setText("")
  8451. self.ui.rel_position_label.setText("")
  8452. # first clear previous text in text editor (if any)
  8453. self.source_editor_tab.code_editor.clear()
  8454. self.source_editor_tab.code_editor.setReadOnly(False)
  8455. self.source_editor_tab.code_editor.completer_enable = False
  8456. self.source_editor_tab.buttonRun.hide()
  8457. # Switch plot_area to CNCJob tab
  8458. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  8459. try:
  8460. self.source_editor_tab.buttonOpen.clicked.disconnect()
  8461. except TypeError:
  8462. pass
  8463. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  8464. try:
  8465. self.source_editor_tab.buttonSave.clicked.disconnect()
  8466. except TypeError:
  8467. pass
  8468. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  8469. # then append the text from GCode to the text editor
  8470. if obj.kind == 'cncjob':
  8471. try:
  8472. file = obj.export_gcode(
  8473. preamble=self.defaults["cncjob_prepend"],
  8474. postamble=self.defaults["cncjob_append"],
  8475. to_file=True)
  8476. if file == 'fail':
  8477. return 'fail'
  8478. except AttributeError:
  8479. self.inform.emit('[WARNING_NOTCL] %s' %
  8480. _("There is no selected object for which to see it's source file code."))
  8481. return 'fail'
  8482. else:
  8483. try:
  8484. file = StringIO(obj.source_file)
  8485. except (AttributeError, TypeError):
  8486. self.inform.emit('[WARNING_NOTCL] %s' %
  8487. _("There is no selected object for which to see it's source file code."))
  8488. return 'fail'
  8489. self.source_editor_tab.t_frame.hide()
  8490. try:
  8491. self.source_editor_tab.code_editor.setPlainText(file.getvalue())
  8492. # for line in file:
  8493. # QtWidgets.QApplication.processEvents()
  8494. # proc_line = str(line).strip('\n')
  8495. # self.source_editor_tab.code_editor.append(proc_line)
  8496. except Exception as e:
  8497. log.debug('App.on_view_source() -->%s' % str(e))
  8498. self.inform.emit('[ERROR] %s: %s' % (_('Failed to load the source code for the selected object'), str(e)))
  8499. return
  8500. self.source_editor_tab.handleTextChanged()
  8501. self.source_editor_tab.t_frame.show()
  8502. self.source_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.Start)
  8503. self.proc_container.view.set_idle()
  8504. # self.ui.show()
  8505. def on_toggle_code_editor(self):
  8506. self.report_usage("on_toggle_code_editor()")
  8507. if self.toggle_codeeditor is False:
  8508. self.init_code_editor(name=_("Code Editor"))
  8509. self.text_editor_tab.buttonOpen.clicked.disconnect()
  8510. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  8511. self.text_editor_tab.buttonSave.clicked.disconnect()
  8512. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  8513. else:
  8514. for idx in range(self.ui.plot_tab_area.count()):
  8515. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  8516. self.ui.plot_tab_area.closeTab(idx)
  8517. break
  8518. self.toggle_codeeditor = False
  8519. def on_code_editor_close(self):
  8520. self.toggle_codeeditor = False
  8521. def goto_text_line(self):
  8522. """
  8523. Will scroll a text to the specified text line.
  8524. :return: None
  8525. """
  8526. dia_box = Dialog_box(title=_("Go to Line ..."),
  8527. label=_("Line:"),
  8528. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  8529. initial_text='')
  8530. try:
  8531. line = int(dia_box.location) - 1
  8532. except (ValueError, TypeError):
  8533. line = 0
  8534. if dia_box.ok:
  8535. # make sure to move first the cursor at the end so after finding the line the line will be positioned
  8536. # at the top of the window
  8537. self.ui.plot_tab_area.currentWidget().code_editor.moveCursor(QTextCursor.End)
  8538. # get the document() of the TextEditor
  8539. doc = self.ui.plot_tab_area.currentWidget().code_editor.document()
  8540. # create a Text Cursor based on the searched line
  8541. cursor = QTextCursor(doc.findBlockByLineNumber(line))
  8542. # set cursor of the code editor with the cursor at the searcehd line
  8543. self.ui.plot_tab_area.currentWidget().code_editor.setTextCursor(cursor)
  8544. def on_filenewscript(self, silent=False, name=None, text=None):
  8545. """
  8546. Will create a new script file and open it in the Code Editor
  8547. :param silent: if True will not display status messages
  8548. :param name: if specified will be the name of the new script
  8549. :param text: pass a source file to the newly created script to be loaded in it
  8550. :return: None
  8551. """
  8552. if silent is False:
  8553. self.inform.emit('[success] %s' % _("New TCL script file created in Code Editor."))
  8554. # delete the absolute and relative position and messages in the infobar
  8555. self.ui.position_label.setText("")
  8556. self.ui.rel_position_label.setText("")
  8557. if name is not None:
  8558. self.new_script_object(name=name, text=text)
  8559. else:
  8560. self.new_script_object(text=text)
  8561. # script_text = script_obj.source_file
  8562. #
  8563. # self.proc_container.view.set_busy(_("Loading..."))
  8564. # script_obj.script_editor_tab.t_frame.hide()
  8565. #
  8566. # script_obj.script_editor_tab.t_frame.show()
  8567. # self.proc_container.view.set_idle()
  8568. def on_fileopenscript(self, name=None, silent=False):
  8569. """
  8570. Will open a Tcl script file into the Code Editor
  8571. :param silent: if True will not display status messages
  8572. :param name: name of a Tcl script file to open
  8573. :return:
  8574. """
  8575. self.report_usage("on_fileopenscript")
  8576. App.log.debug("on_fileopenscript()")
  8577. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  8578. if name:
  8579. filenames = [name]
  8580. else:
  8581. try:
  8582. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  8583. caption=_("Open TCL script"), directory=self.get_last_folder(), filter=_filter_)
  8584. except TypeError:
  8585. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  8586. if len(filenames) == 0:
  8587. if silent is False:
  8588. self.inform.emit('[WARNING_NOTCL] %s' % _("Open TCL script cancelled."))
  8589. else:
  8590. for filename in filenames:
  8591. if filename != '':
  8592. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  8593. def on_filerunscript(self, name=None, silent=False):
  8594. """
  8595. File menu callback for loading and running a TCL script.
  8596. :param silent: if True will not display status messages
  8597. :param name: name of a Tcl script file to be run by FlatCAM
  8598. :return: None
  8599. """
  8600. self.report_usage("on_filerunscript")
  8601. App.log.debug("on_file_runscript()")
  8602. if name:
  8603. filename = name
  8604. if self.cmd_line_headless != 1:
  8605. self.splash.showMessage('%s: %ssec\n%s' %
  8606. (_("Canvas initialization started.\n"
  8607. "Canvas initialization finished in"), '%.2f' % self.used_time,
  8608. _("Executing FlatCAMScript file.")
  8609. ),
  8610. alignment=Qt.AlignBottom | Qt.AlignLeft,
  8611. color=QtGui.QColor("gray"))
  8612. else:
  8613. _filter_ = "TCL script (*.FlatScript);;TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  8614. try:
  8615. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  8616. directory=self.get_last_folder(), filter=_filter_)
  8617. except TypeError:
  8618. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  8619. # The Qt methods above will return a QString which can cause problems later.
  8620. # So far json.dump() will fail to serialize it.
  8621. # TODO: Improve the serialization methods and remove this fix.
  8622. filename = str(filename)
  8623. if filename == "":
  8624. if silent is False:
  8625. self.inform.emit('[WARNING_NOTCL] %s' % _("Run TCL script cancelled."))
  8626. else:
  8627. if self.cmd_line_headless != 1:
  8628. if self.ui.shell_dock.isHidden():
  8629. self.ui.shell_dock.show()
  8630. try:
  8631. with open(filename, "r") as tcl_script:
  8632. cmd_line_shellfile_content = tcl_script.read()
  8633. if self.cmd_line_headless != 1:
  8634. self.shell._sysShell.exec_command(cmd_line_shellfile_content)
  8635. else:
  8636. self.shell._sysShell.exec_command(cmd_line_shellfile_content, no_echo=True)
  8637. if silent is False:
  8638. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor and executed."))
  8639. except Exception as e:
  8640. log.debug("App.on_filerunscript() -> %s" % str(e))
  8641. sys.exit(2)
  8642. def on_file_saveproject(self, silent=False):
  8643. """
  8644. Callback for menu item File->Save Project. Saves the project to
  8645. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  8646. if set to None. The project is saved by calling ``self.save_project()``.
  8647. :param silent: if True will not display status messages
  8648. :return: None
  8649. """
  8650. self.report_usage("on_file_saveproject")
  8651. if self.project_filename is None:
  8652. self.on_file_saveprojectas()
  8653. else:
  8654. self.worker_task.emit({'fcn': self.save_project,
  8655. 'params': [self.project_filename, silent]})
  8656. if self.defaults["global_open_style"] is False:
  8657. self.file_opened.emit("project", self.project_filename)
  8658. self.file_saved.emit("project", self.project_filename)
  8659. self.set_ui_title(name=self.project_filename)
  8660. self.should_we_save = False
  8661. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  8662. """
  8663. Callback for menu item File->Save Project As... Opens a file
  8664. chooser and saves the project to the given file via
  8665. ``self.save_project()``.
  8666. :param make_copy if to be create a copy of the project; boolean
  8667. :param use_thread: if to be run in a separate thread; boolean
  8668. :param quit_action: if to be followed by quiting the application; boolean
  8669. :return: None
  8670. """
  8671. self.report_usage("on_file_saveprojectas")
  8672. self.date = str(datetime.today()).rpartition('.')[0]
  8673. self.date = ''.join(c for c in self.date if c not in ':-')
  8674. self.date = self.date.replace(' ', '_')
  8675. filter_ = "FlatCAM Project (*.FlatPrj);; All Files (*.*)"
  8676. try:
  8677. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  8678. caption=_("Save Project As ..."),
  8679. directory=('{l_save}/{proj}_{date}').format(l_save=str(self.get_last_save_folder()), date=self.date,
  8680. proj=_("Project")),
  8681. filter=filter_
  8682. )
  8683. except TypeError:
  8684. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Project As ..."), filter=filter_)
  8685. filename = str(filename)
  8686. if filename == '':
  8687. self.inform.emit('[WARNING_NOTCL] %s' % _("Save Project cancelled."))
  8688. return
  8689. if use_thread is True:
  8690. self.worker_task.emit({'fcn': self.save_project,
  8691. 'params': [filename, quit_action]})
  8692. else:
  8693. self.save_project(filename, quit_action)
  8694. # self.save_project(filename)
  8695. if self.defaults["global_open_style"] is False:
  8696. self.file_opened.emit("project", filename)
  8697. self.file_saved.emit("project", filename)
  8698. if not make_copy:
  8699. self.project_filename = filename
  8700. self.set_ui_title(name=self.project_filename)
  8701. self.should_we_save = False
  8702. def on_file_save_objects_pdf(self, use_thread=True):
  8703. self.date = str(datetime.today()).rpartition('.')[0]
  8704. self.date = ''.join(c for c in self.date if c not in ':-')
  8705. self.date = self.date.replace(' ', '_')
  8706. try:
  8707. obj_selection = self.collection.get_selected()
  8708. if len(obj_selection) == 1:
  8709. obj_name = str(obj_selection[0].options['name'])
  8710. else:
  8711. obj_name = _("FlatCAM objects print")
  8712. except AttributeError as err:
  8713. log.debug("App.on_file_save_object_pdf() --> %s" % str(err))
  8714. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  8715. return
  8716. if not obj_selection:
  8717. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  8718. return
  8719. filter_ = "PDF File (*.PDF);; All Files (*.*)"
  8720. try:
  8721. filename, _f = QtWidgets.QFileDialog.getSaveFileName(
  8722. caption=_("Save Object as PDF ..."),
  8723. directory=('{l_save}/{obj_name}_{date}').format(l_save=str(self.get_last_save_folder()),
  8724. obj_name=obj_name,
  8725. date=self.date),
  8726. filter=filter_
  8727. )
  8728. except TypeError:
  8729. filename, _f = QtWidgets.QFileDialog.getSaveFileName(caption=_("Save Object as PDF ..."), filter=filter_)
  8730. filename = str(filename)
  8731. if filename == '':
  8732. self.inform.emit('[WARNING_NOTCL] %s' % _("Save Object PDF cancelled."))
  8733. return
  8734. if use_thread is True:
  8735. proc = self.proc_container.new(_("Printing PDF ... Please wait."))
  8736. self.worker_task.emit({'fcn': self.save_pdf, 'params': [filename, obj_selection]})
  8737. else:
  8738. self.save_pdf(filename, obj_selection)
  8739. # self.save_project(filename)
  8740. if self.defaults["global_open_style"] is False:
  8741. self.file_opened.emit("pdf", filename)
  8742. self.file_saved.emit("pdf", filename)
  8743. def save_pdf(self, file_name, obj_selection):
  8744. p_size = self.defaults['global_workspaceT']
  8745. orientation = self.defaults['global_workspace_orientation']
  8746. color = 'black'
  8747. transparency_level = 1.0
  8748. self.pagesize = dict()
  8749. self.pagesize.update(
  8750. {
  8751. 'Bounds': None,
  8752. 'A0': (841*mm, 1189*mm),
  8753. 'A1': (594*mm, 841*mm),
  8754. 'A2': (420*mm, 594*mm),
  8755. 'A3': (297*mm, 420*mm),
  8756. 'A4': (210*mm, 297*mm),
  8757. 'A5': (148*mm, 210*mm),
  8758. 'A6': (105*mm, 148*mm),
  8759. 'A7': (74*mm, 105*mm),
  8760. 'A8': (52*mm, 74*mm),
  8761. 'A9': (37*mm, 52*mm),
  8762. 'A10': (26*mm, 37*mm),
  8763. 'B0': (1000*mm, 1414*mm),
  8764. 'B1': (707*mm, 1000*mm),
  8765. 'B2': (500*mm, 707*mm),
  8766. 'B3': (353*mm, 500*mm),
  8767. 'B4': (250*mm, 353*mm),
  8768. 'B5': (176*mm, 250*mm),
  8769. 'B6': (125*mm, 176*mm),
  8770. 'B7': (88*mm, 125*mm),
  8771. 'B8': (62*mm, 88*mm),
  8772. 'B9': (44*mm, 62*mm),
  8773. 'B10': (31*mm, 44*mm),
  8774. 'C0': (917*mm, 1297*mm),
  8775. 'C1': (648*mm, 917*mm),
  8776. 'C2': (458*mm, 648*mm),
  8777. 'C3': (324*mm, 458*mm),
  8778. 'C4': (229*mm, 324*mm),
  8779. 'C5': (162*mm, 229*mm),
  8780. 'C6': (114*mm, 162*mm),
  8781. 'C7': (81*mm, 114*mm),
  8782. 'C8': (57*mm, 81*mm),
  8783. 'C9': (40*mm, 57*mm),
  8784. 'C10': (28*mm, 40*mm),
  8785. # American paper sizes
  8786. 'LETTER': (8.5*inch, 11*inch),
  8787. 'LEGAL': (8.5*inch, 14*inch),
  8788. 'ELEVENSEVENTEEN': (11*inch, 17*inch),
  8789. # From https://en.wikipedia.org/wiki/Paper_size
  8790. 'JUNIOR_LEGAL': (5*inch, 8*inch),
  8791. 'HALF_LETTER': (5.5*inch, 8*inch),
  8792. 'GOV_LETTER': (8*inch, 10.5*inch),
  8793. 'GOV_LEGAL': (8.5*inch, 13*inch),
  8794. 'LEDGER': (17*inch, 11*inch),
  8795. }
  8796. )
  8797. exported_svg = list()
  8798. for obj in obj_selection:
  8799. svg_obj = obj.export_svg(scale_stroke_factor=0.0,
  8800. scale_factor_x=None, scale_factor_y=None,
  8801. skew_factor_x=None, skew_factor_y=None,
  8802. mirror=None)
  8803. if obj.kind.lower() == 'gerber':
  8804. # color = self.defaults["gerber_plot_fill"][:-2]
  8805. color = obj.fill_color[:-2]
  8806. elif obj.kind.lower() == 'excellon':
  8807. color = '#C40000'
  8808. elif obj.kind.lower() == 'geometry':
  8809. color = self.defaults["global_draw_color"]
  8810. # Change the attributes of the exported SVG
  8811. # We don't need stroke-width
  8812. # We set opacity to maximum
  8813. # We set the colour to WHITE
  8814. root = ET.fromstring(svg_obj)
  8815. for child in root:
  8816. child.set('fill', str(color))
  8817. child.set('opacity', str(transparency_level))
  8818. child.set('stroke', str(color))
  8819. exported_svg.append(ET.tostring(root))
  8820. xmin = Inf
  8821. ymin = Inf
  8822. xmax = -Inf
  8823. ymax = -Inf
  8824. for obj in obj_selection:
  8825. try:
  8826. gxmin, gymin, gxmax, gymax = obj.bounds()
  8827. xmin = min([xmin, gxmin])
  8828. ymin = min([ymin, gymin])
  8829. xmax = max([xmax, gxmax])
  8830. ymax = max([ymax, gymax])
  8831. except Exception as e:
  8832. log.warning("DEV WARNING: Tried to get bounds of empty geometry in App.save_pdf(). %s" % str(e))
  8833. # Determine bounding area for svg export
  8834. bounds = [xmin, ymin, xmax, ymax]
  8835. size = bounds[2] - bounds[0], bounds[3] - bounds[1]
  8836. # This contain the measure units
  8837. uom = obj_selection[0].units.lower()
  8838. # Define a boundary around SVG of about 1.0mm (~39mils)
  8839. if uom in "mm":
  8840. boundary = 1.0
  8841. else:
  8842. boundary = 0.0393701
  8843. # Convert everything to strings for use in the xml doc
  8844. svgwidth = str(size[0] + (2 * boundary))
  8845. svgheight = str(size[1] + (2 * boundary))
  8846. minx = str(bounds[0] - boundary)
  8847. miny = str(bounds[1] + boundary + size[1])
  8848. # Add a SVG Header and footer to the svg output from shapely
  8849. # The transform flips the Y Axis so that everything renders
  8850. # properly within svg apps such as inkscape
  8851. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  8852. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  8853. svg_header += 'width="' + svgwidth + uom + '" '
  8854. svg_header += 'height="' + svgheight + uom + '" '
  8855. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  8856. svg_header += '>'
  8857. svg_header += '<g transform="scale(1,-1)">'
  8858. svg_footer = '</g> </svg>'
  8859. svg_elem = str(svg_header)
  8860. for svg_item in exported_svg:
  8861. svg_elem += str(svg_item)
  8862. svg_elem += str(svg_footer)
  8863. # Parse the xml through a xml parser just to add line feeds
  8864. # and to make it look more pretty for the output
  8865. doc = parse_xml_string(svg_elem)
  8866. doc_final = doc.toprettyxml()
  8867. try:
  8868. if self.defaults['units'].upper() == 'IN':
  8869. unit = inch
  8870. else:
  8871. unit = mm
  8872. doc_final = StringIO(doc_final)
  8873. drawing = svg2rlg(doc_final)
  8874. if p_size == 'Bounds':
  8875. renderPDF.drawToFile(drawing, file_name)
  8876. else:
  8877. if orientation == 'p':
  8878. page_size = portrait(self.pagesize[p_size])
  8879. else:
  8880. page_size = landscape(self.pagesize[p_size])
  8881. my_canvas = canvas.Canvas(file_name, pagesize=page_size)
  8882. my_canvas.translate(bounds[0] * unit, bounds[1] * unit)
  8883. renderPDF.draw(drawing, my_canvas, 0, 0)
  8884. my_canvas.save()
  8885. except Exception as e:
  8886. log.debug("App.save_pdf() --> PDF output --> %s" % str(e))
  8887. return 'fail'
  8888. self.inform.emit('[success] %s: %s' % (_("PDF file saved to"), file_name))
  8889. def export_svg(self, obj_name, filename, scale_stroke_factor=0.00):
  8890. """
  8891. Exports a Geometry Object to an SVG file.
  8892. :param obj_name: the name of the FlatCAM object to be saved as SVG
  8893. :param filename: Path to the SVG file to save to.
  8894. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  8895. :return:
  8896. """
  8897. self.report_usage("export_svg()")
  8898. if filename is None:
  8899. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  8900. is not None else self.defaults["global_last_folder"]
  8901. self.log.debug("export_svg()")
  8902. try:
  8903. obj = self.collection.get_by_name(str(obj_name))
  8904. except Exception:
  8905. # TODO: The return behavior has not been established... should raise exception?
  8906. return "Could not retrieve object: %s" % obj_name
  8907. with self.proc_container.new(_("Exporting SVG")) as proc:
  8908. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor)
  8909. # Determine bounding area for svg export
  8910. bounds = obj.bounds()
  8911. size = obj.size()
  8912. # Convert everything to strings for use in the xml doc
  8913. svgwidth = str(size[0])
  8914. svgheight = str(size[1])
  8915. minx = str(bounds[0])
  8916. miny = str(bounds[1] - size[1])
  8917. uom = obj.units.lower()
  8918. # Add a SVG Header and footer to the svg output from shapely
  8919. # The transform flips the Y Axis so that everything renders
  8920. # properly within svg apps such as inkscape
  8921. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  8922. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  8923. svg_header += 'width="' + svgwidth + uom + '" '
  8924. svg_header += 'height="' + svgheight + uom + '" '
  8925. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  8926. svg_header += '<g transform="scale(1,-1)">'
  8927. svg_footer = '</g> </svg>'
  8928. svg_elem = svg_header + exported_svg + svg_footer
  8929. # Parse the xml through a xml parser just to add line feeds
  8930. # and to make it look more pretty for the output
  8931. svgcode = parse_xml_string(svg_elem)
  8932. svgcode = svgcode.toprettyxml()
  8933. try:
  8934. with open(filename, 'w') as fp:
  8935. fp.write(svgcode)
  8936. except PermissionError:
  8937. self.inform.emit('[WARNING] %s' %
  8938. _("Permission denied, saving not possible.\n"
  8939. "Most likely another app is holding the file open and not accessible."))
  8940. return 'fail'
  8941. if self.defaults["global_open_style"] is False:
  8942. self.file_opened.emit("SVG", filename)
  8943. self.file_saved.emit("SVG", filename)
  8944. self.inform.emit('[success] %s: %s' %
  8945. (_("SVG file exported to"), filename))
  8946. def save_source_file(self, obj_name, filename, use_thread=True):
  8947. """
  8948. Exports a FlatCAM Object to an Gerber/Excellon file.
  8949. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  8950. :param filename: Path to the Gerber file to save to.
  8951. :param use_thread: if to be run in a separate thread
  8952. :return:
  8953. """
  8954. self.report_usage("save source file()")
  8955. if filename is None:
  8956. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  8957. is not None else self.defaults["global_last_folder"]
  8958. self.log.debug("save source file()")
  8959. obj = self.collection.get_by_name(obj_name)
  8960. file_string = StringIO(obj.source_file)
  8961. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  8962. if file_string.getvalue() == '':
  8963. self.inform.emit('[ERROR_NOTCL] %s' %
  8964. _("Save cancelled because source file is empty. Try to export the Gerber file."))
  8965. return 'fail'
  8966. try:
  8967. with open(filename, 'w') as file:
  8968. file.writelines('G04*\n')
  8969. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  8970. (obj.kind.upper(), str(self.version), str(self.version_date)))
  8971. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  8972. file.writelines('G04 Created on : %s*\n' % time_string)
  8973. for line in file_string:
  8974. file.writelines(line)
  8975. except PermissionError:
  8976. self.inform.emit('[WARNING] %s' %
  8977. _("Permission denied, saving not possible.\n"
  8978. "Most likely another app is holding the file open and not accessible."))
  8979. return 'fail'
  8980. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  8981. """
  8982. Exports a Excellon Object to an Excellon file.
  8983. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  8984. :param filename: Path to the Excellon file to save to.
  8985. :param local_use:
  8986. :param use_thread: if to be run in a separate thread
  8987. :return:
  8988. """
  8989. self.report_usage("export_excellon()")
  8990. if filename is None:
  8991. if self.defaults["global_last_save_folder"]:
  8992. filename = self.defaults["global_last_save_folder"] + '/' + 'exported_excellon'
  8993. else:
  8994. filename = self.defaults["global_last_folder"] + '/' + 'exported_excellon'
  8995. self.log.debug("export_excellon()")
  8996. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  8997. self.defaults["excellon_exp_decimals"]
  8998. )
  8999. if local_use is None:
  9000. try:
  9001. obj = self.collection.get_by_name(str(obj_name))
  9002. except Exception:
  9003. # TODO: The return behavior has not been established... should raise exception?
  9004. return "Could not retrieve object: %s" % obj_name
  9005. else:
  9006. obj = local_use
  9007. if not isinstance(obj, FlatCAMExcellon):
  9008. self.inform.emit('[ERROR_NOTCL] %s' %
  9009. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  9010. return
  9011. # updated units
  9012. eunits = self.defaults["excellon_exp_units"]
  9013. ewhole = self.defaults["excellon_exp_integer"]
  9014. efract = self.defaults["excellon_exp_decimals"]
  9015. ezeros = self.defaults["excellon_exp_zeros"]
  9016. eformat = self.defaults["excellon_exp_format"]
  9017. slot_type = self.defaults["excellon_exp_slot_type"]
  9018. fc_units = self.defaults['units'].upper()
  9019. if fc_units == 'MM':
  9020. factor = 1 if eunits == 'METRIC' else 0.03937
  9021. else:
  9022. factor = 25.4 if eunits == 'METRIC' else 1
  9023. def make_excellon():
  9024. try:
  9025. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  9026. header = 'M48\n'
  9027. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  9028. (str(self.version), str(self.version_date))
  9029. header += ';Filename: %s' % str(obj_name) + '\n'
  9030. header += ';Created on : %s' % time_str + '\n'
  9031. if eformat == 'dec':
  9032. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  9033. header += eunits + '\n'
  9034. for tool in obj.tools:
  9035. if eunits == 'METRIC':
  9036. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  9037. tool=str(tool),
  9038. dec=2)
  9039. else:
  9040. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  9041. tool=str(tool),
  9042. dec=4)
  9043. else:
  9044. if ezeros == 'LZ':
  9045. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  9046. form='ndec', e_zeros='LZ', factor=factor,
  9047. slot_type=slot_type)
  9048. header += '%s,%s\n' % (eunits, 'LZ')
  9049. header += format_exc
  9050. for tool in obj.tools:
  9051. if eunits == 'METRIC':
  9052. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  9053. tool=str(tool),
  9054. dec=2)
  9055. else:
  9056. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  9057. tool=str(tool),
  9058. dec=4)
  9059. else:
  9060. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  9061. form='ndec', e_zeros='TZ', factor=factor,
  9062. slot_type=slot_type)
  9063. header += '%s,%s\n' % (eunits, 'TZ')
  9064. header += format_exc
  9065. for tool in obj.tools:
  9066. if eunits == 'METRIC':
  9067. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  9068. tool=str(tool),
  9069. dec=2)
  9070. else:
  9071. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  9072. tool=str(tool),
  9073. dec=4)
  9074. header += '%\n'
  9075. footer = 'M30\n'
  9076. exported_excellon = header
  9077. exported_excellon += excellon_code
  9078. exported_excellon += footer
  9079. if local_use is None:
  9080. try:
  9081. with open(filename, 'w') as fp:
  9082. fp.write(exported_excellon)
  9083. except PermissionError:
  9084. self.inform.emit('[WARNING] %s' %
  9085. _("Permission denied, saving not possible.\n"
  9086. "Most likely another app is holding the file open and not accessible."))
  9087. return 'fail'
  9088. if self.defaults["global_open_style"] is False:
  9089. self.file_opened.emit("Excellon", filename)
  9090. self.file_saved.emit("Excellon", filename)
  9091. self.inform.emit('[success] %s: %s' %
  9092. (_("Excellon file exported to"), filename))
  9093. else:
  9094. return exported_excellon
  9095. except Exception as e:
  9096. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  9097. return 'fail'
  9098. if use_thread is True:
  9099. with self.proc_container.new(_("Exporting Excellon")) as proc:
  9100. def job_thread_exc(app_obj):
  9101. ret = make_excellon()
  9102. if ret == 'fail':
  9103. self.inform.emit('[ERROR_NOTCL] %s' %
  9104. _('Could not export Excellon file.'))
  9105. return
  9106. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  9107. else:
  9108. ret = make_excellon()
  9109. if ret == 'fail':
  9110. self.inform.emit('[ERROR_NOTCL] %s' %
  9111. _('Could not export Excellon file.'))
  9112. return 'fail'
  9113. if local_use is not None:
  9114. return ret
  9115. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  9116. """
  9117. Exports a Gerber Object to an Gerber file.
  9118. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  9119. :param filename: Path to the Gerber file to save to.
  9120. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  9121. When not None, the value will be the actual Gerber object for which to create the Gerber code
  9122. :param use_thread: if to be run in a separate thread
  9123. :return:
  9124. """
  9125. self.report_usage("export_gerber()")
  9126. if filename is None:
  9127. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  9128. is not None else self.defaults["global_last_folder"]
  9129. self.log.debug("export_gerber()")
  9130. if local_use is None:
  9131. try:
  9132. obj = self.collection.get_by_name(str(obj_name))
  9133. except Exception:
  9134. # TODO: The return behavior has not been established... should raise exception?
  9135. return "Could not retrieve object: %s" % obj_name
  9136. else:
  9137. obj = local_use
  9138. # updated units
  9139. gunits = self.defaults["gerber_exp_units"]
  9140. gwhole = self.defaults["gerber_exp_integer"]
  9141. gfract = self.defaults["gerber_exp_decimals"]
  9142. gzeros = self.defaults["gerber_exp_zeros"]
  9143. fc_units = self.defaults['units'].upper()
  9144. if fc_units == 'MM':
  9145. factor = 1 if gunits == 'MM' else 0.03937
  9146. else:
  9147. factor = 25.4 if gunits == 'MM' else 1
  9148. def make_gerber():
  9149. try:
  9150. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  9151. header = 'G04*\n'
  9152. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  9153. (str(self.version), str(self.version_date))
  9154. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  9155. header += 'G04 Created on : %s*' % time_str + '\n'
  9156. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  9157. header += "%MO{units}*%\n".format(units=gunits)
  9158. for apid in obj.apertures:
  9159. if obj.apertures[apid]['type'] == 'C':
  9160. header += "%ADD{apid}{type},{size}*%\n".format(
  9161. apid=str(apid),
  9162. type='C',
  9163. size=(factor * obj.apertures[apid]['size'])
  9164. )
  9165. elif obj.apertures[apid]['type'] == 'R':
  9166. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  9167. apid=str(apid),
  9168. type='R',
  9169. width=(factor * obj.apertures[apid]['width']),
  9170. height=(factor * obj.apertures[apid]['height'])
  9171. )
  9172. elif obj.apertures[apid]['type'] == 'O':
  9173. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  9174. apid=str(apid),
  9175. type='O',
  9176. width=(factor * obj.apertures[apid]['width']),
  9177. height=(factor * obj.apertures[apid]['height'])
  9178. )
  9179. header += '\n'
  9180. # obsolete units but some software may need it
  9181. if gunits == 'IN':
  9182. header += 'G70*\n'
  9183. else:
  9184. header += 'G71*\n'
  9185. # Absolute Mode
  9186. header += 'G90*\n'
  9187. header += 'G01*\n'
  9188. # positive polarity
  9189. header += '%LPD*%\n'
  9190. footer = 'M02*\n'
  9191. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  9192. exported_gerber = header
  9193. exported_gerber += gerber_code
  9194. exported_gerber += footer
  9195. if local_use is None:
  9196. try:
  9197. with open(filename, 'w') as fp:
  9198. fp.write(exported_gerber)
  9199. except PermissionError:
  9200. self.inform.emit('[WARNING] %s' %
  9201. _("Permission denied, saving not possible.\n"
  9202. "Most likely another app is holding the file open and not accessible."))
  9203. return 'fail'
  9204. if self.defaults["global_open_style"] is False:
  9205. self.file_opened.emit("Gerber", filename)
  9206. self.file_saved.emit("Gerber", filename)
  9207. self.inform.emit('[success] %s: %s' %
  9208. (_("Gerber file exported to"), filename))
  9209. else:
  9210. return exported_gerber
  9211. except Exception as e:
  9212. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  9213. return 'fail'
  9214. if use_thread is True:
  9215. with self.proc_container.new(_("Exporting Gerber")) as proc:
  9216. def job_thread_grb(app_obj):
  9217. ret = make_gerber()
  9218. if ret == 'fail':
  9219. self.inform.emit('[ERROR_NOTCL] %s' %
  9220. _('Could not export Gerber file.'))
  9221. return
  9222. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  9223. else:
  9224. ret = make_gerber()
  9225. if ret == 'fail':
  9226. self.inform.emit('[ERROR_NOTCL] %s' %
  9227. _('Could not export Gerber file.'))
  9228. return 'fail'
  9229. if local_use is not None:
  9230. return ret
  9231. def export_dxf(self, obj_name, filename, use_thread=True):
  9232. """
  9233. Exports a Geometry Object to an DXF file.
  9234. :param obj_name: the name of the FlatCAM object to be saved as DXF
  9235. :param filename: Path to the DXF file to save to.
  9236. :param use_thread: if to be run in a separate thread
  9237. :return:
  9238. """
  9239. self.report_usage("export_dxf()")
  9240. if filename is None:
  9241. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  9242. is not None else self.defaults["global_last_folder"]
  9243. self.log.debug("export_dxf()")
  9244. try:
  9245. obj = self.collection.get_by_name(str(obj_name))
  9246. except Exception:
  9247. # TODO: The return behavior has not been established... should raise exception?
  9248. return "Could not retrieve object: %s" % obj_name
  9249. def make_dxf():
  9250. try:
  9251. dxf_code = obj.export_dxf()
  9252. dxf_code.saveas(filename)
  9253. if self.defaults["global_open_style"] is False:
  9254. self.file_opened.emit("DXF", filename)
  9255. self.file_saved.emit("DXF", filename)
  9256. self.inform.emit('[success] %s: %s' % (_("DXF file exported to"), filename))
  9257. except Exception:
  9258. return 'fail'
  9259. if use_thread is True:
  9260. with self.proc_container.new(_("Exporting DXF")) as proc:
  9261. def job_thread_exc(app_obj):
  9262. ret_dxf_val = make_dxf()
  9263. if ret_dxf_val == 'fail':
  9264. app_obj.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  9265. return
  9266. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  9267. else:
  9268. ret = make_dxf()
  9269. if ret == 'fail':
  9270. self.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  9271. return
  9272. def import_svg(self, filename, geo_type='geometry', outname=None):
  9273. """
  9274. Adds a new Geometry Object to the projects and populates
  9275. it with shapes extracted from the SVG file.
  9276. :param filename: Path to the SVG file.
  9277. :param geo_type: Type of FlatCAM object that will be created from SVG
  9278. :param outname:
  9279. :return:
  9280. """
  9281. self.report_usage("import_svg()")
  9282. log.debug("App.import_svg()")
  9283. obj_type = ""
  9284. if geo_type is None or geo_type == "geometry":
  9285. obj_type = "geometry"
  9286. elif geo_type == "gerber":
  9287. obj_type = "gerber"
  9288. else:
  9289. self.inform.emit('[ERROR_NOTCL] %s' %
  9290. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  9291. return
  9292. units = self.defaults['units'].upper()
  9293. def obj_init(geo_obj, app_obj):
  9294. geo_obj.import_svg(filename, obj_type, units=units)
  9295. geo_obj.multigeo = False
  9296. geo_obj.source_file = self.export_gerber(obj_name=name, filename=None, local_use=geo_obj, use_thread=False)
  9297. with self.proc_container.new(_("Importing SVG")) as proc:
  9298. # Object name
  9299. name = outname or filename.split('/')[-1].split('\\')[-1]
  9300. self.new_object(obj_type, name, obj_init, autoselected=False)
  9301. # Register recent file
  9302. self.file_opened.emit("svg", filename)
  9303. # GUI feedback
  9304. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  9305. def import_dxf(self, filename, geo_type='geometry', outname=None):
  9306. """
  9307. Adds a new Geometry Object to the projects and populates
  9308. it with shapes extracted from the DXF file.
  9309. :param filename: Path to the DXF file.
  9310. :param geo_type: Type of FlatCAM object that will be created from DXF
  9311. :param outname:
  9312. :type putname: str
  9313. :return:
  9314. """
  9315. self.report_usage("import_dxf()")
  9316. obj_type = ""
  9317. if geo_type is None or geo_type == "geometry":
  9318. obj_type = "geometry"
  9319. elif geo_type == "gerber":
  9320. obj_type = geo_type
  9321. else:
  9322. self.inform.emit('[ERROR_NOTCL] %s' %
  9323. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  9324. return
  9325. units = self.defaults['units'].upper()
  9326. def obj_init(geo_obj, app_obj):
  9327. geo_obj.import_dxf(filename, obj_type, units=units)
  9328. geo_obj.multigeo = False
  9329. with self.proc_container.new(_("Importing DXF")) as proc:
  9330. # Object name
  9331. name = outname or filename.split('/')[-1].split('\\')[-1]
  9332. self.new_object(obj_type, name, obj_init, autoselected=False)
  9333. # Register recent file
  9334. self.file_opened.emit("dxf", filename)
  9335. # GUI feedback
  9336. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  9337. def open_gerber(self, filename, outname=None):
  9338. """
  9339. Opens a Gerber file, parses it and creates a new object for
  9340. it in the program. Thread-safe.
  9341. :param outname: Name of the resulting object. None causes the
  9342. name to be that of the file.
  9343. :param filename: Gerber file filename
  9344. :type filename: str
  9345. :return: None
  9346. """
  9347. # How the object should be initialized
  9348. def obj_init(gerber_obj, app_obj):
  9349. assert isinstance(gerber_obj, FlatCAMGerber), \
  9350. "Expected to initialize a FlatCAMGerber but got %s" % type(gerber_obj)
  9351. # Opening the file happens here
  9352. try:
  9353. gerber_obj.parse_file(filename)
  9354. except IOError:
  9355. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  9356. return "fail"
  9357. except ParseError as err:
  9358. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  9359. app_obj.log.error(str(err))
  9360. return "fail"
  9361. except Exception as e:
  9362. log.debug("App.open_gerber() --> %s" % str(e))
  9363. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  9364. msg += traceback.format_exc()
  9365. app_obj.inform.emit(msg)
  9366. return "fail"
  9367. if gerber_obj.is_empty():
  9368. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  9369. _("Object is not Gerber file or empty. Aborting object creation."))
  9370. return "fail"
  9371. App.log.debug("open_gerber()")
  9372. with self.proc_container.new(_("Opening Gerber")) as proc:
  9373. # Object name
  9374. name = outname or filename.split('/')[-1].split('\\')[-1]
  9375. # # ## Object creation # ##
  9376. ret = self.new_object("gerber", name, obj_init, autoselected=False)
  9377. if ret == 'fail':
  9378. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open Gerber failed. Probable not a Gerber file.'))
  9379. return 'fail'
  9380. # Register recent file
  9381. self.file_opened.emit("gerber", filename)
  9382. # GUI feedback
  9383. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  9384. def open_excellon(self, filename, outname=None, plot=True):
  9385. """
  9386. Opens an Excellon file, parses it and creates a new object for
  9387. it in the program. Thread-safe.
  9388. :param outname: Name of the resulting object. None causes the name to be that of the file.
  9389. :param filename: Excellon file filename
  9390. :type filename: str
  9391. :param plot: boolean, to plot or not the resulting object
  9392. :return: None
  9393. """
  9394. App.log.debug("open_excellon()")
  9395. # How the object should be initialized
  9396. def obj_init(excellon_obj, app_obj):
  9397. try:
  9398. ret = excellon_obj.parse_file(filename=filename)
  9399. if ret == "fail":
  9400. log.debug("Excellon parsing failed.")
  9401. self.inform.emit('[ERROR_NOTCL] %s' %
  9402. _("This is not Excellon file."))
  9403. return "fail"
  9404. except IOError:
  9405. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  9406. (_("Cannot open file"), filename))
  9407. log.debug("Could not open Excellon object.")
  9408. return "fail"
  9409. except Exception:
  9410. msg = '[ERROR_NOTCL] %s' % \
  9411. _("An internal error has occurred. See shell.\n")
  9412. msg += traceback.format_exc()
  9413. app_obj.inform.emit(msg)
  9414. return "fail"
  9415. ret = excellon_obj.create_geometry()
  9416. if ret == 'fail':
  9417. log.debug("Could not create geometry for Excellon object.")
  9418. return "fail"
  9419. for tool in excellon_obj.tools:
  9420. if excellon_obj.tools[tool]['solid_geometry']:
  9421. return
  9422. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  9423. (_("No geometry found in file"), filename))
  9424. return "fail"
  9425. with self.proc_container.new(_("Opening Excellon.")):
  9426. # Object name
  9427. name = outname or filename.split('/')[-1].split('\\')[-1]
  9428. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  9429. if ret_val == 'fail':
  9430. self.inform.emit('[ERROR_NOTCL] %s' %
  9431. _('Open Excellon file failed. Probable not an Excellon file.'))
  9432. return
  9433. # Register recent file
  9434. self.file_opened.emit("excellon", filename)
  9435. # GUI feedback
  9436. self.inform.emit('[success] %s: %s' %
  9437. (_("Opened"), filename))
  9438. def open_gcode(self, filename, outname=None, force_parsing=None, plot=True):
  9439. """
  9440. Opens a G-gcode file, parses it and creates a new object for
  9441. it in the program. Thread-safe.
  9442. :param outname: Name of the resulting object. None causes the name to be that of the file.
  9443. :param filename: G-code file filename
  9444. :type filename: str
  9445. :return: None
  9446. """
  9447. App.log.debug("open_gcode()")
  9448. # How the object should be initialized
  9449. def obj_init(job_obj, app_obj_):
  9450. """
  9451. :param job_obj: the resulting object
  9452. :type app_obj_: App
  9453. """
  9454. assert isinstance(app_obj_, App), \
  9455. "Initializer expected App, got %s" % type(app_obj_)
  9456. app_obj_.inform.emit('%s...' % _("Reading GCode file"))
  9457. try:
  9458. f = open(filename)
  9459. gcode = f.read()
  9460. f.close()
  9461. except IOError:
  9462. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' %
  9463. (_("Failed to open"), filename))
  9464. return "fail"
  9465. job_obj.gcode = gcode
  9466. gcode_ret = job_obj.gcode_parse(force_parsing=force_parsing)
  9467. if gcode_ret == "fail":
  9468. self.inform.emit('[ERROR_NOTCL] %s' %
  9469. _("This is not GCODE"))
  9470. return "fail"
  9471. job_obj.create_geometry()
  9472. with self.proc_container.new(_("Opening G-Code.")):
  9473. # Object name
  9474. name = outname or filename.split('/')[-1].split('\\')[-1]
  9475. # New object creation and file processing
  9476. obj_ret = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  9477. if obj_ret == 'fail':
  9478. self.inform.emit('[ERROR_NOTCL] %s' %
  9479. _("Failed to create CNCJob Object. Probable not a GCode file. "
  9480. "Try to load it from File menu.\n "
  9481. "Attempting to create a FlatCAM CNCJob Object from "
  9482. "G-Code file failed during processing"))
  9483. return "fail"
  9484. # Register recent file
  9485. self.file_opened.emit("cncjob", filename)
  9486. # GUI feedback
  9487. self.inform.emit('[success] %s: %s' %
  9488. (_("Opened"), filename))
  9489. def open_hpgl2(self, filename, outname=None):
  9490. """
  9491. Opens a HPGL2 file, parses it and creates a new object for
  9492. it in the program. Thread-safe.
  9493. :param outname: Name of the resulting object. None causes the
  9494. name to be that of the file.
  9495. :param filename: HPGL2 file filename
  9496. :type filename: str
  9497. :return: None
  9498. """
  9499. filename = filename
  9500. # How the object should be initialized
  9501. def obj_init(geo_obj, app_obj):
  9502. assert isinstance(geo_obj, FlatCAMGeometry), \
  9503. "Expected to initialize a FlatCAMGeometry but got %s" % type(geo_obj)
  9504. # Opening the file happens here
  9505. obj = HPGL2(self)
  9506. try:
  9507. HPGL2.parse_file(obj, filename)
  9508. except IOError:
  9509. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  9510. return "fail"
  9511. except ParseError as err:
  9512. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  9513. app_obj.log.error(str(err))
  9514. return "fail"
  9515. except Exception as e:
  9516. log.debug("App.open_hpgl2() --> %s" % str(e))
  9517. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  9518. msg += traceback.format_exc()
  9519. app_obj.inform.emit(msg)
  9520. return "fail"
  9521. geo_obj.multigeo = True
  9522. geo_obj.solid_geometry = deepcopy(obj.solid_geometry)
  9523. geo_obj.tools = deepcopy(obj.tools)
  9524. geo_obj.source_file = deepcopy(obj.source_file)
  9525. del obj
  9526. if not geo_obj.solid_geometry:
  9527. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  9528. _("Object is not HPGL2 file or empty. Aborting object creation."))
  9529. return "fail"
  9530. App.log.debug("open_hpgl2()")
  9531. with self.proc_container.new(_("Opening HPGL2")) as proc:
  9532. # Object name
  9533. name = outname or filename.split('/')[-1].split('\\')[-1]
  9534. # # ## Object creation # ##
  9535. ret = self.new_object("geometry", name, obj_init, autoselected=False)
  9536. if ret == 'fail':
  9537. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open HPGL2 failed. Probable not a HPGL2 file.'))
  9538. return 'fail'
  9539. # Register recent file
  9540. self.file_opened.emit("geometry", filename)
  9541. # GUI feedback
  9542. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  9543. def open_script(self, filename, outname=None, silent=False):
  9544. """
  9545. Opens a Script file, parses it and creates a new object for
  9546. it in the program. Thread-safe.
  9547. :param outname: Name of the resulting object. None causes the name to be that of the file.
  9548. :param filename: Script file filename
  9549. :type filename: str
  9550. :return: None
  9551. """
  9552. App.log.debug("open_script()")
  9553. with self.proc_container.new(_("Opening TCL Script...")):
  9554. try:
  9555. with open(filename, "r") as opened_script:
  9556. script_content = opened_script.readlines()
  9557. script_content = ''.join(script_content)
  9558. if silent is False:
  9559. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  9560. except Exception as e:
  9561. log.debug("App.open_script() -> %s" % str(e))
  9562. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to open TCL Script."))
  9563. return
  9564. # Object name
  9565. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  9566. # New object creation and file processing
  9567. self.on_filenewscript(name=script_name, text=script_content)
  9568. # Register recent file
  9569. self.file_opened.emit("script", filename)
  9570. # GUI feedback
  9571. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  9572. def open_config_file(self, filename, run_from_arg=None):
  9573. """
  9574. Loads a config file from the specified file.
  9575. :param filename: Name of the file from which to load.
  9576. :type filename: str
  9577. :return: None
  9578. """
  9579. App.log.debug("Opening config file: " + filename)
  9580. if run_from_arg:
  9581. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  9582. "Canvas initialization finished in"), '%.2f' % self.used_time,
  9583. _("Opening FlatCAM Config file.")),
  9584. alignment=Qt.AlignBottom | Qt.AlignLeft,
  9585. color=QtGui.QColor("gray"))
  9586. # # add the tab if it was closed
  9587. # self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  9588. # # first clear previous text in text editor (if any)
  9589. # self.ui.text_editor_tab.code_editor.clear()
  9590. #
  9591. # # Switch plot_area to CNCJob tab
  9592. # self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  9593. # close the Code editor if already open
  9594. if self.toggle_codeeditor:
  9595. self.on_toggle_code_editor()
  9596. self.on_toggle_code_editor()
  9597. try:
  9598. if filename:
  9599. f = QtCore.QFile(filename)
  9600. if f.open(QtCore.QIODevice.ReadOnly):
  9601. stream = QtCore.QTextStream(f)
  9602. code_edited = stream.readAll()
  9603. self.text_editor_tab.code_editor.setPlainText(code_edited)
  9604. f.close()
  9605. except IOError:
  9606. App.log.error("Failed to open config file: %s" % filename)
  9607. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  9608. (_("Failed to open config file"), filename))
  9609. return
  9610. def open_project(self, filename, run_from_arg=None, plot=True, cli=None):
  9611. """
  9612. Loads a project from the specified file.
  9613. 1) Loads and parses file
  9614. 2) Registers the file as recently opened.
  9615. 3) Calls on_file_new()
  9616. 4) Updates options
  9617. 5) Calls new_object() with the object's from_dict() as init method.
  9618. 6) Calls plot_all() if plot=True
  9619. :param filename: Name of the file from which to load.
  9620. :type filename: str
  9621. :param run_from_arg: True if run for arguments
  9622. :param plot: If True plot all objects in the project
  9623. :param cli: run from command line
  9624. :return: None
  9625. """
  9626. App.log.debug("Opening project: " + filename)
  9627. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  9628. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  9629. if cli is None:
  9630. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  9631. if run_from_arg:
  9632. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  9633. "Canvas initialization finished in"), '%.2f' % self.used_time,
  9634. _("Opening FlatCAM Project file.")),
  9635. alignment=Qt.AlignBottom | Qt.AlignLeft,
  9636. color=QtGui.QColor("gray"))
  9637. # Open and parse an uncompressed Project file
  9638. try:
  9639. f = open(filename, 'r')
  9640. except IOError:
  9641. App.log.error("Failed to open project file: %s" % filename)
  9642. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  9643. (_("Failed to open project file"), filename))
  9644. return
  9645. try:
  9646. d = json.load(f, object_hook=dict2obj)
  9647. except Exception as e:
  9648. App.log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  9649. (filename, str(e)))
  9650. f.close()
  9651. # Open and parse a compressed Project file
  9652. try:
  9653. with lzma.open(filename) as f:
  9654. file_content = f.read().decode('utf-8')
  9655. d = json.loads(file_content, object_hook=dict2obj)
  9656. except Exception as e:
  9657. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  9658. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  9659. (_("Failed to open project file"), filename))
  9660. return
  9661. # Clear the current project
  9662. # # NOT THREAD SAFE # ##
  9663. if run_from_arg is True:
  9664. pass
  9665. elif cli is True:
  9666. self.delete_selection_shape()
  9667. else:
  9668. self.on_file_new()
  9669. # Project options
  9670. self.options.update(d['options'])
  9671. self.project_filename = filename
  9672. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  9673. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  9674. if cli is None:
  9675. self.set_screen_units(self.options["units"])
  9676. # Re create objects
  9677. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  9678. for obj in d['objs']:
  9679. try:
  9680. def obj_init(obj_inst, app_inst):
  9681. obj_inst.from_dict(obj)
  9682. App.log.debug("Recreating from opened project an %s object: %s" %
  9683. (obj['kind'].capitalize(), obj['options']['name']))
  9684. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  9685. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  9686. if cli is None:
  9687. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  9688. obj['kind'].upper(),
  9689. obj['options']['name']
  9690. )
  9691. )
  9692. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=plot)
  9693. except Exception as e:
  9694. print('App.open_project() --> ' + str(e))
  9695. self.inform.emit('[success] %s: %s' % (_("Project loaded from"), filename))
  9696. self.should_we_save = False
  9697. self.file_opened.emit("project", filename)
  9698. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  9699. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  9700. if cli is None:
  9701. self.set_ui_title(name=self.project_filename)
  9702. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  9703. def propagate_defaults(self, silent=False):
  9704. """
  9705. This method is used to set default values in classes. It's
  9706. an alternative to project options but allows the use
  9707. of values invisible to the user.
  9708. :return: None
  9709. """
  9710. if silent is False:
  9711. self.log.debug("propagate_defaults()")
  9712. # Which objects to update the given parameters.
  9713. routes = {
  9714. "global_zdownrate": CNCjob,
  9715. "excellon_zeros": Excellon,
  9716. "excellon_format_upper_in": Excellon,
  9717. "excellon_format_lower_in": Excellon,
  9718. "excellon_format_upper_mm": Excellon,
  9719. "excellon_format_lower_mm": Excellon,
  9720. "excellon_units": Excellon,
  9721. "gerber_use_buffer_for_union": Gerber,
  9722. "geometry_multidepth": Geometry
  9723. }
  9724. for param in routes:
  9725. if param in routes[param].defaults:
  9726. try:
  9727. routes[param].defaults[param] = self.defaults[param]
  9728. if silent is False:
  9729. self.log.debug(" " + param + " OK")
  9730. except KeyError:
  9731. if silent is False:
  9732. self.log.debug("FlatCAMApp.propagate_defaults() --> ERROR: " + param + " not in defaults.")
  9733. else:
  9734. # Try extracting the name:
  9735. # classname_param here is param in the object
  9736. if param.find(routes[param].__name__.lower() + "_") == 0:
  9737. p = param[len(routes[param].__name__) + 1:]
  9738. if p in routes[param].defaults:
  9739. routes[param].defaults[p] = self.defaults[param]
  9740. if silent is False:
  9741. self.log.debug(" " + param + " OK!")
  9742. def plot_all(self, zoom=True):
  9743. """
  9744. Re-generates all plots from all objects.
  9745. :return: None
  9746. """
  9747. self.log.debug("Plot_all()")
  9748. self.inform.emit('[success] %s...' % _("Redrawing all objects"))
  9749. for obj in self.collection.get_list():
  9750. def worker_task(obj):
  9751. with self.proc_container.new("Plotting"):
  9752. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  9753. if zoom:
  9754. self.object_plotted.emit(obj)
  9755. # Send to worker
  9756. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  9757. def register_folder(self, filename):
  9758. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  9759. def register_save_folder(self, filename):
  9760. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  9761. def set_progress_bar(self, percentage, text=""):
  9762. self.ui.progress_bar.setValue(int(percentage))
  9763. def setup_shell(self):
  9764. """
  9765. Creates shell functions. Runs once at startup.
  9766. :return: None
  9767. """
  9768. self.log.debug("setup_shell()")
  9769. def shelp(p=None):
  9770. if not p:
  9771. return _("Available commands:\n") + \
  9772. '\n'.join([' ' + cmd for cmd in sorted(commands)]) + \
  9773. _("\n\nType help <command_name> for usage.\n Example: help open_gerber")
  9774. if p not in commands:
  9775. return "Unknown command: %s" % p
  9776. return commands[p]["help"]
  9777. # --- Migrated to new architecture ---
  9778. # def options(name):
  9779. # ops = self.collection.get_by_name(str(name)).options
  9780. # return '\n'.join(["%s: %s" % (o, ops[o]) for o in ops])
  9781. def h(*args):
  9782. """
  9783. Pre-processes arguments to detect '-keyword value' pairs into dictionary
  9784. and standalone parameters into list.
  9785. """
  9786. kwa = {}
  9787. a = []
  9788. n = len(args)
  9789. name = None
  9790. for i in range(n):
  9791. match = re.search(r'^-([a-zA-Z].*)', args[i])
  9792. if match:
  9793. assert name is None
  9794. name = match.group(1)
  9795. continue
  9796. if name is None:
  9797. a.append(args[i])
  9798. else:
  9799. kwa[name] = args[i]
  9800. name = None
  9801. return a, kwa
  9802. @contextmanager
  9803. def wait_signal(signal, timeout=10000):
  9804. """
  9805. Block loop until signal emitted, timeout (ms) elapses
  9806. or unhandled exception happens in a thread.
  9807. :param timeout: time after which the loop is exited
  9808. :param signal: Signal to wait for.
  9809. """
  9810. loop = QtCore.QEventLoop()
  9811. # Normal termination
  9812. signal.connect(loop.quit)
  9813. # Termination by exception in thread
  9814. self.thread_exception.connect(loop.quit)
  9815. status = {'timed_out': False}
  9816. def report_quit():
  9817. status['timed_out'] = True
  9818. loop.quit()
  9819. yield
  9820. # Temporarily change how exceptions are managed.
  9821. oeh = sys.excepthook
  9822. ex = []
  9823. def except_hook(type_, value, traceback_):
  9824. ex.append(value)
  9825. oeh(type_, value, traceback_)
  9826. sys.excepthook = except_hook
  9827. # Terminate on timeout
  9828. if timeout is not None:
  9829. QtCore.QTimer.singleShot(timeout, report_quit)
  9830. # # ## Block ## ##
  9831. loop.exec_()
  9832. # Restore exception management
  9833. sys.excepthook = oeh
  9834. if ex:
  9835. self.raiseTclError(str(ex[0]))
  9836. if status['timed_out']:
  9837. raise Exception('Timed out!')
  9838. def make_docs():
  9839. output = ''
  9840. import collections
  9841. od = collections.OrderedDict(sorted(commands.items()))
  9842. for cmd_, val in od.items():
  9843. output += cmd_ + ' \n' + ''.join(['~'] * len(cmd_)) + '\n'
  9844. t = val['help']
  9845. usage_i = t.find('>')
  9846. if usage_i < 0:
  9847. expl = t
  9848. output += expl + '\n\n'
  9849. continue
  9850. expl = t[:usage_i - 1]
  9851. output += expl + '\n\n'
  9852. end_usage_i = t[usage_i:].find('\n')
  9853. if end_usage_i < 0:
  9854. end_usage_i = len(t[usage_i:])
  9855. output += ' ' + t[usage_i:] + '\n No parameters.\n'
  9856. else:
  9857. extras = t[usage_i+end_usage_i+1:]
  9858. parts = [s.strip() for s in extras.split('\n')]
  9859. output += ' ' + t[usage_i:usage_i+end_usage_i] + '\n'
  9860. for p in parts:
  9861. output += ' ' + p + '\n\n'
  9862. return output
  9863. '''
  9864. Howto implement TCL shell commands:
  9865. All parameters passed to command should be possible to set as None and test it afterwards.
  9866. This is because we need to see error caused in tcl,
  9867. if None value as default parameter is not allowed TCL will return empty error.
  9868. Use:
  9869. def mycommand(name=None,...):
  9870. Test it like this:
  9871. if name is None:
  9872. self.raise_tcl_error('Argument name is missing.')
  9873. When error ocurre, always use raise_tcl_error, never return "sometext" on error,
  9874. otherwise we will miss it and processing will silently continue.
  9875. Method raise_tcl_error pass error into TCL interpreter, then raise python exception,
  9876. which is catched in exec_command and displayed in TCL shell console with red background.
  9877. Error in console is displayed with TCL trace.
  9878. This behavior works only within main thread,
  9879. errors with promissed tasks can be catched and detected only with log.
  9880. TODO: this problem have to be addressed somehow, maybe rewrite promissing to be blocking somehow for
  9881. TCL shell.
  9882. Kamil's comment: I will rewrite existing TCL commands from time to time to follow this rules.
  9883. '''
  9884. commands = {
  9885. 'help': {
  9886. 'fcn': shelp,
  9887. 'help': _("Shows list of commands.")
  9888. },
  9889. }
  9890. # Import/overwrite tcl commands as objects of TclCommand descendants
  9891. # This modifies the variable 'commands'.
  9892. tclCommands.register_all_commands(self, commands)
  9893. # Add commands to the tcl interpreter
  9894. for cmd in commands:
  9895. self.tcl.createcommand(cmd, commands[cmd]['fcn'])
  9896. # Make the tcl puts function return instead of print to stdout
  9897. self.tcl.eval('''
  9898. rename puts original_puts
  9899. proc puts {args} {
  9900. if {[llength $args] == 1} {
  9901. return "[lindex $args 0]"
  9902. } else {
  9903. eval original_puts $args
  9904. }
  9905. }
  9906. ''')
  9907. def setup_recent_items(self):
  9908. # TODO: Move this to constructor
  9909. icons = {
  9910. "gerber": self.resource_location + "/flatcam_icon16.png",
  9911. "excellon": self.resource_location + "/drill16.png",
  9912. 'geometry': self.resource_location + "/geometry16.png",
  9913. "cncjob": self.resource_location + "/cnc16.png",
  9914. "script": self.resource_location + "/script_new24.png",
  9915. "document": self.resource_location + "/notes16_1.png",
  9916. "project": self.resource_location + "/project16.png",
  9917. "svg": self.resource_location + "/geometry16.png",
  9918. "dxf": self.resource_location + "/dxf16.png",
  9919. "pdf": self.resource_location + "/pdf32.png",
  9920. "image": self.resource_location + "/image16.png"
  9921. }
  9922. try:
  9923. image_opener = self.image_tool.import_image
  9924. except AttributeError:
  9925. image_opener = None
  9926. openers = {
  9927. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  9928. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  9929. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  9930. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  9931. "script": lambda fname: self.worker_task.emit({'fcn': self.open_script, 'params': [fname]}),
  9932. "document": None,
  9933. 'project': self.open_project,
  9934. 'svg': self.import_svg,
  9935. 'dxf': self.import_dxf,
  9936. 'image': image_opener,
  9937. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  9938. }
  9939. # Open recent file for files
  9940. try:
  9941. f = open(self.data_path + '/recent.json')
  9942. except IOError:
  9943. App.log.error("Failed to load recent item list.")
  9944. self.inform.emit('[ERROR_NOTCL] %s' %
  9945. _("Failed to load recent item list."))
  9946. return
  9947. try:
  9948. self.recent = json.load(f)
  9949. except json.scanner.JSONDecodeError:
  9950. App.log.error("Failed to parse recent item list.")
  9951. self.inform.emit('[ERROR_NOTCL] %s' %
  9952. _("Failed to parse recent item list."))
  9953. f.close()
  9954. return
  9955. f.close()
  9956. # Open recent file for projects
  9957. try:
  9958. fp = open(self.data_path + '/recent_projects.json')
  9959. except IOError:
  9960. App.log.error("Failed to load recent project item list.")
  9961. self.inform.emit('[ERROR_NOTCL] %s' %
  9962. _("Failed to load recent projects item list."))
  9963. return
  9964. try:
  9965. self.recent_projects = json.load(fp)
  9966. except json.scanner.JSONDecodeError:
  9967. App.log.error("Failed to parse recent project item list.")
  9968. self.inform.emit('[ERROR_NOTCL] %s' %
  9969. _("Failed to parse recent project item list."))
  9970. fp.close()
  9971. return
  9972. fp.close()
  9973. # Closure needed to create callbacks in a loop.
  9974. # Otherwise late binding occurs.
  9975. def make_callback(func, fname):
  9976. def opener():
  9977. func(fname)
  9978. return opener
  9979. def reset_recent_files():
  9980. # Reset menu
  9981. self.ui.recent.clear()
  9982. self.recent = []
  9983. try:
  9984. ff = open(self.data_path + '/recent.json', 'w')
  9985. except IOError:
  9986. App.log.error("Failed to open recent items file for writing.")
  9987. return
  9988. json.dump(self.recent, ff)
  9989. def reset_recent_projects():
  9990. # Reset menu
  9991. self.ui.recent_projects.clear()
  9992. self.recent_projects = []
  9993. try:
  9994. fp = open(self.data_path + '/recent_projects.json', 'w')
  9995. except IOError:
  9996. App.log.error("Failed to open recent projects items file for writing.")
  9997. return
  9998. json.dump(self.recent, fp)
  9999. # Reset menu
  10000. self.ui.recent.clear()
  10001. self.ui.recent_projects.clear()
  10002. # Create menu items for projects
  10003. for recent in self.recent_projects:
  10004. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  10005. if recent['kind'] == 'project':
  10006. try:
  10007. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  10008. # Attach callback
  10009. o = make_callback(openers[recent["kind"]], recent['filename'])
  10010. action.triggered.connect(o)
  10011. self.ui.recent_projects.addAction(action)
  10012. except KeyError:
  10013. App.log.error("Unsupported file type: %s" % recent["kind"])
  10014. # Last action in Recent Files menu is one that Clear the content
  10015. clear_action_proj = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  10016. (_("Clear Recent projects")), self)
  10017. clear_action_proj.triggered.connect(reset_recent_projects)
  10018. self.ui.recent_projects.addSeparator()
  10019. self.ui.recent_projects.addAction(clear_action_proj)
  10020. # Create menu items for files
  10021. for recent in self.recent:
  10022. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  10023. if recent['kind'] != 'project':
  10024. try:
  10025. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  10026. # Attach callback
  10027. o = make_callback(openers[recent["kind"]], recent['filename'])
  10028. action.triggered.connect(o)
  10029. self.ui.recent.addAction(action)
  10030. except KeyError:
  10031. App.log.error("Unsupported file type: %s" % recent["kind"])
  10032. # Last action in Recent Files menu is one that Clear the content
  10033. clear_action = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  10034. (_("Clear Recent files")), self)
  10035. clear_action.triggered.connect(reset_recent_files)
  10036. self.ui.recent.addSeparator()
  10037. self.ui.recent.addAction(clear_action)
  10038. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  10039. # self.ui.menufilerecent.set_submenu(recent_menu)
  10040. # recent_menu.show_all()
  10041. # self.ui.recent.show()
  10042. self.log.debug("Recent items list has been populated.")
  10043. def setup_component_editor(self):
  10044. # label = QtWidgets.QLabel("Choose an item from Project")
  10045. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  10046. sel_title = QtWidgets.QTextEdit(
  10047. _('<b>Shortcut Key List</b>'))
  10048. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  10049. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  10050. settings = QSettings("Open Source", "FlatCAM")
  10051. if settings.contains("notebook_font_size"):
  10052. fsize = settings.value('notebook_font_size', type=int)
  10053. else:
  10054. fsize = 12
  10055. tsize = fsize + int(fsize / 2)
  10056. # selected_text = (_('''
  10057. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span></p>
  10058. #
  10059. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  10060. # The normal flow when working in FlatCAM is the following:</span></p>
  10061. #
  10062. # <ol>
  10063. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into
  10064. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  10065. # even dragging and dropping the files on the GUI.<br />
  10066. # <br />
  10067. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp; drop of the
  10068. # file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  10069. # &nbsp;</li>
  10070. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it and then
  10071. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  10072. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  10073. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  10074. # <br />
  10075. # If the selection of the object is done on the canvas by single click instead, and the <strong>SELECTED TAB</strong>
  10076. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  10077. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  10078. # it even if it was out of focus.<br />
  10079. # <br />
  10080. # You can change the parameters in this screen and the flow direction is like this:<br />
  10081. # <br />
  10082. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;<strong> Geometry Object
  10083. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  10084. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  10085. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  10086. # </ol>
  10087. #
  10088. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  10089. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  10090. # <strong>F3</strong>.</span></p>
  10091. #
  10092. # ''').format(fsize=fsize, tsize=tsize))
  10093. selected_text = '''
  10094. <p><span style="font-size:{tsize}px"><strong>{title}</strong></span></p>
  10095. <p><span style="font-size:{fsize}px"><strong>{subtitle}</strong>:<br />
  10096. {s1}</span></p>
  10097. <ol>
  10098. <li><span style="font-size:{fsize}px">{s2}<br />
  10099. <br />
  10100. {s3}</span><br />
  10101. &nbsp;</li>
  10102. <li><span style="font-size:{fsize}px">{s4}<br />
  10103. &nbsp;</li>
  10104. <br />
  10105. <li><span style="font-size:{fsize}px">{s5}<br />
  10106. &nbsp;</li>
  10107. <br />
  10108. <li><span style="font-size:{fsize}px">{s6}<br />
  10109. <br />
  10110. {s7}</span></li>
  10111. </ol>
  10112. <p><span style="font-size:{fsize}px">{s8}</span></p>
  10113. '''.format(
  10114. title=_("Selected Tab - Choose an Item from Project Tab"),
  10115. subtitle=_("Details"),
  10116. s1=_("The normal flow when working in FlatCAM is the following:"),
  10117. s2=_("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM "
  10118. "using either the toolbars, key shortcuts or even dragging and dropping the "
  10119. "files on the GUI."),
  10120. s3=_("You can also load a FlatCAM project by double clicking on the project file, "
  10121. "drag and drop of the file into the FLATCAM GUI or through the menu (or toolbar) "
  10122. "actions offered within the app."),
  10123. s4=_("Once an object is available in the Project Tab, by selecting it and then focusing "
  10124. "on SELECTED TAB (more simpler is to double click the object name in the Project Tab, "
  10125. "SELECTED TAB will be updated with the object properties according to its kind: "
  10126. "Gerber, Excellon, Geometry or CNCJob object."),
  10127. s5=_("If the selection of the object is done on the canvas by single click instead, "
  10128. "and the SELECTED TAB is in focus, again the object properties will be displayed into the "
  10129. "Selected Tab. Alternatively, double clicking on the object on the canvas will bring "
  10130. "the SELECTED TAB and populate it even if it was out of focus."),
  10131. s6=_("You can change the parameters in this screen and the flow direction is like this:"),
  10132. s7=_("Gerber/Excellon Object --> Change Parameter --> Generate Geometry --> Geometry Object --> "
  10133. "Add tools (change param in Selected Tab) --> Generate CNCJob --> CNCJob Object --> "
  10134. "Verify GCode (through Edit CNC Code) and/or append/prepend to GCode "
  10135. "(again, done in SELECTED TAB) --> Save GCode."),
  10136. s8=_("A list of key shortcuts is available through an menu entry in Help --> Shortcuts List "
  10137. "or through its own key shortcut: <b>F3</b>."),
  10138. tsize=tsize,
  10139. fsize=fsize
  10140. )
  10141. sel_title.setText(selected_text)
  10142. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  10143. self.ui.selected_scroll_area.setWidget(sel_title)
  10144. def setup_obj_classes(self):
  10145. """
  10146. Sets up application specifics on the FlatCAMObj class.
  10147. :return: None
  10148. """
  10149. FlatCAMObj.app = self
  10150. ObjectCollection.app = self
  10151. Gerber.app = self
  10152. Excellon.app = self
  10153. Geometry.app = self
  10154. CNCjob.app = self
  10155. FCProcess.app = self
  10156. FCProcessContainer.app = self
  10157. OptionsGroupUI.app = self
  10158. def version_check(self):
  10159. """
  10160. Checks for the latest version of the program. Alerts the
  10161. user if theirs is outdated. This method is meant to be run
  10162. in a separate thread.
  10163. :return: None
  10164. """
  10165. self.log.debug("version_check()")
  10166. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  10167. full_url = App.version_url + \
  10168. "?s=" + str(self.defaults['global_serial']) + \
  10169. "&v=" + str(self.version) + \
  10170. "&os=" + str(self.os) + \
  10171. "&" + urllib.parse.urlencode(self.defaults["global_stats"])
  10172. else:
  10173. # no_stats dict; just so it won't break things on website
  10174. no_ststs_dict = {}
  10175. no_ststs_dict["global_ststs"] = {}
  10176. full_url = App.version_url + \
  10177. "?s=" + str(self.defaults['global_serial']) + \
  10178. "&v=" + str(self.version) + \
  10179. "&os=" + str(self.os) + \
  10180. "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  10181. App.log.debug("Checking for updates @ %s" % full_url)
  10182. # ## Get the data
  10183. try:
  10184. f = urllib.request.urlopen(full_url)
  10185. except Exception:
  10186. # App.log.warning("Failed checking for latest version. Could not connect.")
  10187. self.log.warning("Failed checking for latest version. Could not connect.")
  10188. self.inform.emit('[WARNING_NOTCL] %s' %
  10189. _("Failed checking for latest version. Could not connect."))
  10190. return
  10191. try:
  10192. data = json.load(f)
  10193. except Exception as e:
  10194. App.log.error("Could not parse information about latest version.")
  10195. self.inform.emit('[ERROR_NOTCL] %s' %
  10196. _("Could not parse information about latest version."))
  10197. App.log.debug("json.load(): %s" % str(e))
  10198. f.close()
  10199. return
  10200. f.close()
  10201. # ## Latest version?
  10202. if self.version >= data["version"]:
  10203. App.log.debug("FlatCAM is up to date!")
  10204. self.inform.emit('[success] %s' %
  10205. _("FlatCAM is up to date!"))
  10206. return
  10207. App.log.debug("Newer version available.")
  10208. self.message.emit(
  10209. _("Newer Version Available"),
  10210. _("There is a newer version of FlatCAM available for download:\n\n") +
  10211. "<b>%s</b>" % str(data["name"]) + "\n%s" % str(data["message"]),
  10212. _("info")
  10213. )
  10214. def on_plotcanvas_setup(self, container=None):
  10215. """
  10216. This is doing the setup for the plot area (canvas)
  10217. :param container: widget where to install the canvas
  10218. :return: None
  10219. """
  10220. if container:
  10221. plot_container = container
  10222. else:
  10223. plot_container = self.ui.right_layout
  10224. modifier = QtWidgets.QApplication.queryKeyboardModifiers()
  10225. if self.is_legacy is True or modifier == QtCore.Qt.ControlModifier:
  10226. self.is_legacy = True
  10227. self.defaults["global_graphic_engine"] = "2D"
  10228. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  10229. else:
  10230. try:
  10231. self.plotcanvas = PlotCanvas(plot_container, self)
  10232. except Exception as er:
  10233. msg_txt = traceback.format_exc()
  10234. log.debug("App.on_plotcanvas_setup() failed -> %s" % str(er))
  10235. log.debug("OpenGL canvas initialization failed with the following error.\n" + msg_txt)
  10236. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  10237. msg += _("OpenGL canvas initialization failed. HW or HW configuration not supported."
  10238. "Change the graphic engine to Legacy(2D) in Edit -> Preferences -> General tab.\n\n")
  10239. msg += msg_txt
  10240. self.inform.emit(msg)
  10241. return 'fail'
  10242. # So it can receive key presses
  10243. self.plotcanvas.native.setFocus()
  10244. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  10245. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  10246. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  10247. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_mouse_double_click_over_plot)
  10248. # Keys over plot enabled
  10249. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  10250. if self.defaults['global_cursor_type'] == 'small':
  10251. self.app_cursor = self.plotcanvas.new_cursor()
  10252. else:
  10253. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  10254. if self.ui.grid_snap_btn.isChecked():
  10255. self.app_cursor.enabled = True
  10256. else:
  10257. self.app_cursor.enabled = False
  10258. if self.is_legacy is False:
  10259. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  10260. else:
  10261. # will use the default Matplotlib axes
  10262. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  10263. def on_zoom_fit(self, event):
  10264. """
  10265. Callback for zoom-out request. This can be either from the corresponding
  10266. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  10267. with axes limits from the geometry bounds of all objects.
  10268. :param event: Ignored.
  10269. :return: None
  10270. """
  10271. if self.is_legacy is False:
  10272. self.plotcanvas.fit_view()
  10273. else:
  10274. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  10275. width = xmax - xmin
  10276. height = ymax - ymin
  10277. xmin -= 0.05 * width
  10278. xmax += 0.05 * width
  10279. ymin -= 0.05 * height
  10280. ymax += 0.05 * height
  10281. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  10282. def on_zoom_in(self):
  10283. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  10284. def on_zoom_out(self):
  10285. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  10286. def disable_all_plots(self):
  10287. self.report_usage("disable_all_plots()")
  10288. self.disable_plots(self.collection.get_list())
  10289. self.inform.emit('[success] %s' %
  10290. _("All plots disabled."))
  10291. def disable_other_plots(self):
  10292. self.report_usage("disable_other_plots()")
  10293. self.disable_plots(self.collection.get_non_selected())
  10294. self.inform.emit('[success] %s' %
  10295. _("All non selected plots disabled."))
  10296. def enable_all_plots(self):
  10297. self.report_usage("enable_all_plots()")
  10298. self.enable_plots(self.collection.get_list())
  10299. self.inform.emit('[success] %s' %
  10300. _("All plots enabled."))
  10301. def on_enable_sel_plots(self):
  10302. log.debug("App.on_enable_sel_plot()")
  10303. object_list = self.collection.get_selected()
  10304. self.enable_plots(objects=object_list)
  10305. self.inform.emit('[success] %s' % _("Selected plots enabled..."))
  10306. def on_disable_sel_plots(self):
  10307. log.debug("App.on_disable_sel_plot()")
  10308. # self.inform.emit(_("Disabling plots ..."))
  10309. object_list = self.collection.get_selected()
  10310. self.disable_plots(objects=object_list)
  10311. self.inform.emit('[success] %s' % _("Selected plots disabled..."))
  10312. def enable_plots(self, objects):
  10313. """
  10314. Disables plots
  10315. :param objects: list of Objects to be enabled
  10316. :return:
  10317. """
  10318. log.debug("Enabling plots ...")
  10319. # self.inform.emit(_("Working ..."))
  10320. for obj in objects:
  10321. if obj.options['plot'] is False:
  10322. obj.options.set_change_callback(lambda x: None)
  10323. obj.options['plot'] = True
  10324. try:
  10325. # only the Gerber obj has on_plot_cb_click() method
  10326. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  10327. # disable this cb while disconnected,
  10328. # in case the operation takes time the user is not allowed to change it
  10329. obj.ui.plot_cb.setDisabled(True)
  10330. except AttributeError:
  10331. pass
  10332. obj.set_form_item("plot")
  10333. try:
  10334. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  10335. obj.ui.plot_cb.setDisabled(False)
  10336. except AttributeError:
  10337. pass
  10338. obj.options.set_change_callback(obj.on_options_change)
  10339. def worker_task(objs):
  10340. with self.proc_container.new(_("Enabling plots ...")):
  10341. for obj in objs:
  10342. # obj.options['plot'] = True
  10343. if isinstance(obj, FlatCAMCNCjob):
  10344. obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  10345. else:
  10346. obj.plot(visible=True)
  10347. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  10348. # self.plots_updated.emit()
  10349. def disable_plots(self, objects):
  10350. """
  10351. Disables plots
  10352. :param objects: list of Objects to be disabled
  10353. :return:
  10354. """
  10355. # if no objects selected then do nothing
  10356. if not self.collection.get_selected():
  10357. return
  10358. log.debug("Disabling plots ...")
  10359. # self.inform.emit(_("Working ..."))
  10360. for obj in objects:
  10361. if obj.options['plot'] is True:
  10362. obj.options.set_change_callback(lambda x: None)
  10363. obj.options['plot'] = False
  10364. try:
  10365. # only the Gerber obj has on_plot_cb_click() method
  10366. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  10367. obj.ui.plot_cb.setDisabled(True)
  10368. except AttributeError:
  10369. pass
  10370. obj.set_form_item("plot")
  10371. try:
  10372. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  10373. obj.ui.plot_cb.setDisabled(False)
  10374. except AttributeError:
  10375. pass
  10376. obj.options.set_change_callback(obj.on_options_change)
  10377. try:
  10378. self.delete_selection_shape()
  10379. except Exception as e:
  10380. log.debug("App.disable_plots() --> %s" % str(e))
  10381. # self.plots_updated.emit()
  10382. def worker_task(objs):
  10383. with self.proc_container.new(_("Disabling plots ...")):
  10384. for obj in objs:
  10385. # obj.options['plot'] = True
  10386. if isinstance(obj, FlatCAMCNCjob):
  10387. obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  10388. else:
  10389. obj.plot(visible=False)
  10390. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  10391. def toggle_plots(self, objects):
  10392. """
  10393. Toggle plots visibility
  10394. :param objects: list of Objects for which to be toggled the visibility
  10395. :return:
  10396. """
  10397. # if no objects selected then do nothing
  10398. if not self.collection.get_selected():
  10399. return
  10400. log.debug("Toggling plots ...")
  10401. self.inform.emit(_("Working ..."))
  10402. for obj in objects:
  10403. if obj.options['plot'] is False:
  10404. obj.options['plot'] = True
  10405. else:
  10406. obj.options['plot'] = False
  10407. self.plots_updated.emit()
  10408. def clear_plots(self):
  10409. objects = self.collection.get_list()
  10410. for obj in objects:
  10411. obj.clear(obj == objects[-1])
  10412. # Clear pool to free memory
  10413. self.clear_pool()
  10414. def on_set_color_action_triggered(self):
  10415. new_color = self.defaults['gerber_plot_fill']
  10416. act_name = self.sender().text()
  10417. sel_obj_list = self.collection.get_selected()
  10418. if not sel_obj_list:
  10419. return
  10420. # a default value, I just chose this one
  10421. alpha_level = 'BF'
  10422. for sel_obj in sel_obj_list:
  10423. if sel_obj.kind == 'excellon':
  10424. alpha_level = str(hex(
  10425. self.ui.excellon_defaults_form.excellon_gen_group.color_alpha_slider.value())[2:])
  10426. elif sel_obj.kind == 'gerber':
  10427. alpha_level = str(hex(self.ui.gerber_defaults_form.gerber_gen_group.pf_color_alpha_slider.value())[2:])
  10428. elif sel_obj.kind == 'geometry':
  10429. alpha_level = 'FF'
  10430. else:
  10431. log.debug(
  10432. "App.on_set_color_action_triggered() --> Default alpfa for this object type not supported yet")
  10433. continue
  10434. sel_obj.alpha_level = alpha_level
  10435. if act_name == _('Red'):
  10436. new_color = '#FF0000' + alpha_level
  10437. if act_name == _('Blue'):
  10438. new_color = '#0000FF' + alpha_level
  10439. if act_name == _('Yellow'):
  10440. new_color = '#FFDF00' + alpha_level
  10441. if act_name == _('Green'):
  10442. new_color = '#00FF00' + alpha_level
  10443. if act_name == _('Purple'):
  10444. new_color = '#FF00FF' + alpha_level
  10445. if act_name == _('Brown'):
  10446. new_color = '#A52A2A' + alpha_level
  10447. if act_name == _('White'):
  10448. new_color = '#FFFFFF' + alpha_level
  10449. if act_name == _('Black'):
  10450. new_color = '#000000' + alpha_level
  10451. if act_name == _('Custom'):
  10452. new_color = QtGui.QColor(self.defaults['gerber_plot_fill'][:7])
  10453. c_dialog = QtWidgets.QColorDialog()
  10454. plot_fill_color = c_dialog.getColor(initial=new_color)
  10455. if plot_fill_color.isValid() is False:
  10456. return
  10457. new_color = str(plot_fill_color.name()) + alpha_level
  10458. if act_name == _("Default"):
  10459. for sel_obj in sel_obj_list:
  10460. if sel_obj.kind == 'excellon':
  10461. new_color = self.defaults['excellon_plot_fill']
  10462. new_line_color = self.defaults['excellon_plot_line']
  10463. elif sel_obj.kind == 'gerber':
  10464. new_color = self.defaults['gerber_plot_fill']
  10465. new_line_color = self.defaults['gerber_plot_line']
  10466. elif sel_obj.kind == 'geometry':
  10467. new_color = self.defaults['geometry_plot_line']
  10468. new_line_color = self.defaults['geometry_plot_line']
  10469. else:
  10470. log.debug(
  10471. "App.on_set_color_action_triggered() --> Default color for this object type not supported yet")
  10472. continue
  10473. sel_obj.fill_color = new_color
  10474. sel_obj.outline_color = new_line_color
  10475. sel_obj.shapes.redraw(
  10476. update_colors=(new_color, new_line_color)
  10477. )
  10478. return
  10479. if act_name == _("Transparency"):
  10480. alpha_level, ok_button = QtWidgets.QInputDialog.getInt(
  10481. self.ui, _("Set alpha level ..."), '%s:' % _("Value"), min=0, max=255, step=1, value=191)
  10482. if ok_button:
  10483. alpha_str = str(hex(alpha_level)[2:]) if alpha_level != 0 else '00'
  10484. for sel_obj in sel_obj_list:
  10485. sel_obj.fill_color = sel_obj.fill_color[:-2] + alpha_str
  10486. sel_obj.shapes.redraw(
  10487. update_colors=(sel_obj.fill_color, sel_obj.outline_color)
  10488. )
  10489. return
  10490. new_line_color = color_variant(new_color[:7], 0.7)
  10491. if act_name == _("White"):
  10492. new_line_color = color_variant("#dedede", 0.7)
  10493. for sel_obj in sel_obj_list:
  10494. sel_obj.fill_color = new_color
  10495. sel_obj.outline_color = new_line_color
  10496. sel_obj.shapes.redraw(
  10497. update_colors=(new_color, new_line_color)
  10498. )
  10499. def on_grid_snap_triggered(self, state):
  10500. if state:
  10501. self.ui.snap_infobar_label.setPixmap(QtGui.QPixmap(self.resource_location + '/snap_filled_16.png'))
  10502. else:
  10503. self.ui.snap_infobar_label.setPixmap(QtGui.QPixmap(self.resource_location + '/snap_16.png'))
  10504. def generate_cnc_job(self, objects):
  10505. self.report_usage("generate_cnc_job()")
  10506. # for obj in objects:
  10507. # obj.generatecncjob()
  10508. for obj in objects:
  10509. obj.on_generatecnc_button_click()
  10510. def save_project(self, filename, quit_action=False, silent=False):
  10511. """
  10512. Saves the current project to the specified file.
  10513. :param filename: Name of the file in which to save.
  10514. :type filename: str
  10515. :param quit_action: if the project saving will be followed by an app quit; boolean
  10516. :param silent: if True will not display status messages
  10517. :return: None
  10518. """
  10519. self.log.debug("save_project()")
  10520. self.save_in_progress = True
  10521. with self.proc_container.new(_("Saving FlatCAM Project")):
  10522. # Capture the latest changes
  10523. # Current object
  10524. try:
  10525. self.collection.get_active().read_form()
  10526. except Exception as e:
  10527. self.log.debug("save_project() --> There was no active object. Skipping read_form. %s" % str(e))
  10528. pass
  10529. # Serialize the whole project
  10530. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  10531. "options": self.options,
  10532. "version": self.version}
  10533. if self.defaults["global_save_compressed"] is True:
  10534. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  10535. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  10536. # # Write
  10537. f.write(g)
  10538. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  10539. else:
  10540. # Open file
  10541. try:
  10542. f = open(filename, 'w')
  10543. except IOError:
  10544. App.log.error("Failed to open file for saving: %s", filename)
  10545. self.inform.emit('[ERROR_NOTCL] %s' % _("The object is used by another application."))
  10546. return
  10547. # Write
  10548. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  10549. f.close()
  10550. # verification of the saved project
  10551. # Open and parse
  10552. try:
  10553. saved_f = open(filename, 'r')
  10554. except IOError:
  10555. if silent is False:
  10556. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  10557. (_("Failed to verify project file"), filename, _("Retry to save it.")))
  10558. return
  10559. try:
  10560. saved_d = json.load(saved_f, object_hook=dict2obj)
  10561. except Exception:
  10562. if silent is False:
  10563. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  10564. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  10565. f.close()
  10566. return
  10567. saved_f.close()
  10568. if silent is False:
  10569. if 'version' in saved_d:
  10570. self.inform.emit('[success] %s: %s' %
  10571. (_("Project saved to"), filename))
  10572. else:
  10573. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  10574. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  10575. tb_settings = QSettings("Open Source", "FlatCAM")
  10576. lock_state = self.ui.lock_action.isChecked()
  10577. tb_settings.setValue('toolbar_lock', lock_state)
  10578. # This will write the setting to the platform specific storage.
  10579. del tb_settings
  10580. # if quit:
  10581. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  10582. # t.start()
  10583. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  10584. def start_delayed_quit(self, delay, filename, should_quit=None):
  10585. """
  10586. :param delay: period of checking if project file size is more than zero; in seconds
  10587. :param filename: the name of the project file to be checked periodically for size more than zero
  10588. :param should_quit: if the task finished will be followed by an app quit; boolean
  10589. :return:
  10590. """
  10591. to_quit = should_quit
  10592. self.save_timer = QtCore.QTimer()
  10593. self.save_timer.setInterval(delay)
  10594. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  10595. self.save_timer.start()
  10596. def check_project_file_size(self, filename, should_quit=None):
  10597. """
  10598. :param filename: the name of the project file to be checked periodically for size more than zero
  10599. :param should_quit: will quit the app if True; boolean
  10600. :return:
  10601. """
  10602. try:
  10603. if os.stat(filename).st_size > 0:
  10604. self.save_in_progress = False
  10605. self.save_timer.stop()
  10606. if should_quit:
  10607. self.app_quit.emit()
  10608. except Exception:
  10609. traceback.print_exc()
  10610. def on_plotarea_tab_closed(self, tab_idx):
  10611. widget = self.ui.plot_tab_area.widget(tab_idx)
  10612. if widget is not None:
  10613. widget.deleteLater()
  10614. self.ui.plot_tab_area.removeTab(tab_idx)
  10615. def on_options_app2project(self):
  10616. """
  10617. Callback for Options->Transfer Options->App=>Project. Copies options
  10618. from application defaults to project defaults.
  10619. :return: None
  10620. """
  10621. self.report_usage("on_options_app2project")
  10622. self.defaults_read_form()
  10623. self.options.update(self.defaults)
  10624. # self.options_write_form()
  10625. class ArgsThread(QtCore.QObject):
  10626. open_signal = pyqtSignal(list)
  10627. start = pyqtSignal()
  10628. if sys.platform == 'win32':
  10629. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  10630. else:
  10631. address = ('/tmp/testipc', 'AF_UNIX')
  10632. def __init__(self):
  10633. super(ArgsThread, self).__init__()
  10634. self.listener = None
  10635. self.start.connect(self.run)
  10636. def my_loop(self, address):
  10637. try:
  10638. self.listener = Listener(*address)
  10639. while True:
  10640. conn = self.listener.accept()
  10641. self.serve(conn)
  10642. except socket.error:
  10643. conn = Client(*address)
  10644. conn.send(sys.argv)
  10645. conn.send('close')
  10646. # close the current instance only if there are args
  10647. if len(sys.argv) > 1:
  10648. try:
  10649. self.listener.close()
  10650. except Exception:
  10651. pass
  10652. sys.exit()
  10653. def serve(self, conn):
  10654. while True:
  10655. msg = conn.recv()
  10656. if msg == 'close':
  10657. break
  10658. self.open_signal.emit(msg)
  10659. conn.close()
  10660. # the decorator is a must; without it this technique will not work unless the start signal is connected
  10661. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  10662. @pyqtSlot()
  10663. def run(self):
  10664. self.my_loop(self.address)
  10665. class GracefulException(Exception):
  10666. # Graceful Exception raised when the user is requesting to cancel the current threaded task
  10667. def __init__(self):
  10668. super().__init__()
  10669. def __str__(self):
  10670. return '\n\n%s' % _("The user requested a graceful exit of the current task.")
  10671. # end of file