FlatCAMApp.py 481 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925
  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 getopt
  12. import random
  13. import simplejson as json
  14. import lzma
  15. import shutil
  16. from datetime import datetime
  17. import time
  18. import ctypes
  19. import traceback
  20. from shapely.geometry import Point, MultiPolygon
  21. from io import StringIO
  22. from reportlab.graphics import renderPDF
  23. from reportlab.pdfgen import canvas
  24. from reportlab.lib.units import inch, mm
  25. from reportlab.lib.pagesizes import landscape, portrait
  26. from svglib.svglib import svg2rlg
  27. import gc
  28. from xml.dom.minidom import parseString as parse_xml_string
  29. from multiprocessing.connection import Listener, Client
  30. from multiprocessing import Pool
  31. import socket
  32. # ####################################################################################################################
  33. # ################################### Imports part of FlatCAM #############################################
  34. # ####################################################################################################################
  35. # Diverse
  36. from FlatCAMCommon import LoudDict, color_variant
  37. from FlatCAMBookmark import BookmarkManager
  38. from FlatCAMDB import ToolsDB2
  39. from vispy.gloo.util import _screenshot
  40. from vispy.io import write_png
  41. # FlatCAM Objects
  42. from defaults import FlatCAMDefaults
  43. from flatcamObjects.ObjectCollection import *
  44. from flatcamObjects.FlatCAMObj import FlatCAMObj
  45. from flatcamObjects.FlatCAMCNCJob import CNCJobObject
  46. from flatcamObjects.FlatCAMDocument import DocumentObject
  47. from flatcamObjects.FlatCAMExcellon import ExcellonObject
  48. from flatcamObjects.FlatCAMGeometry import GeometryObject
  49. from flatcamObjects.FlatCAMGerber import GerberObject
  50. from flatcamObjects.FlatCAMScript import ScriptObject
  51. # FlatCAM Parsing files
  52. from flatcamParsers.ParseExcellon import Excellon
  53. from flatcamParsers.ParseGerber import Gerber
  54. from camlib import to_dict, dict2obj, ET, ParseError, Geometry, CNCjob
  55. # FlatCAM GUI
  56. from flatcamGUI.PlotCanvas import *
  57. from flatcamGUI.PlotCanvasLegacy import *
  58. from flatcamGUI.FlatCAMGUI import *
  59. from flatcamGUI.GUIElements import FCFileSaveDialog
  60. # FlatCAM Pre-processors
  61. from FlatCAMPostProc import load_preprocessors
  62. # FlatCAM Editors
  63. from flatcamEditors.FlatCAMGeoEditor import FlatCAMGeoEditor
  64. from flatcamEditors.FlatCAMExcEditor import FlatCAMExcEditor
  65. from flatcamEditors.FlatCAMGrbEditor import FlatCAMGrbEditor
  66. from flatcamEditors.FlatCAMTextEditor import TextEditor
  67. from flatcamParsers.ParseHPGL2 import HPGL2
  68. # FlatCAM Workers
  69. from FlatCAMProcess import *
  70. from FlatCAMWorkerStack import WorkerStack
  71. # FlatCAM Tools
  72. from flatcamTools import *
  73. # FlatCAM Translation
  74. import gettext
  75. import FlatCAMTranslation as fcTranslate
  76. import builtins
  77. if sys.platform == 'win32':
  78. import winreg
  79. fcTranslate.apply_language('strings')
  80. if '_' not in builtins.__dict__:
  81. _ = gettext.gettext
  82. class App(QtCore.QObject):
  83. """
  84. The main application class. The constructor starts the GUI.
  85. """
  86. # ###############################################################################################################
  87. # ########################################## App ################################################################
  88. # ###############################################################################################################
  89. # ###############################################################################################################
  90. # ######################################### LOGGING #############################################################
  91. # ###############################################################################################################
  92. log = logging.getLogger('base')
  93. log.setLevel(logging.DEBUG)
  94. # log.setLevel(logging.WARNING)
  95. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  96. handler = logging.StreamHandler()
  97. handler.setFormatter(formatter)
  98. log.addHandler(handler)
  99. # ###############################################################################################################
  100. # #################################### Get Cmd Line Options #####################################################
  101. # ###############################################################################################################
  102. cmd_line_shellfile = ''
  103. cmd_line_shellvar = ''
  104. cmd_line_headless = None
  105. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>\n" \
  106. "FlatCam.py --shellvar=<1,'C:\\path',23>\n" \
  107. "FlatCam.py --headless=1"
  108. try:
  109. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  110. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=",
  111. "shellvar=",
  112. "headless=",
  113. "multiprocessing-fork="])
  114. except getopt.GetoptError:
  115. print(cmd_line_help)
  116. sys.exit(2)
  117. for opt, arg in cmd_line_options:
  118. if opt == '-h':
  119. print(cmd_line_help)
  120. sys.exit()
  121. elif opt == '--shellfile':
  122. cmd_line_shellfile = arg
  123. elif opt == '--shellvar':
  124. cmd_line_shellvar = arg
  125. elif opt == '--headless':
  126. try:
  127. cmd_line_headless = eval(arg)
  128. except NameError:
  129. pass
  130. # ###############################################################################################################
  131. # ################################### Version and VERSION DATE ##################################################
  132. # ###############################################################################################################
  133. version = 8.992
  134. version_date = "2020/05/01"
  135. beta = True
  136. engine = '3D'
  137. # current date now
  138. date = str(datetime.today()).rpartition('.')[0]
  139. date = ''.join(c for c in date if c not in ':-')
  140. date = date.replace(' ', '_')
  141. # ###############################################################################################################
  142. # ############################################ URLS's ###########################################################
  143. # ###############################################################################################################
  144. # URL for update checks and statistics
  145. version_url = "http://flatcam.org/version"
  146. # App URL
  147. app_url = "http://flatcam.org"
  148. # Manual URL
  149. manual_url = "http://flatcam.org/manual/index.html"
  150. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  151. gerber_spec_url = "https://www.ucamco.com/files/downloads/file/81/The_Gerber_File_Format_specification." \
  152. "pdf?7ac957791daba2cdf4c2c913f67a43da"
  153. excellon_spec_url = "https://www.ucamco.com/files/downloads/file/305/the_xnc_file_format_specification.pdf"
  154. bug_report_url = "https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open"
  155. # this variable will hold the project status
  156. # if True it will mean that the project was modified and not saved
  157. should_we_save = False
  158. # flag is True if saving action has been triggered
  159. save_in_progress = False
  160. # ###############################################################################################################
  161. # ####################################### APP Signals ######################################################
  162. # ###############################################################################################################
  163. # Inform the user
  164. # Handled by:
  165. # * App.info() --> Print on the status bar
  166. inform = QtCore.pyqtSignal(str)
  167. app_quit = QtCore.pyqtSignal()
  168. # General purpose background task
  169. worker_task = QtCore.pyqtSignal(dict)
  170. # File opened
  171. # Handled by:
  172. # * register_folder()
  173. # * register_recent()
  174. # Note: Setting the parameters to unicode does not seem
  175. # to have an effect. Then are received as Qstring
  176. # anyway.
  177. # File type and filename
  178. file_opened = QtCore.pyqtSignal(str, str)
  179. # File type and filename
  180. file_saved = QtCore.pyqtSignal(str, str)
  181. # Percentage of progress
  182. progress = QtCore.pyqtSignal(int)
  183. plots_updated = QtCore.pyqtSignal()
  184. # Emitted by new_object() and passes the new object as argument, plot flag.
  185. # on_object_created() adds the object to the collection, plots on appropriate flag
  186. # and emits new_object_available.
  187. object_created = QtCore.pyqtSignal(object, bool, bool)
  188. # Emitted when a object has been changed (like scaled, mirrored)
  189. object_changed = QtCore.pyqtSignal(object)
  190. # Emitted after object has been plotted.
  191. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  192. object_plotted = QtCore.pyqtSignal(object)
  193. # Emitted when a new object has been added or deleted from/to the collection
  194. object_status_changed = QtCore.pyqtSignal(object, str, str)
  195. message = QtCore.pyqtSignal(str, str, str)
  196. # Emmited when shell command is finished(one command only)
  197. shell_command_finished = QtCore.pyqtSignal(object)
  198. # Emitted when multiprocess pool has been recreated
  199. pool_recreated = QtCore.pyqtSignal(object)
  200. # Emitted when an unhandled exception happens
  201. # in the worker task.
  202. thread_exception = QtCore.pyqtSignal(object)
  203. # used to signal that there are arguments for the app
  204. args_at_startup = QtCore.pyqtSignal(list)
  205. # a reusable signal to replot a list of objects
  206. # should be disconnected after use so it can be reused
  207. replot_signal = pyqtSignal(list)
  208. # signal emitted when jumping
  209. jump_signal = pyqtSignal(tuple)
  210. # signal emitted when jumping
  211. locate_signal = pyqtSignal(tuple, str)
  212. # close app signal
  213. close_app_signal = pyqtSignal()
  214. # will perform the cleanup operation after a Graceful Exit
  215. # usefull for the NCC Tool and Paint Tool where some progressive plotting might leave
  216. # graphic residues behind
  217. cleanup = pyqtSignal()
  218. def __init__(self, user_defaults=True):
  219. """
  220. Starts the application.
  221. :return: app
  222. :rtype: App
  223. """
  224. App.log.info("FlatCAM Starting...")
  225. self.main_thread = QtWidgets.QApplication.instance().thread()
  226. # ############################################################################################################
  227. # ################# Setup the listening thread for another instance launching with args ######################
  228. # ############################################################################################################
  229. if sys.platform == 'win32' or sys.platform == 'linux':
  230. # make sure the thread is stored by using a self. otherwise it's garbage collected
  231. self.th = QtCore.QThread()
  232. self.th.start(priority=QtCore.QThread.LowestPriority)
  233. self.new_launch = ArgsThread()
  234. self.new_launch.open_signal[list].connect(self.on_startup_args)
  235. self.new_launch.moveToThread(self.th)
  236. self.new_launch.start.emit()
  237. # ############################################################################################################
  238. # # ######################################## OS-specific #####################################################
  239. # ############################################################################################################
  240. portable = False
  241. # Folder for user settings.
  242. if sys.platform == 'win32':
  243. from win32comext.shell import shell, shellcon
  244. if platform.architecture()[0] == '32bit':
  245. App.log.debug("Win32!")
  246. else:
  247. App.log.debug("Win64!")
  248. # #######################################################################################################
  249. # ####### CONFIG FILE WITH PARAMETERS REGARDING PORTABILITY #############################################
  250. # #######################################################################################################
  251. config_file = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config\\configuration.txt'
  252. try:
  253. with open(config_file, 'r'):
  254. pass
  255. except FileNotFoundError:
  256. config_file = os.path.dirname(os.path.realpath(__file__)) + '\\config\\configuration.txt'
  257. try:
  258. with open(config_file, 'r') as f:
  259. try:
  260. for line in f:
  261. param = str(line).replace('\n', '').rpartition('=')
  262. if param[0] == 'portable':
  263. try:
  264. portable = eval(param[2])
  265. except NameError:
  266. portable = False
  267. if param[0] == 'headless':
  268. if param[2].lower() == 'true':
  269. self.cmd_line_headless = 1
  270. else:
  271. self.cmd_line_headless = None
  272. except Exception as e:
  273. log.debug('App.__init__() -->%s' % str(e))
  274. return
  275. except FileNotFoundError as e:
  276. log.debug(str(e))
  277. pass
  278. if portable is False:
  279. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + '\\FlatCAM'
  280. else:
  281. self.data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  282. self.os = 'windows'
  283. else: # Linux/Unix/MacOS
  284. self.data_path = os.path.expanduser('~') + '/.FlatCAM'
  285. self.os = 'unix'
  286. # ############################################################################################################
  287. # ################################# Setup folders and files ##################################################
  288. # ############################################################################################################
  289. if not os.path.exists(self.data_path):
  290. os.makedirs(self.data_path)
  291. App.log.debug('Created data folder: ' + self.data_path)
  292. os.makedirs(os.path.join(self.data_path, 'preprocessors'))
  293. App.log.debug('Created data preprocessors folder: ' + os.path.join(self.data_path, 'preprocessors'))
  294. self.preprocessorpaths = os.path.join(self.data_path, 'preprocessors')
  295. if not os.path.exists(self.preprocessorpaths):
  296. os.makedirs(self.preprocessorpaths)
  297. App.log.debug('Created preprocessors folder: ' + self.preprocessorpaths)
  298. # create geo_tools_db.FlatDB file if there is none
  299. try:
  300. f = open(self.data_path + '/geo_tools_db.FlatDB')
  301. f.close()
  302. except IOError:
  303. App.log.debug('Creating empty geo_tool_db.FlatDB')
  304. f = open(self.data_path + '/geo_tools_db.FlatDB', 'w')
  305. json.dump({}, f)
  306. f.close()
  307. # create current_defaults.FlatConfig file if there is none
  308. try:
  309. f = open(self.data_path + '/current_defaults.FlatConfig')
  310. f.close()
  311. except IOError:
  312. App.log.debug('Creating empty current_defaults.FlatConfig')
  313. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  314. json.dump({}, f)
  315. f.close()
  316. # Write factory_defaults.FlatConfig file to disk
  317. FlatCAMDefaults.save_factory_defaults(os.path.join(self.data_path, "factory_defaults.FlatConfig"))
  318. # create a recent files json file if there is none
  319. try:
  320. f = open(self.data_path + '/recent.json')
  321. f.close()
  322. except IOError:
  323. App.log.debug('Creating empty recent.json')
  324. f = open(self.data_path + '/recent.json', 'w')
  325. json.dump([], f)
  326. f.close()
  327. # create a recent projects json file if there is none
  328. try:
  329. fp = open(self.data_path + '/recent_projects.json')
  330. fp.close()
  331. except IOError:
  332. App.log.debug('Creating empty recent_projects.json')
  333. fp = open(self.data_path + '/recent_projects.json', 'w')
  334. json.dump([], fp)
  335. fp.close()
  336. # Application directory. CHDIR to it. Otherwise, trying to load
  337. # GUI icons will fail as their path is relative.
  338. # This will fail under cx_freeze ...
  339. self.app_home = os.path.dirname(os.path.realpath(__file__))
  340. App.log.debug("Application path is " + self.app_home)
  341. App.log.debug("Started in " + os.getcwd())
  342. # cx_freeze workaround
  343. if os.path.isfile(self.app_home):
  344. self.app_home = os.path.dirname(self.app_home)
  345. os.chdir(self.app_home)
  346. # ############################################################################################################
  347. # ################################# DEFAULTS - PREFERENCES STORAGE ###########################################
  348. # ############################################################################################################
  349. self.defaults = FlatCAMDefaults()
  350. current_defaults_path = os.path.join(self.data_path, "current_defaults.FlatConfig")
  351. if user_defaults:
  352. self.defaults.load(filename=current_defaults_path)
  353. if self.defaults["global_gray_icons"] is False:
  354. self.resource_location = 'share'
  355. else:
  356. self.resource_location = 'share/dark_resources'
  357. if self.defaults['units'] == 'MM':
  358. self.decimals = int(self.defaults['decimals_metric'])
  359. else:
  360. self.decimals = int(self.defaults['decimals_inch'])
  361. self.current_units = self.defaults['units']
  362. # ###########################################################################################################
  363. # #################################### SETUP OBJECT CLASSES #################################################
  364. # ###########################################################################################################
  365. self.setup_obj_classes()
  366. # ###########################################################################################################
  367. # ###################################### CREATE MULTIPROCESSING POOL #######################################
  368. # ###########################################################################################################
  369. self.pool = Pool()
  370. # ###########################################################################################################
  371. # ###################################### Setting the Splash Screen ##########################################
  372. # ###########################################################################################################
  373. splash_settings = QSettings("Open Source", "FlatCAM")
  374. if splash_settings.contains("splash_screen"):
  375. show_splash = splash_settings.value("splash_screen")
  376. else:
  377. splash_settings.setValue('splash_screen', 1)
  378. # This will write the setting to the platform specific storage.
  379. del splash_settings
  380. show_splash = 1
  381. if show_splash and self.cmd_line_headless != 1:
  382. splash_pix = QtGui.QPixmap(self.resource_location + '/splash.png')
  383. self.splash = QtWidgets.QSplashScreen(splash_pix, Qt.WindowStaysOnTopHint)
  384. # self.splash.setMask(splash_pix.mask())
  385. # move splashscreen to the current monitor
  386. desktop = QtWidgets.QApplication.desktop()
  387. screen = desktop.screenNumber(QtGui.QCursor.pos())
  388. current_screen_center = desktop.availableGeometry(screen).center()
  389. self.splash.move(current_screen_center - self.splash.rect().center())
  390. self.splash.show()
  391. self.splash.showMessage(_("FlatCAM is initializing ..."),
  392. alignment=Qt.AlignBottom | Qt.AlignLeft,
  393. color=QtGui.QColor("gray"))
  394. else:
  395. show_splash = 0
  396. # ###########################################################################################################
  397. # ######################################### Initialize GUI ##################################################
  398. # ###########################################################################################################
  399. # FlatCAM colors used in plotting
  400. self.FC_light_green = '#BBF268BF'
  401. self.FC_dark_green = '#006E20BF'
  402. self.FC_light_blue = '#a5a5ffbf'
  403. self.FC_dark_blue = '#0000ffbf'
  404. QtCore.QObject.__init__(self)
  405. self.ui = FlatCAMGUI(self)
  406. self.on_grid_snap_triggered(state=True)
  407. theme_settings = QtCore.QSettings("Open Source", "FlatCAM")
  408. if theme_settings.contains("theme"):
  409. theme = theme_settings.value('theme', type=str)
  410. else:
  411. theme = 'white'
  412. if self.defaults["global_cursor_color_enabled"]:
  413. self.cursor_color_3D = self.defaults["global_cursor_color"]
  414. else:
  415. if theme == 'white':
  416. self.cursor_color_3D = 'black'
  417. else:
  418. self.cursor_color_3D = 'gray'
  419. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  420. self.ui.final_save.connect(self.final_save)
  421. # restore the toolbar view
  422. self.restore_toolbar_view()
  423. # restore the GUI geometry
  424. self.restore_main_win_geom()
  425. # set FlatCAM units in the Status bar
  426. self.set_screen_units(self.defaults['units'])
  427. # ###########################################################################################################
  428. # ########################################### AUTOSAVE SETUP ################################################
  429. # ###########################################################################################################
  430. self.block_autosave = False
  431. self.autosave_timer = QtCore.QTimer(self)
  432. self.save_project_auto_update()
  433. self.autosave_timer.timeout.connect(self.save_project_auto)
  434. # ###########################################################################################################
  435. # ##################################### UPDATE PREFERENCES GUI FORMS ########################################
  436. # ###########################################################################################################
  437. self.preferencesUiManager = PreferencesUIManager(defaults=self.defaults, data_path=self.data_path, ui=self.ui, inform=self.inform)
  438. self.preferencesUiManager.defaults_write_form()
  439. # When the self.defaults dictionary changes will update the Preferences GUI forms
  440. self.defaults.set_change_callback(self.on_defaults_dict_change)
  441. # ###########################################################################################################
  442. # ##################################### FIRST RUN SECTION ###################################################
  443. # ################################ It's done only once after install #####################################
  444. # ###########################################################################################################
  445. if self.defaults["first_run"] is True:
  446. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  447. initial_lay = 'compact'
  448. self.ui.general_defaults_form.general_gui_group.on_layout(lay=initial_lay)
  449. # Set the combobox in Preferences to the current layout
  450. idx = self.ui.general_defaults_form.general_gui_group.layout_combo.findText(initial_lay)
  451. self.ui.general_defaults_form.general_gui_group.layout_combo.setCurrentIndex(idx)
  452. # after the first run, this object should be False
  453. self.defaults["first_run"] = False
  454. self.preferencesUiManager.save_defaults(silent=True)
  455. # ###########################################################################################################
  456. # ############################################ Data #########################################################
  457. # ###########################################################################################################
  458. self.recent = []
  459. self.recent_projects = []
  460. self.clipboard = QtWidgets.QApplication.clipboard()
  461. self.project_filename = None
  462. self.toggle_units_ignore = False
  463. # ###########################################################################################################
  464. # #################################### LOAD PREPROCESSORS ###################################################
  465. # ###########################################################################################################
  466. # a dictionary that have as keys the name of the preprocessor files and the value is the class from
  467. # the preprocessor file
  468. self.preprocessors = load_preprocessors(self)
  469. # make sure that always the 'default' preprocessor is the first item in the dictionary
  470. if 'default' in self.preprocessors.keys():
  471. new_ppp_dict = {}
  472. # add the 'default' name first in the dict after removing from the preprocessor's dictionary
  473. default_pp = self.preprocessors.pop('default')
  474. new_ppp_dict['default'] = default_pp
  475. # then add the rest of the keys
  476. for name, val_class in self.preprocessors.items():
  477. new_ppp_dict[name] = val_class
  478. # and now put back the ordered dict with 'default' key first
  479. self.preprocessors = new_ppp_dict
  480. for name in list(self.preprocessors.keys()):
  481. # 'Paste' preprocessors are to be used only in the Solder Paste Dispensing Tool
  482. if name.partition('_')[0] == 'Paste':
  483. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  484. continue
  485. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  486. # HPGL preprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  487. if name == 'hpgl':
  488. continue
  489. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  490. # ###########################################################################################################
  491. # ########################################## LOAD LANGUAGES ################################################
  492. # ###########################################################################################################
  493. self.languages = fcTranslate.load_languages()
  494. for name in sorted(self.languages.values()):
  495. self.ui.general_defaults_form.general_app_group.language_cb.addItem(name)
  496. # ###########################################################################################################
  497. # ####################################### APPLY APP LANGUAGE ################################################
  498. # ###########################################################################################################
  499. ret_val = fcTranslate.apply_language('strings')
  500. if ret_val == "no language":
  501. self.inform.emit('[ERROR] %s' % _("Could not find the Language files. The App strings are missing."))
  502. log.debug("Could not find the Language files. The App strings are missing.")
  503. else:
  504. # make the current language the current selection on the language combobox
  505. self.ui.general_defaults_form.general_app_group.language_cb.setCurrentText(ret_val)
  506. log.debug("App.__init__() --> Applied %s language." % str(ret_val).capitalize())
  507. # ###########################################################################################################
  508. # ###################################### CREATE UNIQUE SERIAL NUMBER ########################################
  509. # ###########################################################################################################
  510. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  511. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  512. self.defaults['global_serial'] = ''.join([random.choice(chars) for __ in range(20)])
  513. self.preferencesUiManager.save_defaults(silent=True, first_time=True)
  514. self.defaults.propagate_defaults()
  515. # ###########################################################################################################
  516. # ######################################## UPDATE THE OPTIONS ###############################################
  517. # ###########################################################################################################
  518. self.options = LoudDict()
  519. # -----------------------------------------------------------------------------------------------------------
  520. # Update the self.options from the self.defaults
  521. # The self.defaults holds the application defaults while the self.options holds the object defaults
  522. # -----------------------------------------------------------------------------------------------------------
  523. # Copy app defaults to project options
  524. for def_key, def_val in self.defaults.items():
  525. self.options[def_key] = deepcopy(def_val)
  526. self.preferencesUiManager.show_preferences_gui()
  527. # ### End of Data ####
  528. # ###########################################################################################################
  529. # #################################### SETUP OBJECT COLLECTION ##############################################
  530. # ###########################################################################################################
  531. self.collection = ObjectCollection(self)
  532. self.ui.project_tab_layout.addWidget(self.collection.view)
  533. # ### Adjust tabs width ## ##
  534. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  535. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  536. self.collection.view.setMinimumWidth(290)
  537. self.log.debug("Finished creating Object Collection.")
  538. # ###########################################################################################################
  539. # ######################################## SETUP Plot Area ##################################################
  540. # ###########################################################################################################
  541. # determine if the Legacy Graphic Engine is to be used or the OpenGL one
  542. if self.defaults["global_graphic_engine"] == '3D':
  543. self.is_legacy = False
  544. else:
  545. self.is_legacy = True
  546. # Event signals disconnect id holders
  547. self.mp = None
  548. self.mm = None
  549. self.mr = None
  550. self.mdc = None
  551. self.mp_zc = None
  552. self.kp = None
  553. # Matplotlib axis
  554. self.axes = None
  555. if show_splash:
  556. self.splash.showMessage(_("FlatCAM is initializing ...\n"
  557. "Canvas initialization started."),
  558. alignment=Qt.AlignBottom | Qt.AlignLeft,
  559. color=QtGui.QColor("gray"))
  560. start_plot_time = time.time() # debug
  561. self.plotcanvas = None
  562. self.app_cursor = None
  563. self.hover_shapes = None
  564. self.log.debug("Setting up canvas: %s" % str(self.defaults["global_graphic_engine"]))
  565. # setup the PlotCanvas
  566. self.on_plotcanvas_setup()
  567. end_plot_time = time.time()
  568. self.used_time = end_plot_time - start_plot_time
  569. self.log.debug("Finished Canvas initialization in %s seconds." % str(self.used_time))
  570. if show_splash:
  571. self.splash.showMessage('%s: %ssec' % (_("FlatCAM is initializing ...\n"
  572. "Canvas initialization started.\n"
  573. "Canvas initialization finished in"), '%.2f' % self.used_time),
  574. alignment=Qt.AlignBottom | Qt.AlignLeft,
  575. color=QtGui.QColor("gray"))
  576. self.ui.splitter.setStretchFactor(1, 2)
  577. # ###########################################################################################################
  578. # ############################################### SYS TRAY ##################################################
  579. # ###########################################################################################################
  580. if self.defaults["global_systray_icon"]:
  581. self.parent_w = QtWidgets.QWidget()
  582. if self.cmd_line_headless == 1:
  583. self.trayIcon = FlatCAMSystemTray(app=self,
  584. icon=QtGui.QIcon(self.resource_location +
  585. '/flatcam_icon32_green.png'),
  586. headless=True,
  587. parent=self.parent_w)
  588. else:
  589. self.trayIcon = FlatCAMSystemTray(app=self,
  590. icon=QtGui.QIcon(self.resource_location +
  591. '/flatcam_icon32_green.png'),
  592. parent=self.parent_w)
  593. # ###########################################################################################################
  594. # ############################################### Worker SETUP ##############################################
  595. # ###########################################################################################################
  596. if self.defaults["global_worker_number"]:
  597. self.workers = WorkerStack(workers_number=int(self.defaults["global_worker_number"]))
  598. else:
  599. self.workers = WorkerStack(workers_number=2)
  600. self.worker_task.connect(self.workers.add_task)
  601. self.log.debug("Finished creating Workers crew.")
  602. # ###########################################################################################################
  603. # ############################################# Activity Monitor ###########################################
  604. # ###########################################################################################################
  605. self.activity_view = FlatCAMActivityView(app=self)
  606. self.ui.infobar.addWidget(self.activity_view)
  607. self.proc_container = FCVisibleProcessContainer(self.activity_view)
  608. # ###########################################################################################################
  609. # ############################################# Signal handling #############################################
  610. # ###########################################################################################################
  611. # ########################################## Custom signals ################################################
  612. # signal for displaying messages in status bar
  613. self.inform.connect(self.info)
  614. # signal to be called when the app is quiting
  615. self.app_quit.connect(self.quit_application, type=Qt.QueuedConnection)
  616. self.message.connect(self.message_dialog)
  617. # self.progress.connect(self.set_progress_bar)
  618. # signals that are emitted when object state changes
  619. self.object_created.connect(self.on_object_created)
  620. self.object_changed.connect(self.on_object_changed)
  621. self.object_plotted.connect(self.on_object_plotted)
  622. self.plots_updated.connect(self.on_plots_updated)
  623. # signals emitted when file state change
  624. self.file_opened.connect(self.register_recent)
  625. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  626. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  627. # ########################################## Standard signals ###############################################
  628. # ### Menu
  629. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  630. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  631. self.ui.menufilenewgrb.triggered.connect(self.new_gerber_object)
  632. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  633. self.ui.menufilenewdoc.triggered.connect(self.new_document_object)
  634. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  635. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  636. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  637. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  638. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  639. self.ui.menufilenewscript.triggered.connect(self.on_filenewscript)
  640. self.ui.menufileopenscript.triggered.connect(self.on_fileopenscript)
  641. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  642. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  643. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  644. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  645. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  646. self.ui.menufileimport_hpgl2_as_geo.triggered.connect(self.on_fileopenhpgl2)
  647. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  648. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  649. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  650. self.ui.menufileexportgerber.triggered.connect(self.on_file_exportgerber)
  651. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  652. self.ui.menufile_print.triggered.connect(lambda: self.on_file_save_objects_pdf(use_thread=True))
  653. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  654. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  655. # self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  656. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  657. self.ui.menufileexportpref.triggered.connect(self.on_export_preferences)
  658. self.ui.menufileimportpref.triggered.connect(self.on_import_preferences)
  659. self.ui.menufile_exit.triggered.connect(self.final_save)
  660. self.ui.menueditedit.triggered.connect(lambda: self.object2editor())
  661. self.ui.menueditok.triggered.connect(lambda: self.editor2object())
  662. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  663. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  664. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  665. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  666. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  667. self.ui.menueditdelete.triggered.connect(self.on_delete)
  668. self.ui.menueditcopyobject.triggered.connect(self.on_copy_command)
  669. self.ui.menueditconvert_any2geo.triggered.connect(self.convert_any2geo)
  670. self.ui.menueditconvert_any2gerber.triggered.connect(self.convert_any2gerber)
  671. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  672. self.ui.menuedit_move2origin.triggered.connect(self.on_move2origin)
  673. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  674. self.ui.menueditlocate.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  675. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  676. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  677. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  678. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  679. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  680. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  681. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  682. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  683. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  684. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  685. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  686. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  687. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  688. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  689. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  690. self.ui.menuoptions_tools_db.triggered.connect(lambda: self.on_tools_database(source='app'))
  691. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  692. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  693. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  694. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  695. self.ui.menuview_zoom_in.triggered.connect(self.on_zoom_in)
  696. self.ui.menuview_zoom_out.triggered.connect(self.on_zoom_out)
  697. self.ui.menuview_replot.triggered.connect(self.plot_all)
  698. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  699. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  700. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  701. self.ui.menuview_toggle_notebook.triggered.connect(self.on_toggle_notebook)
  702. self.ui.menu_toggle_nb.triggered.connect(self.on_toggle_notebook)
  703. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  704. self.ui.menuview_toggle_grid_lines.triggered.connect(self.on_toggle_grid_lines)
  705. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  706. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_toggle)
  707. self.ui.menutoolshell.triggered.connect(self.toggle_shell)
  708. self.ui.menuhelp_about.triggered.connect(self.on_about)
  709. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  710. self.ui.menuhelp_report_bug.triggered.connect(lambda: webbrowser.open(self.bug_report_url))
  711. self.ui.menuhelp_exc_spec.triggered.connect(lambda: webbrowser.open(self.excellon_spec_url))
  712. self.ui.menuhelp_gerber_spec.triggered.connect(lambda: webbrowser.open(self.gerber_spec_url))
  713. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  714. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  715. self.ui.menuprojectenable.triggered.connect(self.on_enable_sel_plots)
  716. self.ui.menuprojectdisable.triggered.connect(self.on_disable_sel_plots)
  717. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  718. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  719. self.ui.menuprojectcopy.triggered.connect(self.on_copy_command)
  720. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  721. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  722. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  723. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  724. # ToolBar signals
  725. self.connect_toolbar_signals()
  726. # Notebook and Plot Tab Area signals
  727. # make the right click on the notebook tab and plot tab area tab raise a menu
  728. self.ui.notebook.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  729. self.ui.plot_tab_area.tabBar.setContextMenuPolicy(QtCore.Qt.ActionsContextMenu)
  730. self.on_tab_setup_context_menu()
  731. # activate initial state
  732. self.on_tab_rmb_click(self.defaults["global_tabs_detachable"])
  733. # Context Menu
  734. self.ui.popmenu_disable.triggered.connect(lambda: self.toggle_plots(self.collection.get_selected()))
  735. self.ui.popmenu_panel_toggle.triggered.connect(self.on_toggle_notebook)
  736. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  737. self.ui.popmenu_new_grb.triggered.connect(self.new_gerber_object)
  738. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  739. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  740. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  741. self.ui.clearplot.triggered.connect(self.clear_plots)
  742. self.ui.replot.triggered.connect(self.plot_all)
  743. self.ui.popmenu_copy.triggered.connect(self.on_copy_command)
  744. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  745. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  746. self.ui.popmenu_save.triggered.connect(lambda: self.editor2object())
  747. self.ui.popmenu_move.triggered.connect(self.obj_move)
  748. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  749. # Project Context Menu -> Color Setting
  750. for act in self.ui.menuprojectcolor.actions():
  751. act.triggered.connect(self.on_set_color_action_triggered)
  752. # ###########################################################################################################
  753. # #################################### GUI PREFERENCES SIGNALS ##############################################
  754. # ###########################################################################################################
  755. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  756. lambda: self.on_toggle_units(no_pref=False))
  757. # ##################################### Workspace Setting Signals ###########################################
  758. self.ui.general_defaults_form.general_app_set_group.wk_cb.currentIndexChanged.connect(
  759. self.on_workspace_modified)
  760. self.ui.general_defaults_form.general_app_set_group.wk_orientation_radio.activated_custom.connect(
  761. self.on_workspace_modified
  762. )
  763. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  764. # ###########################################################################################################
  765. # ######################################## GUI SETTINGS SIGNALS #############################################
  766. # ###########################################################################################################
  767. self.ui.general_defaults_form.general_app_group.ge_radio.activated_custom.connect(self.on_app_restart)
  768. self.ui.general_defaults_form.general_app_set_group.cursor_radio.activated_custom.connect(self.on_cursor_type)
  769. # ######################################## Tools related signals ############################################
  770. # Film Tool
  771. self.ui.tools_defaults_form.tools_film_group.film_color_entry.editingFinished.connect(
  772. self.on_film_color_entry)
  773. self.ui.tools_defaults_form.tools_film_group.film_color_button.clicked.connect(
  774. self.on_film_color_button)
  775. # QRCode Tool
  776. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.editingFinished.connect(
  777. self.on_qrcode_fill_color_entry)
  778. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.clicked.connect(
  779. self.on_qrcode_fill_color_button)
  780. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.editingFinished.connect(
  781. self.on_qrcode_back_color_entry)
  782. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.clicked.connect(
  783. self.on_qrcode_back_color_button)
  784. # portability changed signal
  785. self.ui.general_defaults_form.general_app_group.portability_cb.stateChanged.connect(self.on_portable_checked)
  786. # Object list
  787. self.collection.view.activated.connect(self.on_row_activated)
  788. self.collection.item_selected.connect(self.on_row_selected)
  789. self.object_status_changed.connect(self.on_collection_updated)
  790. # Make sure that when the Excellon loading parameters are changed, the change is reflected in the
  791. # Export Excellon parameters.
  792. self.ui.excellon_defaults_form.excellon_gen_group.update_excellon_cb.stateChanged.connect(
  793. self.on_update_exc_export
  794. )
  795. # call it once to make sure it is updated at startup
  796. self.on_update_exc_export(state=self.defaults["excellon_update"])
  797. # when there are arguments at application startup this get launched
  798. self.args_at_startup[list].connect(self.on_startup_args)
  799. # ###########################################################################################################
  800. # ####################################### FILE ASSOCIATIONS SIGNALS #########################################
  801. # ###########################################################################################################
  802. self.ui.util_defaults_form.fa_excellon_group.restore_btn.clicked.connect(
  803. lambda: self.restore_extensions(ext_type='excellon'))
  804. self.ui.util_defaults_form.fa_gcode_group.restore_btn.clicked.connect(
  805. lambda: self.restore_extensions(ext_type='gcode'))
  806. self.ui.util_defaults_form.fa_gerber_group.restore_btn.clicked.connect(
  807. lambda: self.restore_extensions(ext_type='gerber'))
  808. self.ui.util_defaults_form.fa_excellon_group.del_all_btn.clicked.connect(
  809. lambda: self.delete_all_extensions(ext_type='excellon'))
  810. self.ui.util_defaults_form.fa_gcode_group.del_all_btn.clicked.connect(
  811. lambda: self.delete_all_extensions(ext_type='gcode'))
  812. self.ui.util_defaults_form.fa_gerber_group.del_all_btn.clicked.connect(
  813. lambda: self.delete_all_extensions(ext_type='gerber'))
  814. self.ui.util_defaults_form.fa_excellon_group.add_btn.clicked.connect(
  815. lambda: self.add_extension(ext_type='excellon'))
  816. self.ui.util_defaults_form.fa_gcode_group.add_btn.clicked.connect(
  817. lambda: self.add_extension(ext_type='gcode'))
  818. self.ui.util_defaults_form.fa_gerber_group.add_btn.clicked.connect(
  819. lambda: self.add_extension(ext_type='gerber'))
  820. self.ui.util_defaults_form.fa_excellon_group.del_btn.clicked.connect(
  821. lambda: self.del_extension(ext_type='excellon'))
  822. self.ui.util_defaults_form.fa_gcode_group.del_btn.clicked.connect(
  823. lambda: self.del_extension(ext_type='gcode'))
  824. self.ui.util_defaults_form.fa_gerber_group.del_btn.clicked.connect(
  825. lambda: self.del_extension(ext_type='gerber'))
  826. # connect the 'Apply' buttons from the Preferences/File Associations
  827. self.ui.util_defaults_form.fa_excellon_group.exc_list_btn.clicked.connect(
  828. lambda: self.on_register_files(obj_type='excellon'))
  829. self.ui.util_defaults_form.fa_gcode_group.gco_list_btn.clicked.connect(
  830. lambda: self.on_register_files(obj_type='gcode'))
  831. self.ui.util_defaults_form.fa_gerber_group.grb_list_btn.clicked.connect(
  832. lambda: self.on_register_files(obj_type='gerber'))
  833. # ###########################################################################################################
  834. # ########################################### KEYWORDS SIGNALS ##############################################
  835. # ###########################################################################################################
  836. self.ui.util_defaults_form.kw_group.restore_btn.clicked.connect(
  837. lambda: self.restore_extensions(ext_type='keyword'))
  838. self.ui.util_defaults_form.kw_group.del_all_btn.clicked.connect(
  839. lambda: self.delete_all_extensions(ext_type='keyword'))
  840. self.ui.util_defaults_form.kw_group.add_btn.clicked.connect(
  841. lambda: self.add_extension(ext_type='keyword'))
  842. self.ui.util_defaults_form.kw_group.del_btn.clicked.connect(
  843. lambda: self.del_extension(ext_type='keyword'))
  844. # connect the abort_all_tasks related slots to the related signals
  845. self.proc_container.idle_flag.connect(self.app_is_idle)
  846. # signal emitted when a tab is closed in the Plot Area
  847. self.ui.plot_tab_area.tab_closed_signal.connect(self.on_plot_area_tab_closed)
  848. self.ui.grid_snap_btn.triggered.connect(self.on_grid_snap_triggered)
  849. self.ui.snap_infobar_label.clicked.connect(self.on_grid_icon_snap_clicked)
  850. # signal to close the application
  851. self.close_app_signal.connect(self.kill_app)
  852. # ################################# FINISHED CONNECTING SIGNALS #############################################
  853. # ###########################################################################################################
  854. # ###########################################################################################################
  855. # ###########################################################################################################
  856. self.log.debug("Finished connecting Signals.")
  857. # ###########################################################################################################
  858. # ########################################## Other setups ###################################################
  859. # ###########################################################################################################
  860. # to use for tools like Distance tool who depends on the event sources who are changed inside the Editors
  861. # depending on from where those tools are called different actions can be done
  862. self.call_source = 'app'
  863. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  864. self.tool_tab_locked = False
  865. # decide if to show or hide the Notebook side of the screen at startup
  866. if self.defaults["global_project_at_startup"] is True:
  867. self.ui.splitter.setSizes([1, 1])
  868. else:
  869. self.ui.splitter.setSizes([0, 1])
  870. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  871. self.setup_component_editor()
  872. # ###########################################################################################################
  873. # ####################################### Auto-complete KEYWORDS ############################################
  874. # ###########################################################################################################
  875. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  876. 'aligndrill', 'aligndrillgrid', 'bbox', 'clear', 'cncjob', 'cutout',
  877. 'del', 'drillcncjob', 'export_dxf', 'edxf', 'export_excellon',
  878. 'export_exc',
  879. 'export_gcode', 'export_gerber', 'export_svg', 'ext', 'exteriors', 'follow',
  880. 'geo_union', 'geocutout', 'get_bounds', 'get_names', 'get_sys', 'help', 'import_svg',
  881. 'interiors', 'isolate', 'join_excellon',
  882. 'join_geometry', 'list_sys', 'milld', 'mills', 'milldrills', 'millslots',
  883. 'mirror', 'ncc',
  884. 'ncr', 'new', 'new_geometry', 'non_copper_regions', 'offset',
  885. 'open_excellon', 'open_gcode', 'open_gerber', 'open_project', 'options', 'origin',
  886. 'paint', 'panelize', 'plot_all', 'plot_objects', 'plot_status', 'quit_flatcam',
  887. 'save', 'save_project',
  888. 'save_sys', 'scale', 'set_active', 'set_origin', 'set_sys',
  889. 'skew', 'subtract_poly', 'subtract_rectangle',
  890. 'version', 'write_gcode'
  891. ]
  892. self.default_keywords = ['Desktop', 'Documents', 'FlatConfig', 'FlatPrj', 'False', 'Marius', 'My Documents',
  893. 'Paste_1',
  894. 'Repetier', 'Roland_MDX_20', 'Users', 'Toolchange_Custom', 'Toolchange_Probe_MACH3',
  895. 'Toolchange_manual', 'True', 'Users',
  896. 'all', 'auto', 'axis',
  897. 'axisoffset', 'box', 'center_x', 'center_y', 'columns', 'combine', 'connect',
  898. 'contour', 'default',
  899. 'depthperpass', 'dia', 'diatol', 'dist', 'drilled_dias', 'drillz', 'dpp',
  900. 'dwelltime', 'extracut_length', 'endxy', 'enz', 'f', 'feedrate',
  901. 'feedrate_z', 'grbl_11', 'GRBL_laser', 'gridoffsety', 'gridx', 'gridy',
  902. 'has_offset', 'holes', 'hpgl', 'iso_type', 'line_xyz', 'margin', 'marlin', 'method',
  903. 'milled_dias', 'minoffset', 'name', 'offset', 'opt_type', 'order',
  904. 'outname', 'overlap', 'passes', 'postamble', 'pp', 'ppname_e', 'ppname_g',
  905. 'preamble', 'radius', 'ref', 'rest', 'rows', 'shellvar_', 'scale_factor',
  906. 'spacing_columns',
  907. 'spacing_rows', 'spindlespeed', 'startz', 'startxy',
  908. 'toolchange_xy', 'toolchangez', 'travelz',
  909. 'tooldia', 'use_threads', 'value',
  910. 'x', 'x0', 'x1', 'y', 'y0', 'y1', 'z_cut', 'z_move'
  911. ]
  912. self.tcl_keywords = [
  913. 'after', 'append', 'apply', 'argc', 'argv', 'argv0', 'array', 'attemptckalloc', 'attemptckrealloc',
  914. 'auto_execok', 'auto_import', 'auto_load', 'auto_mkindex', 'auto_path', 'auto_qualify', 'auto_reset',
  915. 'bgerror', 'binary', 'break', 'case', 'catch', 'cd', 'chan', 'ckalloc', 'ckfree', 'ckrealloc', 'clock',
  916. 'close', 'concat', 'continue', 'coroutine', 'dde', 'dict', 'encoding', 'env', 'eof', 'error', 'errorCode',
  917. 'errorInfo', 'eval', 'exec', 'exit', 'expr', 'fblocked', 'fconfigure', 'fcopy', 'file', 'fileevent',
  918. 'filename', 'flush', 'for', 'foreach', 'format', 'gets', 'glob', 'global', 'history', 'http', 'if', 'incr',
  919. 'info', 'interp', 'join', 'lappend', 'lassign', 'lindex', 'linsert', 'list', 'llength', 'load', 'lrange',
  920. 'lrepeat', 'lreplace', 'lreverse', 'lsearch', 'lset', 'lsort', 'mathfunc', 'mathop', 'memory', 'msgcat',
  921. 'my', 'namespace', 'next', 'nextto', 'open', 'package', 'parray', 'pid', 'pkg_mkIndex', 'platform',
  922. 'proc', 'puts', 'pwd', 're_syntax', 'read', 'refchan', 'regexp', 'registry', 'regsub', 'rename', 'return',
  923. 'safe', 'scan', 'seek', 'self', 'set', 'socket', 'source', 'split', 'string', 'subst', 'switch',
  924. 'tailcall', 'Tcl', 'Tcl_Access', 'Tcl_AddErrorInfo', 'Tcl_AddObjErrorInfo', 'Tcl_AlertNotifier',
  925. 'Tcl_Alloc', 'Tcl_AllocHashEntryProc', 'Tcl_AllocStatBuf', 'Tcl_AllowExceptions', 'Tcl_AppendAllObjTypes',
  926. 'Tcl_AppendElement', 'Tcl_AppendExportList', 'Tcl_AppendFormatToObj', 'Tcl_AppendLimitedToObj',
  927. 'Tcl_AppendObjToErrorInfo', 'Tcl_AppendObjToObj', 'Tcl_AppendPrintfToObj', 'Tcl_AppendResult',
  928. 'Tcl_AppendResultVA', 'Tcl_AppendStringsToObj', 'Tcl_AppendStringsToObjVA', 'Tcl_AppendToObj',
  929. 'Tcl_AppendUnicodeToObj', 'Tcl_AppInit', 'Tcl_AppInitProc', 'Tcl_ArgvInfo', 'Tcl_AsyncCreate',
  930. 'Tcl_AsyncDelete', 'Tcl_AsyncInvoke', 'Tcl_AsyncMark', 'Tcl_AsyncProc', 'Tcl_AsyncReady',
  931. 'Tcl_AttemptAlloc', 'Tcl_AttemptRealloc', 'Tcl_AttemptSetObjLength', 'Tcl_BackgroundError',
  932. 'Tcl_BackgroundException', 'Tcl_Backslash', 'Tcl_BadChannelOption', 'Tcl_CallWhenDeleted', 'Tcl_Canceled',
  933. 'Tcl_CancelEval', 'Tcl_CancelIdleCall', 'Tcl_ChannelBlockModeProc', 'Tcl_ChannelBuffered',
  934. 'Tcl_ChannelClose2Proc', 'Tcl_ChannelCloseProc', 'Tcl_ChannelFlushProc', 'Tcl_ChannelGetHandleProc',
  935. 'Tcl_ChannelGetOptionProc', 'Tcl_ChannelHandlerProc', 'Tcl_ChannelInputProc', 'Tcl_ChannelName',
  936. 'Tcl_ChannelOutputProc', 'Tcl_ChannelProc', 'Tcl_ChannelSeekProc', 'Tcl_ChannelSetOptionProc',
  937. 'Tcl_ChannelThreadActionProc', 'Tcl_ChannelTruncateProc', 'Tcl_ChannelType', 'Tcl_ChannelVersion',
  938. 'Tcl_ChannelWatchProc', 'Tcl_ChannelWideSeekProc', 'Tcl_Chdir', 'Tcl_ClassGetMetadata',
  939. 'Tcl_ClassSetConstructor', 'Tcl_ClassSetDestructor', 'Tcl_ClassSetMetadata', 'Tcl_ClearChannelHandlers',
  940. 'Tcl_CloneProc', 'Tcl_Close', 'Tcl_CloseProc', 'Tcl_CmdDeleteProc', 'Tcl_CmdInfo',
  941. 'Tcl_CmdObjTraceDeleteProc', 'Tcl_CmdObjTraceProc', 'Tcl_CmdProc', 'Tcl_CmdTraceProc',
  942. 'Tcl_CommandComplete', 'Tcl_CommandTraceInfo', 'Tcl_CommandTraceProc', 'Tcl_CompareHashKeysProc',
  943. 'Tcl_Concat', 'Tcl_ConcatObj', 'Tcl_ConditionFinalize', 'Tcl_ConditionNotify', 'Tcl_ConditionWait',
  944. 'Tcl_Config', 'Tcl_ConvertCountedElement', 'Tcl_ConvertElement', 'Tcl_ConvertToType',
  945. 'Tcl_CopyObjectInstance', 'Tcl_CreateAlias', 'Tcl_CreateAliasObj', 'Tcl_CreateChannel',
  946. 'Tcl_CreateChannelHandler', 'Tcl_CreateCloseHandler', 'Tcl_CreateCommand', 'Tcl_CreateEncoding',
  947. 'Tcl_CreateEnsemble', 'Tcl_CreateEventSource', 'Tcl_CreateExitHandler', 'Tcl_CreateFileHandler',
  948. 'Tcl_CreateHashEntry', 'Tcl_CreateInterp', 'Tcl_CreateMathFunc', 'Tcl_CreateNamespace',
  949. 'Tcl_CreateObjCommand', 'Tcl_CreateObjTrace', 'Tcl_CreateSlave', 'Tcl_CreateThread',
  950. 'Tcl_CreateThreadExitHandler', 'Tcl_CreateTimerHandler', 'Tcl_CreateTrace',
  951. 'Tcl_CutChannel', 'Tcl_DecrRefCount', 'Tcl_DeleteAssocData', 'Tcl_DeleteChannelHandler',
  952. 'Tcl_DeleteCloseHandler', 'Tcl_DeleteCommand', 'Tcl_DeleteCommandFromToken', 'Tcl_DeleteEvents',
  953. 'Tcl_DeleteEventSource', 'Tcl_DeleteExitHandler', 'Tcl_DeleteFileHandler', 'Tcl_DeleteHashEntry',
  954. 'Tcl_DeleteHashTable', 'Tcl_DeleteInterp', 'Tcl_DeleteNamespace', 'Tcl_DeleteThreadExitHandler',
  955. 'Tcl_DeleteTimerHandler', 'Tcl_DeleteTrace', 'Tcl_DetachChannel', 'Tcl_DetachPids', 'Tcl_DictObjDone',
  956. 'Tcl_DictObjFirst', 'Tcl_DictObjGet', 'Tcl_DictObjNext', 'Tcl_DictObjPut', 'Tcl_DictObjPutKeyList',
  957. 'Tcl_DictObjRemove', 'Tcl_DictObjRemoveKeyList', 'Tcl_DictObjSize', 'Tcl_DiscardInterpState',
  958. 'Tcl_DiscardResult', 'Tcl_DontCallWhenDeleted', 'Tcl_DoOneEvent', 'Tcl_DoWhenIdle',
  959. 'Tcl_DriverBlockModeProc', 'Tcl_DriverClose2Proc', 'Tcl_DriverCloseProc', 'Tcl_DriverFlushProc',
  960. 'Tcl_DriverGetHandleProc', 'Tcl_DriverGetOptionProc', 'Tcl_DriverHandlerProc', 'Tcl_DriverInputProc',
  961. 'Tcl_DriverOutputProc', 'Tcl_DriverSeekProc', 'Tcl_DriverSetOptionProc', 'Tcl_DriverThreadActionProc',
  962. 'Tcl_DriverTruncateProc', 'Tcl_DriverWatchProc', 'Tcl_DriverWideSeekProc', 'Tcl_DStringAppend',
  963. 'Tcl_DStringAppendElement', 'Tcl_DStringEndSublist', 'Tcl_DStringFree', 'Tcl_DStringGetResult',
  964. 'Tcl_DStringInit', 'Tcl_DStringLength', 'Tcl_DStringResult', 'Tcl_DStringSetLength',
  965. 'Tcl_DStringStartSublist', 'Tcl_DStringTrunc', 'Tcl_DStringValue', 'Tcl_DumpActiveMemory',
  966. 'Tcl_DupInternalRepProc', 'Tcl_DuplicateObj', 'Tcl_EncodingConvertProc', 'Tcl_EncodingFreeProc',
  967. 'Tcl_EncodingType', 'tcl_endOfWord', 'Tcl_Eof', 'Tcl_ErrnoId', 'Tcl_ErrnoMsg', 'Tcl_Eval', 'Tcl_EvalEx',
  968. 'Tcl_EvalFile', 'Tcl_EvalObjEx', 'Tcl_EvalObjv', 'Tcl_EvalTokens', 'Tcl_EvalTokensStandard', 'Tcl_Event',
  969. 'Tcl_EventCheckProc', 'Tcl_EventDeleteProc', 'Tcl_EventProc', 'Tcl_EventSetupProc', 'Tcl_EventuallyFree',
  970. 'Tcl_Exit', 'Tcl_ExitProc', 'Tcl_ExitThread', 'Tcl_Export', 'Tcl_ExposeCommand', 'Tcl_ExprBoolean',
  971. 'Tcl_ExprBooleanObj', 'Tcl_ExprDouble', 'Tcl_ExprDoubleObj', 'Tcl_ExprLong', 'Tcl_ExprLongObj',
  972. 'Tcl_ExprObj', 'Tcl_ExprString', 'Tcl_ExternalToUtf', 'Tcl_ExternalToUtfDString', 'Tcl_FileProc',
  973. 'Tcl_Filesystem', 'Tcl_Finalize', 'Tcl_FinalizeNotifier', 'Tcl_FinalizeThread', 'Tcl_FindCommand',
  974. 'Tcl_FindEnsemble', 'Tcl_FindExecutable', 'Tcl_FindHashEntry', 'tcl_findLibrary', 'Tcl_FindNamespace',
  975. 'Tcl_FirstHashEntry', 'Tcl_Flush', 'Tcl_ForgetImport', 'Tcl_Format', 'Tcl_FreeHashEntryProc',
  976. 'Tcl_FreeInternalRepProc', 'Tcl_FreeParse', 'Tcl_FreeProc', 'Tcl_FreeResult',
  977. 'Tcl_Free·\xa0Tcl_FreeEncoding', 'Tcl_FSAccess', 'Tcl_FSAccessProc', 'Tcl_FSChdir',
  978. 'Tcl_FSChdirProc', 'Tcl_FSConvertToPathType', 'Tcl_FSCopyDirectory', 'Tcl_FSCopyDirectoryProc',
  979. 'Tcl_FSCopyFile', 'Tcl_FSCopyFileProc', 'Tcl_FSCreateDirectory', 'Tcl_FSCreateDirectoryProc',
  980. 'Tcl_FSCreateInternalRepProc', 'Tcl_FSData', 'Tcl_FSDeleteFile', 'Tcl_FSDeleteFileProc',
  981. 'Tcl_FSDupInternalRepProc', 'Tcl_FSEqualPaths', 'Tcl_FSEvalFile', 'Tcl_FSEvalFileEx',
  982. 'Tcl_FSFileAttrsGet', 'Tcl_FSFileAttrsGetProc', 'Tcl_FSFileAttrsSet', 'Tcl_FSFileAttrsSetProc',
  983. 'Tcl_FSFileAttrStrings', 'Tcl_FSFileSystemInfo', 'Tcl_FSFilesystemPathTypeProc',
  984. 'Tcl_FSFilesystemSeparatorProc', 'Tcl_FSFreeInternalRepProc', 'Tcl_FSGetCwd', 'Tcl_FSGetCwdProc',
  985. 'Tcl_FSGetFileSystemForPath', 'Tcl_FSGetInternalRep', 'Tcl_FSGetNativePath', 'Tcl_FSGetNormalizedPath',
  986. 'Tcl_FSGetPathType', 'Tcl_FSGetTranslatedPath', 'Tcl_FSGetTranslatedStringPath',
  987. 'Tcl_FSInternalToNormalizedProc', 'Tcl_FSJoinPath', 'Tcl_FSJoinToPath', 'Tcl_FSLinkProc',
  988. 'Tcl_FSLink·\xa0Tcl_FSListVolumes', 'Tcl_FSListVolumesProc', 'Tcl_FSLoadFile', 'Tcl_FSLoadFileProc',
  989. 'Tcl_FSLstat', 'Tcl_FSLstatProc', 'Tcl_FSMatchInDirectory', 'Tcl_FSMatchInDirectoryProc',
  990. 'Tcl_FSMountsChanged', 'Tcl_FSNewNativePath', 'Tcl_FSNormalizePathProc', 'Tcl_FSOpenFileChannel',
  991. 'Tcl_FSOpenFileChannelProc', 'Tcl_FSPathInFilesystemProc', 'Tcl_FSPathSeparator', 'Tcl_FSRegister',
  992. 'Tcl_FSRemoveDirectory', 'Tcl_FSRemoveDirectoryProc', 'Tcl_FSRenameFile', 'Tcl_FSRenameFileProc',
  993. 'Tcl_FSSplitPath', 'Tcl_FSStat', 'Tcl_FSStatProc', 'Tcl_FSUnloadFile', 'Tcl_FSUnloadFileProc',
  994. 'Tcl_FSUnregister', 'Tcl_FSUtime', 'Tcl_FSUtimeProc', 'Tcl_GetAccessTimeFromStat', 'Tcl_GetAlias',
  995. 'Tcl_GetAliasObj', 'Tcl_GetAssocData', 'Tcl_GetBignumFromObj', 'Tcl_GetBlocksFromStat',
  996. 'Tcl_GetBlockSizeFromStat', 'Tcl_GetBoolean', 'Tcl_GetBooleanFromObj', 'Tcl_GetByteArrayFromObj',
  997. 'Tcl_GetChangeTimeFromStat', 'Tcl_GetChannel', 'Tcl_GetChannelBufferSize', 'Tcl_GetChannelError',
  998. 'Tcl_GetChannelErrorInterp', 'Tcl_GetChannelHandle', 'Tcl_GetChannelInstanceData', 'Tcl_GetChannelMode',
  999. 'Tcl_GetChannelName', 'Tcl_GetChannelNames', 'Tcl_GetChannelNamesEx', 'Tcl_GetChannelOption',
  1000. 'Tcl_GetChannelThread', 'Tcl_GetChannelType', 'Tcl_GetCharLength', 'Tcl_GetClassAsObject',
  1001. 'Tcl_GetCommandFromObj', 'Tcl_GetCommandFullName', 'Tcl_GetCommandInfo', 'Tcl_GetCommandInfoFromToken',
  1002. 'Tcl_GetCommandName', 'Tcl_GetCurrentNamespace', 'Tcl_GetCurrentThread', 'Tcl_GetCwd',
  1003. 'Tcl_GetDefaultEncodingDir', 'Tcl_GetDeviceTypeFromStat', 'Tcl_GetDouble', 'Tcl_GetDoubleFromObj',
  1004. 'Tcl_GetEncoding', 'Tcl_GetEncodingFromObj', 'Tcl_GetEncodingName', 'Tcl_GetEncodingNameFromEnvironment',
  1005. 'Tcl_GetEncodingNames', 'Tcl_GetEncodingSearchPath', 'Tcl_GetEnsembleFlags', 'Tcl_GetEnsembleMappingDict',
  1006. 'Tcl_GetEnsembleNamespace', 'Tcl_GetEnsembleParameterList', 'Tcl_GetEnsembleSubcommandList',
  1007. 'Tcl_GetEnsembleUnknownHandler', 'Tcl_GetErrno', 'Tcl_GetErrorLine', 'Tcl_GetFSDeviceFromStat',
  1008. 'Tcl_GetFSInodeFromStat', 'Tcl_GetGlobalNamespace', 'Tcl_GetGroupIdFromStat', 'Tcl_GetHashKey',
  1009. 'Tcl_GetHashValue', 'Tcl_GetHostName', 'Tcl_GetIndexFromObj', 'Tcl_GetIndexFromObjStruct', 'Tcl_GetInt',
  1010. 'Tcl_GetInterpPath', 'Tcl_GetIntFromObj', 'Tcl_GetLinkCountFromStat', 'Tcl_GetLongFromObj',
  1011. 'Tcl_GetMaster', 'Tcl_GetMathFuncInfo', 'Tcl_GetModeFromStat', 'Tcl_GetModificationTimeFromStat',
  1012. 'Tcl_GetNameOfExecutable', 'Tcl_GetNamespaceUnknownHandler', 'Tcl_GetObjectAsClass', 'Tcl_GetObjectCommand',
  1013. 'Tcl_GetObjectFromObj', 'Tcl_GetObjectName', 'Tcl_GetObjectNamespace', 'Tcl_GetObjResult', 'Tcl_GetObjType',
  1014. 'Tcl_GetOpenFile', 'Tcl_GetPathType', 'Tcl_GetRange', 'Tcl_GetRegExpFromObj', 'Tcl_GetReturnOptions',
  1015. 'Tcl_Gets', 'Tcl_GetServiceMode', 'Tcl_GetSizeFromStat', 'Tcl_GetSlave', 'Tcl_GetsObj',
  1016. 'Tcl_GetStackedChannel', 'Tcl_GetStartupScript', 'Tcl_GetStdChannel', 'Tcl_GetString',
  1017. 'Tcl_GetStringFromObj', 'Tcl_GetStringResult', 'Tcl_GetThreadData', 'Tcl_GetTime', 'Tcl_GetTopChannel',
  1018. 'Tcl_GetUniChar', 'Tcl_GetUnicode', 'Tcl_GetUnicodeFromObj', 'Tcl_GetUserIdFromStat', 'Tcl_GetVar',
  1019. 'Tcl_GetVar2', 'Tcl_GetVar2Ex', 'Tcl_GetVersion', 'Tcl_GetWideIntFromObj', 'Tcl_GlobalEval',
  1020. 'Tcl_GlobalEvalObj', 'Tcl_GlobTypeData', 'Tcl_HashKeyType', 'Tcl_HashStats', 'Tcl_HideCommand',
  1021. 'Tcl_IdleProc', 'Tcl_Import', 'Tcl_IncrRefCount', 'Tcl_Init', 'Tcl_InitCustomHashTable',
  1022. 'Tcl_InitHashTable', 'Tcl_InitMemory', 'Tcl_InitNotifier', 'Tcl_InitObjHashTable', 'Tcl_InitStubs',
  1023. 'Tcl_InputBlocked', 'Tcl_InputBuffered', 'tcl_interactive', 'Tcl_Interp', 'Tcl_InterpActive',
  1024. 'Tcl_InterpDeleted', 'Tcl_InterpDeleteProc', 'Tcl_InvalidateStringRep', 'Tcl_IsChannelExisting',
  1025. 'Tcl_IsChannelRegistered', 'Tcl_IsChannelShared', 'Tcl_IsEnsemble', 'Tcl_IsSafe', 'Tcl_IsShared',
  1026. 'Tcl_IsStandardChannel', 'Tcl_JoinPath', 'Tcl_JoinThread', 'tcl_library', 'Tcl_LimitAddHandler',
  1027. 'Tcl_LimitCheck', 'Tcl_LimitExceeded', 'Tcl_LimitGetCommands', 'Tcl_LimitGetGranularity',
  1028. 'Tcl_LimitGetTime', 'Tcl_LimitHandlerDeleteProc', 'Tcl_LimitHandlerProc', 'Tcl_LimitReady',
  1029. 'Tcl_LimitRemoveHandler', 'Tcl_LimitSetCommands', 'Tcl_LimitSetGranularity', 'Tcl_LimitSetTime',
  1030. 'Tcl_LimitTypeEnabled', 'Tcl_LimitTypeExceeded', 'Tcl_LimitTypeReset', 'Tcl_LimitTypeSet',
  1031. 'Tcl_LinkVar', 'Tcl_ListMathFuncs', 'Tcl_ListObjAppendElement', 'Tcl_ListObjAppendList',
  1032. 'Tcl_ListObjGetElements', 'Tcl_ListObjIndex', 'Tcl_ListObjLength', 'Tcl_ListObjReplace',
  1033. 'Tcl_LogCommandInfo', 'Tcl_Main', 'Tcl_MainLoopProc', 'Tcl_MakeFileChannel', 'Tcl_MakeSafe',
  1034. 'Tcl_MakeTcpClientChannel', 'Tcl_MathProc', 'TCL_MEM_DEBUG', 'Tcl_Merge', 'Tcl_MethodCallProc',
  1035. 'Tcl_MethodDeclarerClass', 'Tcl_MethodDeclarerObject', 'Tcl_MethodDeleteProc', 'Tcl_MethodIsPublic',
  1036. 'Tcl_MethodIsType', 'Tcl_MethodName', 'Tcl_MethodType', 'Tcl_MutexFinalize', 'Tcl_MutexLock',
  1037. 'Tcl_MutexUnlock', 'Tcl_NamespaceDeleteProc', 'Tcl_NewBignumObj', 'Tcl_NewBooleanObj',
  1038. 'Tcl_NewByteArrayObj', 'Tcl_NewDictObj', 'Tcl_NewDoubleObj', 'Tcl_NewInstanceMethod', 'Tcl_NewIntObj',
  1039. 'Tcl_NewListObj', 'Tcl_NewLongObj', 'Tcl_NewMethod', 'Tcl_NewObj', 'Tcl_NewObjectInstance',
  1040. 'Tcl_NewStringObj', 'Tcl_NewUnicodeObj', 'Tcl_NewWideIntObj', 'Tcl_NextHashEntry', 'tcl_nonwordchars',
  1041. 'Tcl_NotifierProcs', 'Tcl_NotifyChannel', 'Tcl_NRAddCallback', 'Tcl_NRCallObjProc', 'Tcl_NRCmdSwap',
  1042. 'Tcl_NRCreateCommand', 'Tcl_NREvalObj', 'Tcl_NREvalObjv', 'Tcl_NumUtfChars', 'Tcl_Obj', 'Tcl_ObjCmdProc',
  1043. 'Tcl_ObjectContextInvokeNext', 'Tcl_ObjectContextIsFiltering', 'Tcl_ObjectContextMethod',
  1044. 'Tcl_ObjectContextObject', 'Tcl_ObjectContextSkippedArgs', 'Tcl_ObjectDeleted', 'Tcl_ObjectGetMetadata',
  1045. 'Tcl_ObjectGetMethodNameMapper', 'Tcl_ObjectMapMethodNameProc', 'Tcl_ObjectMetadataDeleteProc',
  1046. 'Tcl_ObjectSetMetadata', 'Tcl_ObjectSetMethodNameMapper', 'Tcl_ObjGetVar2', 'Tcl_ObjPrintf',
  1047. 'Tcl_ObjSetVar2', 'Tcl_ObjType', 'Tcl_OpenCommandChannel', 'Tcl_OpenFileChannel', 'Tcl_OpenTcpClient',
  1048. 'Tcl_OpenTcpServer', 'Tcl_OutputBuffered', 'Tcl_PackageInitProc', 'Tcl_PackageUnloadProc', 'Tcl_Panic',
  1049. 'Tcl_PanicProc', 'Tcl_PanicVA', 'Tcl_ParseArgsObjv', 'Tcl_ParseBraces', 'Tcl_ParseCommand', 'Tcl_ParseExpr',
  1050. 'Tcl_ParseQuotedString', 'Tcl_ParseVar', 'Tcl_ParseVarName', 'tcl_patchLevel', 'tcl_pkgPath',
  1051. 'Tcl_PkgPresent', 'Tcl_PkgPresentEx', 'Tcl_PkgProvide', 'Tcl_PkgProvideEx', 'Tcl_PkgRequire',
  1052. 'Tcl_PkgRequireEx', 'Tcl_PkgRequireProc', 'tcl_platform', 'Tcl_PosixError', 'tcl_precision',
  1053. 'Tcl_Preserve', 'Tcl_PrintDouble', 'Tcl_PutEnv', 'Tcl_QueryTimeProc', 'Tcl_QueueEvent', 'tcl_rcFileName',
  1054. 'Tcl_Read', 'Tcl_ReadChars', 'Tcl_ReadRaw', 'Tcl_Realloc', 'Tcl_ReapDetachedProcs', 'Tcl_RecordAndEval',
  1055. 'Tcl_RecordAndEvalObj', 'Tcl_RegExpCompile', 'Tcl_RegExpExec', 'Tcl_RegExpExecObj', 'Tcl_RegExpGetInfo',
  1056. 'Tcl_RegExpIndices', 'Tcl_RegExpInfo', 'Tcl_RegExpMatch', 'Tcl_RegExpMatchObj', 'Tcl_RegExpRange',
  1057. 'Tcl_RegisterChannel', 'Tcl_RegisterConfig', 'Tcl_RegisterObjType', 'Tcl_Release', 'Tcl_ResetResult',
  1058. 'Tcl_RestoreInterpState', 'Tcl_RestoreResult', 'Tcl_SaveInterpState', 'Tcl_SaveResult', 'Tcl_ScaleTimeProc',
  1059. 'Tcl_ScanCountedElement', 'Tcl_ScanElement', 'Tcl_Seek', 'Tcl_ServiceAll', 'Tcl_ServiceEvent',
  1060. 'Tcl_ServiceModeHook', 'Tcl_SetAssocData', 'Tcl_SetBignumObj', 'Tcl_SetBooleanObj',
  1061. 'Tcl_SetByteArrayLength', 'Tcl_SetByteArrayObj', 'Tcl_SetChannelBufferSize', 'Tcl_SetChannelError',
  1062. 'Tcl_SetChannelErrorInterp', 'Tcl_SetChannelOption', 'Tcl_SetCommandInfo', 'Tcl_SetCommandInfoFromToken',
  1063. 'Tcl_SetDefaultEncodingDir', 'Tcl_SetDoubleObj', 'Tcl_SetEncodingSearchPath', 'Tcl_SetEnsembleFlags',
  1064. 'Tcl_SetEnsembleMappingDict', 'Tcl_SetEnsembleParameterList', 'Tcl_SetEnsembleSubcommandList',
  1065. 'Tcl_SetEnsembleUnknownHandler', 'Tcl_SetErrno', 'Tcl_SetErrorCode', 'Tcl_SetErrorCodeVA',
  1066. 'Tcl_SetErrorLine', 'Tcl_SetExitProc', 'Tcl_SetFromAnyProc', 'Tcl_SetHashValue', 'Tcl_SetIntObj',
  1067. 'Tcl_SetListObj', 'Tcl_SetLongObj', 'Tcl_SetMainLoop', 'Tcl_SetMaxBlockTime',
  1068. 'Tcl_SetNamespaceUnknownHandler', 'Tcl_SetNotifier', 'Tcl_SetObjErrorCode', 'Tcl_SetObjLength',
  1069. 'Tcl_SetObjResult', 'Tcl_SetPanicProc', 'Tcl_SetRecursionLimit', 'Tcl_SetResult', 'Tcl_SetReturnOptions',
  1070. 'Tcl_SetServiceMode', 'Tcl_SetStartupScript', 'Tcl_SetStdChannel', 'Tcl_SetStringObj',
  1071. 'Tcl_SetSystemEncoding', 'Tcl_SetTimeProc', 'Tcl_SetTimer', 'Tcl_SetUnicodeObj', 'Tcl_SetVar',
  1072. 'Tcl_SetVar2', 'Tcl_SetVar2Ex', 'Tcl_SetWideIntObj', 'Tcl_SignalId', 'Tcl_SignalMsg', 'Tcl_Sleep',
  1073. 'Tcl_SourceRCFile', 'Tcl_SpliceChannel', 'Tcl_SplitList', 'Tcl_SplitPath', 'Tcl_StackChannel',
  1074. 'Tcl_StandardChannels', 'tcl_startOfNextWord', 'tcl_startOfPreviousWord', 'Tcl_Stat', 'Tcl_StaticPackage',
  1075. 'Tcl_StringCaseMatch', 'Tcl_StringMatch', 'Tcl_SubstObj', 'Tcl_TakeBignumFromObj', 'Tcl_TcpAcceptProc',
  1076. 'Tcl_Tell', 'Tcl_ThreadAlert', 'Tcl_ThreadQueueEvent', 'Tcl_Time', 'Tcl_TimerProc', 'Tcl_Token',
  1077. 'Tcl_TraceCommand', 'tcl_traceCompile', 'tcl_traceEval', 'Tcl_TraceVar', 'Tcl_TraceVar2',
  1078. 'Tcl_TransferResult', 'Tcl_TranslateFileName', 'Tcl_TruncateChannel', 'Tcl_Ungets', 'Tcl_UniChar',
  1079. 'Tcl_UniCharAtIndex', 'Tcl_UniCharCaseMatch', 'Tcl_UniCharIsAlnum', 'Tcl_UniCharIsAlpha',
  1080. 'Tcl_UniCharIsControl', 'Tcl_UniCharIsDigit', 'Tcl_UniCharIsGraph', 'Tcl_UniCharIsLower',
  1081. 'Tcl_UniCharIsPrint', 'Tcl_UniCharIsPunct', 'Tcl_UniCharIsSpace', 'Tcl_UniCharIsUpper',
  1082. 'Tcl_UniCharIsWordChar', 'Tcl_UniCharLen', 'Tcl_UniCharNcasecmp', 'Tcl_UniCharNcmp', 'Tcl_UniCharToLower',
  1083. 'Tcl_UniCharToTitle', 'Tcl_UniCharToUpper', 'Tcl_UniCharToUtf', 'Tcl_UniCharToUtfDString', 'Tcl_UnlinkVar',
  1084. 'Tcl_UnregisterChannel', 'Tcl_UnsetVar', 'Tcl_UnsetVar2', 'Tcl_UnstackChannel', 'Tcl_UntraceCommand',
  1085. 'Tcl_UntraceVar', 'Tcl_UntraceVar2', 'Tcl_UpdateLinkedVar', 'Tcl_UpdateStringProc', 'Tcl_UpVar',
  1086. 'Tcl_UpVar2', 'Tcl_UtfAtIndex', 'Tcl_UtfBackslash', 'Tcl_UtfCharComplete', 'Tcl_UtfFindFirst',
  1087. 'Tcl_UtfFindLast', 'Tcl_UtfNext', 'Tcl_UtfPrev', 'Tcl_UtfToExternal', 'Tcl_UtfToExternalDString',
  1088. 'Tcl_UtfToLower', 'Tcl_UtfToTitle', 'Tcl_UtfToUniChar', 'Tcl_UtfToUniCharDString', 'Tcl_UtfToUpper',
  1089. 'Tcl_ValidateAllMemory', 'Tcl_Value', 'Tcl_VarEval', 'Tcl_VarEvalVA', 'Tcl_VarTraceInfo',
  1090. 'Tcl_VarTraceInfo2', 'Tcl_VarTraceProc', 'tcl_version', 'Tcl_WaitForEvent', 'Tcl_WaitPid',
  1091. 'Tcl_WinTCharToUtf', 'Tcl_WinUtfToTChar', 'tcl_wordBreakAfter', 'tcl_wordBreakBefore', 'tcl_wordchars',
  1092. 'Tcl_Write', 'Tcl_WriteChars', 'Tcl_WriteObj', 'Tcl_WriteRaw', 'Tcl_WrongNumArgs', 'Tcl_ZlibAdler32',
  1093. 'Tcl_ZlibCRC32', 'Tcl_ZlibDeflate', 'Tcl_ZlibInflate', 'Tcl_ZlibStreamChecksum', 'Tcl_ZlibStreamClose',
  1094. 'Tcl_ZlibStreamEof', 'Tcl_ZlibStreamGet', 'Tcl_ZlibStreamGetCommandName', 'Tcl_ZlibStreamInit',
  1095. 'Tcl_ZlibStreamPut', 'tcltest', 'tell', 'throw', 'time', 'tm', 'trace', 'transchan', 'try', 'unknown',
  1096. 'unload', 'unset', 'update', 'uplevel', 'upvar', 'variable', 'vwait', 'while', 'yield', 'yieldto', 'zlib'
  1097. ]
  1098. self.autocomplete_kw_list = self.defaults['util_autocomplete_keywords'].replace(' ', '').split(',')
  1099. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  1100. # ###########################################################################################################
  1101. # ############################################## Shell SETUP ################################################
  1102. # ###########################################################################################################
  1103. self.shell = FCShell(app=self, version=self.version)
  1104. self.ui.shell_dock.setWidget(self.shell)
  1105. self.log.debug("TCL Shell has been initialized.")
  1106. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1107. if self.defaults["global_shell_at_startup"]:
  1108. self.ui.shell_dock.show()
  1109. else:
  1110. self.ui.shell_dock.hide()
  1111. # ###########################################################################################################
  1112. # ########################################## Tools and Plugins ##############################################
  1113. # ###########################################################################################################
  1114. self.dblsidedtool = None
  1115. self.distance_tool = None
  1116. self.distance_min_tool = None
  1117. self.panelize_tool = None
  1118. self.film_tool = None
  1119. self.paste_tool = None
  1120. self.calculator_tool = None
  1121. self.rules_tool = None
  1122. self.sub_tool = None
  1123. self.move_tool = None
  1124. self.cutout_tool = None
  1125. self.ncclear_tool = None
  1126. self.optimal_tool = None
  1127. self.paint_tool = None
  1128. self.transform_tool = None
  1129. self.properties_tool = None
  1130. self.pdf_tool = None
  1131. self.image_tool = None
  1132. self.pcb_wizard_tool = None
  1133. self.cal_exc_tool = None
  1134. self.qrcode_tool = None
  1135. self.copper_thieving_tool = None
  1136. self.fiducial_tool = None
  1137. self.edrills_tool = None
  1138. self.align_objects_tool = None
  1139. self.punch_tool = None
  1140. self.invert_tool = None
  1141. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1142. try:
  1143. self.install_tools()
  1144. except AttributeError as e:
  1145. log.debug("App.__init__() install tools() --> %s" % str(e))
  1146. # ###########################################################################################################
  1147. # ############################################ SETUP RECENT ITEMS ###########################################
  1148. # ###########################################################################################################
  1149. self.setup_recent_items()
  1150. # ###########################################################################################################
  1151. # ######################################### BookMarks Manager ###############################################
  1152. # ###########################################################################################################
  1153. # install Bookmark Manager and populate bookmarks in the Help -> Bookmarks
  1154. self.install_bookmarks()
  1155. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"])
  1156. # ###########################################################################################################
  1157. # ########################################### Tools Database ################################################
  1158. # ###########################################################################################################
  1159. self.tools_db_tab = None
  1160. # ### System Font Parsing ###
  1161. # self.f_parse = ParseFont(self)
  1162. # self.parse_system_fonts()
  1163. # ###########################################################################################################
  1164. # ######################################### Check for updates ###############################################
  1165. # ###########################################################################################################
  1166. # Separate thread (Not worker)
  1167. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1168. if (self.beta is False or self.beta is None) and \
  1169. self.ui.general_defaults_form.general_app_group.version_check_cb.get_value() is True:
  1170. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1171. self.thr2 = QtCore.QThread()
  1172. self.worker_task.emit({'fcn': self.version_check,
  1173. 'params': []})
  1174. self.thr2.start(QtCore.QThread.LowPriority)
  1175. # ###########################################################################################################
  1176. # ##################################### Register files with FlatCAM; #######################################
  1177. # ################################### It works only for Windows for now ####################################
  1178. # ###########################################################################################################
  1179. if sys.platform == 'win32' and self.defaults["first_run"] is True:
  1180. self.on_register_files()
  1181. # ###########################################################################################################
  1182. # ######################################## Variables for global usage #######################################
  1183. # ###########################################################################################################
  1184. # hold the App units
  1185. self.units = 'MM'
  1186. # coordinates for relative position display
  1187. self.rel_point1 = (0, 0)
  1188. self.rel_point2 = (0, 0)
  1189. # variable to store coordinates
  1190. self.pos = (0, 0)
  1191. self.pos_canvas = (0, 0)
  1192. self.pos_jump = (0, 0)
  1193. # variable to store mouse coordinates
  1194. self.mouse = [0, 0]
  1195. # variable to store the delta positions on cavnas
  1196. self.dx = 0
  1197. self.dy = 0
  1198. # decide if we have a double click or single click
  1199. self.doubleclick = False
  1200. # store here the is_dragging value
  1201. self.event_is_dragging = False
  1202. # variable to store if a command is active (then the var is not None) and which one it is
  1203. self.command_active = None
  1204. # variable to store the status of moving selection action
  1205. # None value means that it's not an selection action
  1206. # True value = a selection from left to right
  1207. # False value = a selection from right to left
  1208. self.selection_type = None
  1209. # List to store the objects that are currently loaded in FlatCAM
  1210. # This list is updated on each object creation or object delete
  1211. self.all_objects_list = []
  1212. self.objects_under_the_click_list = []
  1213. # List to store the objects that are selected
  1214. self.sel_objects_list = []
  1215. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1216. self.key_modifiers = None
  1217. # Variable to hold the status of the axis
  1218. self.toggle_axis = True
  1219. # Variable to hold the status of the grid lines
  1220. self.toggle_grid_lines = True
  1221. # Variable to store the status of the fullscreen event
  1222. self.toggle_fscreen = False
  1223. # Variable to store the status of the code editor
  1224. self.toggle_codeeditor = False
  1225. # Variable to be used for situations when we don't want the LMB click on canvas to auto open the Project Tab
  1226. self.click_noproject = False
  1227. self.cursor = None
  1228. # Variable to store the GCODE that was edited
  1229. self.gcode_edited = ""
  1230. self.text_editor_tab = None
  1231. # reference for the self.ui.code_editor
  1232. self.reference_code_editor = None
  1233. self.script_code = ''
  1234. # if Tools DB are changed/edited in the Edit -> Tools Database tab the value will be set to True
  1235. self.tools_db_changed_flag = False
  1236. self.grb_list = ['art', 'bot', 'bsm', 'cmp', 'crc', 'crs', 'dim', 'g4', 'gb0', 'gb1', 'gb2', 'gb3', 'gb5',
  1237. 'gb6', 'gb7', 'gb8', 'gb9', 'gbd', 'gbl', 'gbo', 'gbp', 'gbr', 'gbs', 'gdo', 'ger', 'gko',
  1238. 'gml', 'gm1', 'gm2', 'gm3', 'grb', 'gtl', 'gto', 'gtp', 'gts', 'ly15', 'ly2', 'mil', 'outline',
  1239. 'pho', 'plc', 'pls', 'smb', 'smt', 'sol', 'spb', 'spt', 'ssb', 'sst', 'stc', 'sts', 'top',
  1240. 'tsm']
  1241. self.exc_list = ['drd', 'drl', 'drill', 'exc', 'ncd', 'tap', 'txt', 'xln']
  1242. self.gcode_list = ['cnc', 'din', 'dnc', 'ecs', 'eia', 'fan', 'fgc', 'fnc', 'gc', 'gcd', 'gcode', 'h', 'hnc',
  1243. 'i', 'min', 'mpf', 'mpr', 'nc', 'ncc', 'ncg', 'ngc', 'ncp', 'out', 'ply', 'rol',
  1244. 'sbp', 'tap', 'xpi']
  1245. self.svg_list = ['svg']
  1246. self.dxf_list = ['dxf']
  1247. self.pdf_list = ['pdf']
  1248. self.prj_list = ['flatprj']
  1249. self.conf_list = ['flatconfig']
  1250. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1251. # flag for polygons not cleared
  1252. self.poly_not_cleared = False
  1253. # VisPy visuals
  1254. self.isHovering = False
  1255. self.notHovering = True
  1256. # Window geometry
  1257. self.x_pos = None
  1258. self.y_pos = None
  1259. self.width = None
  1260. self.height = None
  1261. # when True, the app has to return from any thread
  1262. self.abort_flag = False
  1263. # set the value used in the Windows Title
  1264. self.engine = self.ui.general_defaults_form.general_app_group.ge_radio.get_value()
  1265. # this holds a widget that is installed in the Plot Area when View Source option is used
  1266. self.source_editor_tab = None
  1267. self.pagesize = {}
  1268. # Storage for shapes, storage that can be used by FlatCAm tools for utility geometry
  1269. # VisPy visuals
  1270. if self.is_legacy is False:
  1271. try:
  1272. self.tool_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  1273. except AttributeError:
  1274. self.tool_shapes = None
  1275. else:
  1276. from flatcamGUI.PlotCanvasLegacy import ShapeCollectionLegacy
  1277. self.tool_shapes = ShapeCollectionLegacy(obj=self, app=self, name="tool")
  1278. # used in the delayed shutdown self.start_delayed_quit() method
  1279. self.save_timer = None
  1280. # ###########################################################################################################
  1281. # ################################## ADDING FlatCAM EDITORS section #########################################
  1282. # ###########################################################################################################
  1283. # watch out for the position of the editors instantiation ... if it is done before a save of the default values
  1284. # at the first launch of the App , the editors will not be functional.
  1285. try:
  1286. self.geo_editor = FlatCAMGeoEditor(self)
  1287. except AttributeError:
  1288. pass
  1289. try:
  1290. self.exc_editor = FlatCAMExcEditor(self)
  1291. except AttributeError:
  1292. pass
  1293. try:
  1294. self.grb_editor = FlatCAMGrbEditor(self)
  1295. except AttributeError:
  1296. pass
  1297. self.log.debug("Finished adding FlatCAM Editor's.")
  1298. self.set_ui_title(name=_("New Project - Not saved"))
  1299. # disable the Excellon path optimizations made with Google OR-Tools if the app is run on a 32bit platform
  1300. current_platform = platform.architecture()[0]
  1301. if current_platform != '64bit':
  1302. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.set_value('T')
  1303. self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio.setDisabled(True)
  1304. # ###########################################################################################################
  1305. # ##################################### Finished the CONSTRUCTOR ############################################
  1306. # ###########################################################################################################
  1307. App.log.debug("END of constructor. Releasing control.")
  1308. # ###########################################################################################################
  1309. # ########################################## SHOW GUI #######################################################
  1310. # ###########################################################################################################
  1311. # if the app is not started as headless, show it
  1312. if self.cmd_line_headless != 1:
  1313. if show_splash:
  1314. # finish the splash
  1315. self.splash.finish(self.ui)
  1316. mgui_settings = QSettings("Open Source", "FlatCAM")
  1317. if mgui_settings.contains("maximized_gui"):
  1318. maximized_ui = mgui_settings.value('maximized_gui', type=bool)
  1319. if maximized_ui is True:
  1320. self.ui.showMaximized()
  1321. else:
  1322. self.ui.show()
  1323. else:
  1324. self.ui.show()
  1325. if self.defaults["global_systray_icon"]:
  1326. self.trayIcon.show()
  1327. else:
  1328. log.warning("******************* RUNNING HEADLESS *******************")
  1329. # ###########################################################################################################
  1330. # ######################################## START-UP ARGUMENTS ###############################################
  1331. # ###########################################################################################################
  1332. # test if the program was started with a script as parameter
  1333. if self.cmd_line_shellvar:
  1334. try:
  1335. cnt = 0
  1336. command_tcl = 0
  1337. for i in self.cmd_line_shellvar.split(','):
  1338. if i is not None:
  1339. # noinspection PyBroadException
  1340. try:
  1341. command_tcl = eval(i)
  1342. except Exception:
  1343. command_tcl = i
  1344. command_tcl_formatted = 'set shellvar_{nr} "{cmd}"'.format(cmd=str(command_tcl), nr=str(cnt))
  1345. cnt += 1
  1346. # if there are Windows paths then replace the path separator with a Unix like one
  1347. if sys.platform == 'win32':
  1348. command_tcl_formatted = command_tcl_formatted.replace('\\', '/')
  1349. self.shell.exec_command(command_tcl_formatted, no_echo=True)
  1350. except Exception as ext:
  1351. print("ERROR: ", ext)
  1352. sys.exit(2)
  1353. if self.cmd_line_shellfile:
  1354. if self.cmd_line_headless != 1:
  1355. if self.ui.shell_dock.isHidden():
  1356. self.ui.shell_dock.show()
  1357. try:
  1358. with open(self.cmd_line_shellfile, "r") as myfile:
  1359. # if show_splash:
  1360. # self.splash.showMessage('%s: %ssec\n%s' % (
  1361. # _("Canvas initialization started.\n"
  1362. # "Canvas initialization finished in"), '%.2f' % self.used_time,
  1363. # _("Executing Tcl Script ...")),
  1364. # alignment=Qt.AlignBottom | Qt.AlignLeft,
  1365. # color=QtGui.QColor("gray"))
  1366. cmd_line_shellfile_text = myfile.read()
  1367. if self.cmd_line_headless != 1:
  1368. self.shell.exec_command(cmd_line_shellfile_text)
  1369. else:
  1370. self.shell.exec_command(cmd_line_shellfile_text, no_echo=True)
  1371. except Exception as ext:
  1372. print("ERROR: ", ext)
  1373. sys.exit(2)
  1374. # accept some type file as command line parameter: FlatCAM project, FlatCAM preferences or scripts
  1375. # the path/file_name must be enclosed in quotes if it contain spaces
  1376. if App.args:
  1377. self.args_at_startup.emit(App.args)
  1378. if self.defaults.old_defaults_found is True:
  1379. self.inform.emit('[WARNING_NOTCL] %s' % _("Found old default preferences files. "
  1380. "Please reboot the application to update."))
  1381. self.defaults.old_defaults_found = False
  1382. # ######################################### INIT FINISHED #######################################################
  1383. # #################################################################################################################
  1384. # #################################################################################################################
  1385. # #################################################################################################################
  1386. # #################################################################################################################
  1387. # #################################################################################################################
  1388. @staticmethod
  1389. def copy_and_overwrite(from_path, to_path):
  1390. """
  1391. From here:
  1392. https://stackoverflow.com/questions/12683834/how-to-copy-directory-recursively-in-python-and-overwrite-all
  1393. :param from_path: source path
  1394. :param to_path: destination path
  1395. :return: None
  1396. """
  1397. if os.path.exists(to_path):
  1398. shutil.rmtree(to_path)
  1399. try:
  1400. shutil.copytree(from_path, to_path)
  1401. except FileNotFoundError:
  1402. from_new_path = os.path.dirname(os.path.realpath(__file__)) + '\\flatcamGUI\\VisPyData\\data'
  1403. shutil.copytree(from_new_path, to_path)
  1404. def on_startup_args(self, args, silent=False):
  1405. """
  1406. This will process any arguments provided to the application at startup. Like trying to launch a file or project.
  1407. :param silent: when True it will not print messages on Tcl Shell and/or status bar
  1408. :param args: a list containing the application args at startup
  1409. :return: None
  1410. """
  1411. if args is not None:
  1412. args_to_process = args
  1413. else:
  1414. args_to_process = App.args
  1415. log.debug("Application was started with arguments: %s. Processing ..." % str(args_to_process))
  1416. for argument in args_to_process:
  1417. if '.FlatPrj'.lower() in argument.lower():
  1418. try:
  1419. project_name = str(argument)
  1420. if project_name == "":
  1421. if silent is False:
  1422. self.inform.emit(_("Cancelled."))
  1423. else:
  1424. # self.open_project(project_name)
  1425. run_from_arg = True
  1426. # self.worker_task.emit({'fcn': self.open_project,
  1427. # 'params': [project_name, run_from_arg]})
  1428. self.open_project(filename=project_name, run_from_arg=run_from_arg)
  1429. except Exception as e:
  1430. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1431. elif '.FlatConfig'.lower() in argument.lower():
  1432. try:
  1433. file_name = str(argument)
  1434. if file_name == "":
  1435. if silent is False:
  1436. self.inform.emit(_("Open Config file failed."))
  1437. else:
  1438. run_from_arg = True
  1439. # self.worker_task.emit({'fcn': self.open_config_file,
  1440. # 'params': [file_name, run_from_arg]})
  1441. self.open_config_file(file_name, run_from_arg=run_from_arg)
  1442. except Exception as e:
  1443. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1444. elif '.FlatScript'.lower() in argument.lower() or '.TCL'.lower() in argument.lower():
  1445. try:
  1446. file_name = str(argument)
  1447. if file_name == "":
  1448. if silent is False:
  1449. self.inform.emit(_("Open Script file failed."))
  1450. else:
  1451. if silent is False:
  1452. self.on_fileopenscript(name=file_name)
  1453. self.ui.plot_tab_area.setCurrentWidget(self.ui.plot_tab)
  1454. self.on_filerunscript(name=file_name)
  1455. except Exception as e:
  1456. log.debug("Could not open FlatCAM Script file as App parameter due: %s" % str(e))
  1457. elif 'quit'.lower() in argument.lower() or 'exit'.lower() in argument.lower():
  1458. log.debug("App.on_startup_args() --> Quit event.")
  1459. sys.exit()
  1460. elif 'save'.lower() in argument.lower():
  1461. log.debug("App.on_startup_args() --> Save event. App Defaults saved.")
  1462. self.preferencesUiManager.save_defaults()
  1463. else:
  1464. exc_list = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().split(',')
  1465. proc_arg = argument.lower()
  1466. for ext in exc_list:
  1467. proc_ext = ext.replace(' ', '')
  1468. proc_ext = '.%s' % proc_ext
  1469. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1470. file_name = str(argument)
  1471. if file_name == "":
  1472. if silent is False:
  1473. self.inform.emit(_("Open Excellon file failed."))
  1474. else:
  1475. self.on_fileopenexcellon(name=file_name)
  1476. return
  1477. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().split(',')
  1478. for ext in gco_list:
  1479. proc_ext = ext.replace(' ', '')
  1480. proc_ext = '.%s' % proc_ext
  1481. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1482. file_name = str(argument)
  1483. if file_name == "":
  1484. if silent is False:
  1485. self.inform.emit(_("Open GCode file failed."))
  1486. else:
  1487. self.on_fileopengcode(name=file_name)
  1488. return
  1489. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().split(',')
  1490. for ext in grb_list:
  1491. proc_ext = ext.replace(' ', '')
  1492. proc_ext = '.%s' % proc_ext
  1493. if proc_ext.lower() in proc_arg and proc_ext != '.':
  1494. file_name = str(argument)
  1495. if file_name == "":
  1496. if silent is False:
  1497. self.inform.emit(_("Open Gerber file failed."))
  1498. else:
  1499. self.on_fileopengerber(name=file_name)
  1500. return
  1501. # if it reached here without already returning then the app was registered with a file that it does not
  1502. # recognize therefore we must quit but take into consideration the app reboot from within, in that case
  1503. # the args_to_process will contain the path to the FlatCAM.exe (cx_freezed executable)
  1504. # for arg in args_to_process:
  1505. # if 'FlatCAM.exe' in arg:
  1506. # continue
  1507. # else:
  1508. # sys.exit(2)
  1509. def set_ui_title(self, name):
  1510. """
  1511. Sets the title of the main window.
  1512. :param name: String that store the project path and project name
  1513. :return: None
  1514. """
  1515. self.ui.setWindowTitle('FlatCAM %s %s - %s - [%s] %s' %
  1516. (self.version,
  1517. ('BETA' if self.beta else ''),
  1518. platform.architecture()[0],
  1519. self.engine,
  1520. name)
  1521. )
  1522. def on_app_restart(self):
  1523. # make sure that the Sys Tray icon is hidden before restart otherwise it will
  1524. # be left in the SySTray
  1525. try:
  1526. self.trayIcon.hide()
  1527. except Exception:
  1528. pass
  1529. fcTranslate.restart_program(app=self)
  1530. def clear_pool(self):
  1531. """
  1532. Clear the multiprocessing pool and calls garbage collector.
  1533. :return: None
  1534. """
  1535. self.pool.close()
  1536. self.pool = Pool()
  1537. self.pool_recreated.emit(self.pool)
  1538. gc.collect()
  1539. def install_tools(self):
  1540. """
  1541. This installs the FlatCAM tools (plugin-like) which reside in their own classes.
  1542. Instantiation of the Tools classes.
  1543. The order that the tools are installed is important as they can depend on each other install position.
  1544. :return: None
  1545. """
  1546. self.distance_tool = Distance(self)
  1547. self.distance_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance16.png'), pos=self.ui.menuedit,
  1548. before=self.ui.menueditorigin,
  1549. separator=False)
  1550. self.distance_min_tool = DistanceMin(self)
  1551. self.distance_min_tool.install(icon=QtGui.QIcon(self.resource_location + '/distance_min16.png'),
  1552. pos=self.ui.menuedit,
  1553. before=self.ui.menueditorigin,
  1554. separator=True)
  1555. self.dblsidedtool = DblSidedTool(self)
  1556. self.dblsidedtool.install(icon=QtGui.QIcon(self.resource_location + '/doubleside16.png'), separator=False)
  1557. self.cal_exc_tool = ToolCalibration(self)
  1558. self.cal_exc_tool.install(icon=QtGui.QIcon(self.resource_location + '/calibrate_16.png'), pos=self.ui.menutool,
  1559. before=self.dblsidedtool.menuAction,
  1560. separator=False)
  1561. self.align_objects_tool = AlignObjects(self)
  1562. self.align_objects_tool.install(icon=QtGui.QIcon(self.resource_location + '/align16.png'), separator=False)
  1563. self.edrills_tool = ToolExtractDrills(self)
  1564. self.edrills_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill16.png'), separator=True)
  1565. self.panelize_tool = Panelize(self)
  1566. self.panelize_tool.install(icon=QtGui.QIcon(self.resource_location + '/panelize16.png'))
  1567. self.film_tool = Film(self)
  1568. self.film_tool.install(icon=QtGui.QIcon(self.resource_location + '/film16.png'))
  1569. self.paste_tool = SolderPaste(self)
  1570. self.paste_tool.install(icon=QtGui.QIcon(self.resource_location + '/solderpastebis32.png'))
  1571. self.calculator_tool = ToolCalculator(self)
  1572. self.calculator_tool.install(icon=QtGui.QIcon(self.resource_location + '/calculator16.png'), separator=True)
  1573. self.sub_tool = ToolSub(self)
  1574. self.sub_tool.install(icon=QtGui.QIcon(self.resource_location + '/sub32.png'),
  1575. pos=self.ui.menutool, separator=True)
  1576. self.rules_tool = RulesCheck(self)
  1577. self.rules_tool.install(icon=QtGui.QIcon(self.resource_location + '/rules32.png'),
  1578. pos=self.ui.menutool, separator=False)
  1579. self.optimal_tool = ToolOptimal(self)
  1580. self.optimal_tool.install(icon=QtGui.QIcon(self.resource_location + '/open_excellon32.png'),
  1581. pos=self.ui.menutool, separator=True)
  1582. self.move_tool = ToolMove(self)
  1583. self.move_tool.install(icon=QtGui.QIcon(self.resource_location + '/move16.png'), pos=self.ui.menuedit,
  1584. before=self.ui.menueditorigin, separator=True)
  1585. self.cutout_tool = CutOut(self)
  1586. self.cutout_tool.install(icon=QtGui.QIcon(self.resource_location + '/cut16_bis.png'), pos=self.ui.menutool,
  1587. before=self.sub_tool.menuAction)
  1588. self.ncclear_tool = NonCopperClear(self)
  1589. self.ncclear_tool.install(icon=QtGui.QIcon(self.resource_location + '/ncc16.png'), pos=self.ui.menutool,
  1590. before=self.sub_tool.menuAction, separator=True)
  1591. self.paint_tool = ToolPaint(self)
  1592. self.paint_tool.install(icon=QtGui.QIcon(self.resource_location + '/paint16.png'), pos=self.ui.menutool,
  1593. before=self.sub_tool.menuAction, separator=True)
  1594. self.copper_thieving_tool = ToolCopperThieving(self)
  1595. self.copper_thieving_tool.install(icon=QtGui.QIcon(self.resource_location + '/copperfill32.png'),
  1596. pos=self.ui.menutool)
  1597. self.fiducial_tool = ToolFiducials(self)
  1598. self.fiducial_tool.install(icon=QtGui.QIcon(self.resource_location + '/fiducials_32.png'),
  1599. pos=self.ui.menutool)
  1600. self.qrcode_tool = QRCode(self)
  1601. self.qrcode_tool.install(icon=QtGui.QIcon(self.resource_location + '/qrcode32.png'),
  1602. pos=self.ui.menutool)
  1603. self.punch_tool = ToolPunchGerber(self)
  1604. self.punch_tool.install(icon=QtGui.QIcon(self.resource_location + '/punch32.png'), pos=self.ui.menutool)
  1605. self.invert_tool = ToolInvertGerber(self)
  1606. self.invert_tool.install(icon=QtGui.QIcon(self.resource_location + '/invert32.png'), pos=self.ui.menutool)
  1607. self.transform_tool = ToolTransform(self)
  1608. self.transform_tool.install(icon=QtGui.QIcon(self.resource_location + '/transform.png'),
  1609. pos=self.ui.menuoptions, separator=True)
  1610. self.properties_tool = Properties(self)
  1611. self.properties_tool.install(icon=QtGui.QIcon(self.resource_location + '/properties32.png'),
  1612. pos=self.ui.menuoptions)
  1613. self.pdf_tool = ToolPDF(self)
  1614. self.pdf_tool.install(icon=QtGui.QIcon(self.resource_location + '/pdf32.png'),
  1615. pos=self.ui.menufileimport,
  1616. separator=True)
  1617. self.image_tool = ToolImage(self)
  1618. self.image_tool.install(icon=QtGui.QIcon(self.resource_location + '/image32.png'),
  1619. pos=self.ui.menufileimport,
  1620. separator=True)
  1621. self.pcb_wizard_tool = PcbWizard(self)
  1622. self.pcb_wizard_tool.install(icon=QtGui.QIcon(self.resource_location + '/drill32.png'),
  1623. pos=self.ui.menufileimport)
  1624. self.log.debug("Tools are installed.")
  1625. def remove_tools(self):
  1626. """
  1627. Will remove all the actions in the Tool menu.
  1628. :return: None
  1629. """
  1630. for act in self.ui.menutool.actions():
  1631. self.ui.menutool.removeAction(act)
  1632. def init_tools(self):
  1633. """
  1634. Initialize the Tool tab in the notebook side of the central widget.
  1635. Remove the actions in the Tools menu.
  1636. Instantiate again the FlatCAM tools (plugins).
  1637. All this is required when changing the layout: standard, compact etc.
  1638. :return: None
  1639. """
  1640. log.debug("init_tools()")
  1641. # delete the data currently in the Tools Tab and the Tab itself
  1642. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1643. if widget is not None:
  1644. widget.deleteLater()
  1645. self.ui.notebook.removeTab(2)
  1646. # rebuild the Tools Tab
  1647. self.ui.tool_tab = QtWidgets.QWidget()
  1648. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1649. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1650. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  1651. self.ui.tool_scroll_area = VerticalScrollArea()
  1652. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1653. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1654. # first remove all of them
  1655. self.remove_tools()
  1656. # re-add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  1657. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon(self.resource_location + '/shell16.png'),
  1658. '&Command Line\tS')
  1659. self.ui.menutoolshell.triggered.connect(self.toggle_shell)
  1660. # third install all of them
  1661. try:
  1662. self.install_tools()
  1663. except AttributeError:
  1664. pass
  1665. self.log.debug("Tools are initialized.")
  1666. # def parse_system_fonts(self):
  1667. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1668. # 'params': []})
  1669. def connect_toolbar_signals(self):
  1670. """
  1671. Reconnect the signals to the actions in the toolbar.
  1672. This has to be done each time after the FlatCAM tools are removed/installed.
  1673. :return: None
  1674. """
  1675. # Toolbar
  1676. # self.ui.file_new_btn.triggered.connect(self.on_file_new)
  1677. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  1678. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  1679. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  1680. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  1681. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  1682. self.ui.replot_btn.triggered.connect(self.plot_all)
  1683. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  1684. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1685. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1686. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  1687. self.ui.newgrb_btn.triggered.connect(self.new_gerber_object)
  1688. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  1689. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  1690. self.ui.update_obj_btn.triggered.connect(lambda: self.editor2object())
  1691. self.ui.copy_btn.triggered.connect(self.on_copy_command)
  1692. self.ui.delete_btn.triggered.connect(self.on_delete)
  1693. self.ui.distance_btn.triggered.connect(lambda: self.distance_tool.run(toggle=True))
  1694. self.ui.distance_min_btn.triggered.connect(lambda: self.distance_min_tool.run(toggle=True))
  1695. self.ui.origin_btn.triggered.connect(self.on_set_origin)
  1696. self.ui.move2origin_btn.triggered.connect(self.on_move2origin)
  1697. self.ui.jmp_btn.triggered.connect(self.on_jump_to)
  1698. self.ui.locate_btn.triggered.connect(lambda: self.on_locate(obj=self.collection.get_active()))
  1699. self.ui.shell_btn.triggered.connect(self.toggle_shell)
  1700. self.ui.new_script_btn.triggered.connect(self.on_filenewscript)
  1701. self.ui.open_script_btn.triggered.connect(self.on_fileopenscript)
  1702. self.ui.run_script_btn.triggered.connect(self.on_filerunscript)
  1703. # Tools Toolbar Signals
  1704. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run(toggle=True))
  1705. self.ui.cal_btn.triggered.connect(lambda: self.cal_exc_tool.run(toggle=True))
  1706. self.ui.align_btn.triggered.connect(lambda: self.align_objects_tool.run(toggle=True))
  1707. self.ui.extract_btn.triggered.connect(lambda: self.edrills_tool.run(toggle=True))
  1708. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run(toggle=True))
  1709. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run(toggle=True))
  1710. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run(toggle=True))
  1711. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run(toggle=True))
  1712. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run(toggle=True))
  1713. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run(toggle=True))
  1714. self.ui.sub_btn.triggered.connect(lambda: self.sub_tool.run(toggle=True))
  1715. self.ui.rules_btn.triggered.connect(lambda: self.rules_tool.run(toggle=True))
  1716. self.ui.optimal_btn.triggered.connect(lambda: self.optimal_tool.run(toggle=True))
  1717. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run(toggle=True))
  1718. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run(toggle=True))
  1719. self.ui.qrcode_btn.triggered.connect(lambda: self.qrcode_tool.run(toggle=True))
  1720. self.ui.copperfill_btn.triggered.connect(lambda: self.copper_thieving_tool.run(toggle=True))
  1721. self.ui.fiducials_btn.triggered.connect(lambda: self.fiducial_tool.run(toggle=True))
  1722. self.ui.punch_btn.triggered.connect(lambda: self.punch_tool.run(toggle=True))
  1723. self.ui.invert_btn.triggered.connect(lambda: self.invert_tool.run(toggle=True))
  1724. def object2editor(self):
  1725. """
  1726. Send the current Geometry or Excellon object (if any) into the it's editor.
  1727. :return: None
  1728. """
  1729. self.report_usage("object2editor()")
  1730. # disable the objects menu as it may interfere with the Editors
  1731. self.ui.menuobjects.setDisabled(True)
  1732. edited_object = self.collection.get_active()
  1733. if isinstance(edited_object, GerberObject) or isinstance(edited_object, GeometryObject) or \
  1734. isinstance(edited_object, ExcellonObject):
  1735. pass
  1736. else:
  1737. self.inform.emit('[WARNING_NOTCL] %s' % _("Select a Geometry, Gerber or Excellon Object to edit."))
  1738. return
  1739. if isinstance(edited_object, GeometryObject):
  1740. # store the Geometry Editor Toolbar visibility before entering in the Editor
  1741. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  1742. # we set the notebook to hidden
  1743. # self.ui.splitter.setSizes([0, 1])
  1744. if edited_object.multigeo is True:
  1745. sel_rows = [item.row() for item in edited_object.ui.geo_tools_table.selectedItems()]
  1746. if len(sel_rows) > 1:
  1747. self.inform.emit('[WARNING_NOTCL] %s' %
  1748. _("Simultaneous editing of tools geometry in a MultiGeo Geometry "
  1749. "is not possible.\n"
  1750. "Edit only one geometry at a time."))
  1751. # determine the tool dia of the selected tool
  1752. selected_tooldia = float(edited_object.ui.geo_tools_table.item(sel_rows[0], 1).text())
  1753. # now find the key in the edited_object.tools that has this tooldia
  1754. multi_tool = 1
  1755. for tool in edited_object.tools:
  1756. if edited_object.tools[tool]['tooldia'] == selected_tooldia:
  1757. multi_tool = tool
  1758. break
  1759. self.geo_editor.edit_fcgeometry(edited_object, multigeo_tool=multi_tool)
  1760. else:
  1761. self.geo_editor.edit_fcgeometry(edited_object)
  1762. # set call source to the Editor we go into
  1763. self.call_source = 'geo_editor'
  1764. elif isinstance(edited_object, ExcellonObject):
  1765. # store the Excellon Editor Toolbar visibility before entering in the Editor
  1766. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  1767. if self.ui.splitter.sizes()[0] == 0:
  1768. self.ui.splitter.setSizes([1, 1])
  1769. self.exc_editor.edit_fcexcellon(edited_object)
  1770. # set call source to the Editor we go into
  1771. self.call_source = 'exc_editor'
  1772. elif isinstance(edited_object, GerberObject):
  1773. # store the Gerber Editor Toolbar visibility before entering in the Editor
  1774. self.grb_editor.toolbar_old_state = True if self.ui.grb_edit_toolbar.isVisible() else False
  1775. if self.ui.splitter.sizes()[0] == 0:
  1776. self.ui.splitter.setSizes([1, 1])
  1777. self.grb_editor.edit_fcgerber(edited_object)
  1778. # set call source to the Editor we go into
  1779. self.call_source = 'grb_editor'
  1780. # reset the following variables so the UI is built again after edit
  1781. edited_object.ui_build = False
  1782. edited_object.build_aperture_storage = False
  1783. # make sure that we can't select another object while in Editor Mode:
  1784. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1785. self.ui.project_frame.setDisabled(True)
  1786. # delete any selection shape that might be active as they are not relevant in Editor
  1787. self.delete_selection_shape()
  1788. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  1789. self.ui.plot_tab_area.protectTab(0)
  1790. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor is activated ..."))
  1791. self.should_we_save = True
  1792. def editor2object(self, cleanup=None):
  1793. """
  1794. Transfers the Geometry or Excellon from it's editor to the current object.
  1795. :return: None
  1796. """
  1797. self.report_usage("editor2object()")
  1798. # re-enable the objects menu that was disabled on entry in Editor mode
  1799. self.ui.menuobjects.setDisabled(False)
  1800. # do not update a geometry or excellon object unless it comes out of an editor
  1801. if self.call_source != 'app':
  1802. edited_obj = self.collection.get_active()
  1803. if cleanup is None:
  1804. msgbox = QtWidgets.QMessageBox()
  1805. msgbox.setText(_("Do you want to save the edited object?"))
  1806. msgbox.setWindowTitle(_("Close Editor"))
  1807. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  1808. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  1809. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  1810. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  1811. msgbox.setDefaultButton(bt_yes)
  1812. msgbox.exec_()
  1813. response = msgbox.clickedButton()
  1814. if response == bt_yes:
  1815. # clean the Tools Tab
  1816. self.ui.tool_scroll_area.takeWidget()
  1817. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1818. self.ui.notebook.setTabText(2, "Tool")
  1819. if isinstance(edited_obj, GeometryObject):
  1820. obj_type = "Geometry"
  1821. if cleanup is None:
  1822. self.geo_editor.update_fcgeometry(edited_obj)
  1823. # self.geo_editor.update_options(edited_obj)
  1824. self.geo_editor.deactivate()
  1825. # restore GUI to the Selected TAB
  1826. # Remove anything else in the GUI
  1827. self.ui.tool_scroll_area.takeWidget()
  1828. # update the geo object options so it is including the bounding box values
  1829. try:
  1830. xmin, ymin, xmax, ymax = edited_obj.bounds(flatten=True)
  1831. edited_obj.options['xmin'] = xmin
  1832. edited_obj.options['ymin'] = ymin
  1833. edited_obj.options['xmax'] = xmax
  1834. edited_obj.options['ymax'] = ymax
  1835. except AttributeError as e:
  1836. self.inform.emit('[WARNING] %s' % _("Object empty after edit."))
  1837. log.debug("App.editor2object() --> Geometry --> %s" % str(e))
  1838. edited_obj.build_ui()
  1839. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1840. elif isinstance(edited_obj, GerberObject):
  1841. obj_type = "Gerber"
  1842. if cleanup is None:
  1843. self.grb_editor.update_fcgerber()
  1844. self.grb_editor.update_options(edited_obj)
  1845. self.grb_editor.deactivate_grb_editor()
  1846. # delete the old object (the source object) if it was an empty one
  1847. try:
  1848. if len(edited_obj.solid_geometry) == 0:
  1849. old_name = edited_obj.options['name']
  1850. self.collection.set_active(old_name)
  1851. self.collection.delete_active()
  1852. except TypeError:
  1853. # if the solid_geometry is a single Polygon the len() will not work
  1854. # in any case, falling here means that we have something in the solid_geometry, even if only
  1855. # a single Polygon, therefore we pass this
  1856. pass
  1857. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1858. # restore GUI to the Selected TAB
  1859. # Remove anything else in the GUI
  1860. self.ui.selected_scroll_area.takeWidget()
  1861. elif isinstance(edited_obj, ExcellonObject):
  1862. obj_type = "Excellon"
  1863. if cleanup is None:
  1864. self.exc_editor.update_fcexcellon(edited_obj)
  1865. # self.exc_editor.update_options(edited_obj)
  1866. self.exc_editor.deactivate()
  1867. # restore GUI to the Selected TAB
  1868. # Remove anything else in the GUI
  1869. self.ui.tool_scroll_area.takeWidget()
  1870. # delete the old object (the source object) if it was an empty one
  1871. if len(edited_obj.drills) == 0 and len(edited_obj.slots) == 0:
  1872. old_name = edited_obj.options['name']
  1873. self.collection.delete_by_name(name=old_name)
  1874. self.inform.emit('[success] %s' % _("Editor exited. Editor content saved."))
  1875. else:
  1876. self.inform.emit('[WARNING_NOTCL] %s' %
  1877. _("Select a Gerber, Geometry or Excellon Object to update."))
  1878. return
  1879. self.inform.emit('[selected] %s %s' % (obj_type, _("is updated, returning to App...")))
  1880. elif response == bt_no:
  1881. # clean the Tools Tab
  1882. self.ui.tool_scroll_area.takeWidget()
  1883. self.ui.tool_scroll_area.setWidget(QtWidgets.QWidget())
  1884. self.ui.notebook.setTabText(2, "Tool")
  1885. self.inform.emit('[WARNING_NOTCL] %s' % _("Editor exited. Editor content was not saved."))
  1886. if isinstance(edited_obj, GeometryObject):
  1887. self.geo_editor.deactivate()
  1888. edited_obj.build_ui()
  1889. elif isinstance(edited_obj, GerberObject):
  1890. self.grb_editor.deactivate_grb_editor()
  1891. edited_obj.build_ui()
  1892. elif isinstance(edited_obj, ExcellonObject):
  1893. self.exc_editor.deactivate()
  1894. edited_obj.build_ui()
  1895. else:
  1896. self.inform.emit('[WARNING_NOTCL] %s' %
  1897. _("Select a Gerber, Geometry or Excellon Object to update."))
  1898. return
  1899. elif response == bt_cancel:
  1900. return
  1901. # edited_obj.set_ui(edited_obj.ui_type(decimals=self.decimals))
  1902. # edited_obj.build_ui()
  1903. # Switch notebook to Selected page
  1904. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  1905. else:
  1906. if isinstance(edited_obj, GeometryObject):
  1907. self.geo_editor.deactivate()
  1908. elif isinstance(edited_obj, GerberObject):
  1909. self.grb_editor.deactivate_grb_editor()
  1910. elif isinstance(edited_obj, ExcellonObject):
  1911. self.exc_editor.deactivate()
  1912. else:
  1913. self.inform.emit('[WARNING_NOTCL] %s' %
  1914. _("Select a Gerber, Geometry or Excellon Object to update."))
  1915. return
  1916. # if notebook is hidden we show it
  1917. if self.ui.splitter.sizes()[0] == 0:
  1918. self.ui.splitter.setSizes([1, 1])
  1919. # restore the call_source to app
  1920. self.call_source = 'app'
  1921. edited_obj.plot()
  1922. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  1923. self.ui.plot_tab_area.protectTab(0)
  1924. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  1925. # self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1926. self.ui.project_frame.setDisabled(False)
  1927. def get_last_folder(self):
  1928. """
  1929. Get the folder path from where the last file was opened.
  1930. :return: String, last opened folder path
  1931. """
  1932. return self.defaults["global_last_folder"]
  1933. def get_last_save_folder(self):
  1934. """
  1935. Get the folder path from where the last file was saved.
  1936. :return: String, last saved folder path
  1937. """
  1938. loc = self.defaults["global_last_save_folder"]
  1939. if loc is None:
  1940. loc = self.defaults["global_last_folder"]
  1941. if loc is None:
  1942. loc = os.path.dirname(__file__)
  1943. return loc
  1944. def report_usage(self, resource):
  1945. """
  1946. Increments usage counter for the given resource
  1947. in self.defaults['global_stats'].
  1948. :param resource: Name of the resource.
  1949. :return: None
  1950. """
  1951. if resource in self.defaults['global_stats']:
  1952. self.defaults['global_stats'][resource] += 1
  1953. else:
  1954. self.defaults['global_stats'][resource] = 1
  1955. def info(self, msg):
  1956. """
  1957. Informs the user. Normally on the status bar, optionally
  1958. also on the shell.
  1959. :param msg: Text to write.
  1960. :return: None
  1961. """
  1962. # Type of message in brackets at the beginning of the message.
  1963. match = re.search(r"\[(.*)\](.*)", msg)
  1964. if match:
  1965. level = match.group(1)
  1966. msg_ = match.group(2)
  1967. self.ui.fcinfo.set_status(str(msg_), level=level)
  1968. if level.lower() == "error":
  1969. self.shell_message(msg, error=True, show=True)
  1970. elif level.lower() == "warning":
  1971. self.shell_message(msg, warning=True, show=True)
  1972. elif level.lower() == "error_notcl":
  1973. self.shell_message(msg, error=True, show=False)
  1974. elif level.lower() == "warning_notcl":
  1975. self.shell_message(msg, warning=True, show=False)
  1976. elif level.lower() == "success":
  1977. self.shell_message(msg, success=True, show=False)
  1978. elif level.lower() == "selected":
  1979. self.shell_message(msg, selected=True, show=False)
  1980. else:
  1981. self.shell_message(msg, show=False)
  1982. else:
  1983. self.ui.fcinfo.set_status(str(msg), level="info")
  1984. # make sure that if the message is to clear the infobar with a space
  1985. # is not printed over and over on the shell
  1986. if msg != '':
  1987. self.shell_message(msg)
  1988. def restore_toolbar_view(self):
  1989. """
  1990. Some toolbars may be hidden by user and here we restore the state of the toolbars visibility that
  1991. was saved in the defaults dictionary.
  1992. :return: None
  1993. """
  1994. tb = self.defaults["global_toolbar_view"]
  1995. if tb & 1:
  1996. self.ui.toolbarfile.setVisible(True)
  1997. else:
  1998. self.ui.toolbarfile.setVisible(False)
  1999. if tb & 2:
  2000. self.ui.toolbargeo.setVisible(True)
  2001. else:
  2002. self.ui.toolbargeo.setVisible(False)
  2003. if tb & 4:
  2004. self.ui.toolbarview.setVisible(True)
  2005. else:
  2006. self.ui.toolbarview.setVisible(False)
  2007. if tb & 8:
  2008. self.ui.toolbartools.setVisible(True)
  2009. else:
  2010. self.ui.toolbartools.setVisible(False)
  2011. if tb & 16:
  2012. self.ui.exc_edit_toolbar.setVisible(True)
  2013. else:
  2014. self.ui.exc_edit_toolbar.setVisible(False)
  2015. if tb & 32:
  2016. self.ui.geo_edit_toolbar.setVisible(True)
  2017. else:
  2018. self.ui.geo_edit_toolbar.setVisible(False)
  2019. if tb & 64:
  2020. self.ui.grb_edit_toolbar.setVisible(True)
  2021. else:
  2022. self.ui.grb_edit_toolbar.setVisible(False)
  2023. if tb & 128:
  2024. self.ui.snap_toolbar.setVisible(True)
  2025. else:
  2026. self.ui.snap_toolbar.setVisible(False)
  2027. if tb & 256:
  2028. self.ui.toolbarshell.setVisible(True)
  2029. else:
  2030. self.ui.toolbarshell.setVisible(False)
  2031. def on_import_preferences(self):
  2032. """
  2033. Loads the application default settings from a saved file into
  2034. ``self.defaults`` dictionary.
  2035. :return: None
  2036. """
  2037. self.report_usage("on_import_preferences")
  2038. App.log.debug("App.on_import_preferences()")
  2039. # Show file chooser
  2040. filter_ = "Config File (*.FlatConfig);;All Files (*.*)"
  2041. try:
  2042. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2043. directory=self.data_path,
  2044. filter=filter_)
  2045. except TypeError:
  2046. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Import FlatCAM Preferences"),
  2047. filter=filter_)
  2048. filename = str(filename)
  2049. if filename == "":
  2050. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2051. return
  2052. # Load in the defaults from the chosen file
  2053. self.defaults.load(filename=filename)
  2054. self.on_preferences_edited()
  2055. self.inform.emit('[success] %s: %s' % (_("Imported Defaults from"), filename))
  2056. def on_export_preferences(self):
  2057. """
  2058. Save the defaults dictionary to a file.
  2059. :return: None
  2060. """
  2061. self.report_usage("on_export_preferences")
  2062. App.log.debug("on_export_preferences()")
  2063. defaults_file_content = None
  2064. # Show file chooser
  2065. date = str(datetime.today()).rpartition('.')[0]
  2066. date = ''.join(c for c in date if c not in ':-')
  2067. date = date.replace(' ', '_')
  2068. filter__ = "Config File .FlatConfig (*.FlatConfig);;All Files (*.*)"
  2069. try:
  2070. filename, _f = FCFileSaveDialog.get_saved_filename(
  2071. caption=_("Export FlatCAM Preferences"),
  2072. directory=self.data_path + '/preferences_' + date,
  2073. filter=filter__
  2074. )
  2075. except TypeError:
  2076. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export FlatCAM Preferences"), filter=filter__)
  2077. filename = str(filename)
  2078. if filename == "":
  2079. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2080. return
  2081. # Update options
  2082. self.preferencesUiManager.defaults_read_form()
  2083. self.defaults.propagate_defaults()
  2084. # Save update options
  2085. try:
  2086. self.defaults.write(filename=filename)
  2087. except Exception:
  2088. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2089. return
  2090. if self.defaults["global_open_style"] is False:
  2091. self.file_opened.emit("preferences", filename)
  2092. self.file_saved.emit("preferences", filename)
  2093. self.inform.emit('[success] %s: %s' % (_("Exported preferences to"), filename))
  2094. def save_to_file(self, content_to_save, txt_content):
  2095. """
  2096. Save something to a file.
  2097. :return: None
  2098. """
  2099. self.report_usage("save_to_file")
  2100. App.log.debug("save_to_file()")
  2101. self.date = str(datetime.today()).rpartition('.')[0]
  2102. self.date = ''.join(c for c in self.date if c not in ':-')
  2103. self.date = self.date.replace(' ', '_')
  2104. filter__ = "HTML File .html (*.html);;TXT File .txt (*.txt);;All Files (*.*)"
  2105. path_to_save = self.defaults["global_last_save_folder"] if\
  2106. self.defaults["global_last_save_folder"] is not None else self.data_path
  2107. try:
  2108. filename, _f = FCFileSaveDialog.get_saved_filename(
  2109. caption=_("Save to file"),
  2110. directory=path_to_save + '/file_' + self.date,
  2111. filter=filter__
  2112. )
  2113. except TypeError:
  2114. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save to file"), filter=filter__)
  2115. filename = str(filename)
  2116. if filename == "":
  2117. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  2118. return
  2119. else:
  2120. try:
  2121. with open(filename, 'w') as f:
  2122. ___ = f.read()
  2123. except PermissionError:
  2124. self.inform.emit('[WARNING] %s' %
  2125. _("Permission denied, saving not possible.\n"
  2126. "Most likely another app is holding the file open and not accessible."))
  2127. return
  2128. except IOError:
  2129. App.log.debug('Creating a new file ...')
  2130. f = open(filename, 'w')
  2131. f.close()
  2132. except Exception:
  2133. e = sys.exc_info()[0]
  2134. App.log.error("Could not load the file.")
  2135. App.log.error(str(e))
  2136. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not load the file."))
  2137. return
  2138. # Save content
  2139. if filename.rpartition('.')[2].lower() == 'html':
  2140. file_content = content_to_save
  2141. else:
  2142. file_content = txt_content
  2143. try:
  2144. with open(filename, "w") as f:
  2145. f.write(file_content)
  2146. except Exception:
  2147. self.inform.emit('[ERROR_NOTCL] %s %s' % (_("Failed to write defaults to file."), str(filename)))
  2148. return
  2149. self.inform.emit('[success] %s: %s' % (_("Exported file to"), filename))
  2150. def save_geometry(self, x, y, width, height, notebook_width):
  2151. """
  2152. Will save the application geometry and positions in the defaults discitionary to be restored at the next
  2153. launch of the application.
  2154. :param x: X position of the main window
  2155. :param y: Y position of the main window
  2156. :param width: width of the main window
  2157. :param height: height of the main window
  2158. :param notebook_width: the notebook width is adjustable so it get saved here, too.
  2159. :return: None
  2160. """
  2161. self.defaults["global_def_win_x"] = x
  2162. self.defaults["global_def_win_y"] = y
  2163. self.defaults["global_def_win_w"] = width
  2164. self.defaults["global_def_win_h"] = height
  2165. self.defaults["global_def_notebook_width"] = notebook_width
  2166. self.preferencesUiManager.save_defaults()
  2167. def restore_main_win_geom(self):
  2168. try:
  2169. self.ui.setGeometry(self.defaults["global_def_win_x"],
  2170. self.defaults["global_def_win_y"],
  2171. self.defaults["global_def_win_w"],
  2172. self.defaults["global_def_win_h"])
  2173. self.ui.splitter.setSizes([self.defaults["global_def_notebook_width"], 0])
  2174. except KeyError as e:
  2175. log.debug("App.restore_main_win_geom() --> %s" % str(e))
  2176. def message_dialog(self, title, message, kind="info"):
  2177. """
  2178. Builds and show a custom QMessageBox to be used in FlatCAM.
  2179. :param title: title of the QMessageBox
  2180. :param message: message to be displayed
  2181. :param kind: type of QMessageBox; will display a specific icon.
  2182. :return:
  2183. """
  2184. icon = {"info": QtWidgets.QMessageBox.Information,
  2185. "warning": QtWidgets.QMessageBox.Warning,
  2186. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  2187. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  2188. dlg.setText(message)
  2189. dlg.exec_()
  2190. def register_recent(self, kind, filename):
  2191. """
  2192. Will register the files opened into record dictionaries. The FlatCAM projects has it's own
  2193. dictionary.
  2194. :param kind: type of file that was opened
  2195. :param filename: the path and file name for the file that was opened
  2196. :return:
  2197. """
  2198. self.log.debug("register_recent()")
  2199. self.log.debug(" %s" % kind)
  2200. self.log.debug(" %s" % filename)
  2201. record = {'kind': str(kind), 'filename': str(filename)}
  2202. if record in self.recent:
  2203. return
  2204. if record in self.recent_projects:
  2205. return
  2206. if record['kind'] == 'project':
  2207. self.recent_projects.insert(0, record)
  2208. else:
  2209. self.recent.insert(0, record)
  2210. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  2211. self.recent.pop()
  2212. if len(self.recent_projects) > self.defaults['global_recent_limit']: # Limit reached
  2213. self.recent_projects.pop()
  2214. try:
  2215. f = open(self.data_path + '/recent.json', 'w')
  2216. except IOError:
  2217. App.log.error("Failed to open recent items file for writing.")
  2218. self.inform.emit('[ERROR_NOTCL] %s' %
  2219. _('Failed to open recent files file for writing.'))
  2220. return
  2221. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  2222. f.close()
  2223. try:
  2224. fp = open(self.data_path + '/recent_projects.json', 'w')
  2225. except IOError:
  2226. App.log.error("Failed to open recent items file for writing.")
  2227. self.inform.emit('[ERROR_NOTCL] %s' %
  2228. _('Failed to open recent projects file for writing.'))
  2229. return
  2230. json.dump(self.recent_projects, fp, default=to_dict, indent=2, sort_keys=True)
  2231. fp.close()
  2232. # Re-build the recent items menu
  2233. self.setup_recent_items()
  2234. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  2235. """
  2236. Creates a new specialized FlatCAMObj and attaches it to the application,
  2237. this is, updates the GUI accordingly, any other records and plots it.
  2238. This method is thread-safe.
  2239. Notes:
  2240. * If the name is in use, the self.collection will modify it
  2241. when appending it to the collection. There is no need to handle
  2242. name conflicts here.
  2243. :param kind: The kind of object to create. One of 'gerber', 'excellon', 'cncjob' and 'geometry'.
  2244. :type kind: str
  2245. :param name: Name for the object.
  2246. :type name: str
  2247. :param initialize: Function to run after creation of the object but before it is attached to the application.
  2248. The function is called with 2 parameters: the new object and the App instance.
  2249. :type initialize: function
  2250. :param active:
  2251. :param fit:
  2252. :param plot: If to plot the resulting object
  2253. :param autoselected: if the resulting object is autoselected in the Project tab and therefore in the
  2254. self.collection
  2255. :return: None
  2256. :rtype: None
  2257. """
  2258. App.log.debug("new_object()")
  2259. obj_plot = plot
  2260. obj_autoselected = autoselected
  2261. t0 = time.time() # Debug
  2262. # ## Create object
  2263. classdict = {
  2264. "gerber": GerberObject,
  2265. "excellon": ExcellonObject,
  2266. "cncjob": CNCJobObject,
  2267. "geometry": GeometryObject,
  2268. "script": ScriptObject,
  2269. "document": DocumentObject
  2270. }
  2271. App.log.debug("Calling object constructor...")
  2272. # Object creation/instantiation
  2273. obj = classdict[kind](name)
  2274. obj.units = self.options["units"]
  2275. # IMPORTANT
  2276. # The key names in defaults and options dictionary's are not random:
  2277. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  2278. # called here, the 'kind' followed by an underline. Above the App default values from self.defaults are
  2279. # copied to self.options. After that, below, depending on the type of
  2280. # object that is created, it will strip the name of the object and the underline (if the original key was
  2281. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  2282. # "toolchange"
  2283. for option in self.options:
  2284. if option.find(kind + "_") == 0:
  2285. oname = option[len(kind) + 1:]
  2286. obj.options[oname] = self.options[option]
  2287. obj.isHovering = False
  2288. obj.notHovering = True
  2289. # Initialize as per user request
  2290. # User must take care to implement initialize
  2291. # in a thread-safe way as is is likely that we
  2292. # have been invoked in a separate thread.
  2293. t1 = time.time()
  2294. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  2295. try:
  2296. return_value = initialize(obj, self)
  2297. except Exception as e:
  2298. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  2299. msg += _("Object ({kind}) failed because: {error} \n\n").format(kind=kind, error=str(e))
  2300. msg += traceback.format_exc()
  2301. self.inform.emit(msg)
  2302. return "fail"
  2303. t2 = time.time()
  2304. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  2305. if return_value == 'fail':
  2306. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  2307. return "fail"
  2308. # Check units and convert if necessary
  2309. # This condition CAN be true because initialize() can change obj.units
  2310. if self.options["units"].upper() != obj.units.upper():
  2311. self.inform.emit('%s: %s' % (_("Converting units to "), self.options["units"]))
  2312. obj.convert_units(self.options["units"])
  2313. t3 = time.time()
  2314. self.log.debug("%f seconds converting units." % (t3 - t2))
  2315. # Create the bounding box for the object and then add the results to the obj.options
  2316. # But not for Scripts or for Documents
  2317. if kind != 'document' and kind != 'script':
  2318. try:
  2319. xmin, ymin, xmax, ymax = obj.bounds()
  2320. obj.options['xmin'] = xmin
  2321. obj.options['ymin'] = ymin
  2322. obj.options['xmax'] = xmax
  2323. obj.options['ymax'] = ymax
  2324. except Exception as e:
  2325. log.warning("App.new_object() -> The object has no bounds properties. %s" % str(e))
  2326. return "fail"
  2327. try:
  2328. if kind == 'excellon':
  2329. obj.fill_color = self.defaults["excellon_plot_fill"]
  2330. obj.outline_color = self.defaults["excellon_plot_line"]
  2331. if kind == 'gerber':
  2332. obj.fill_color = self.defaults["gerber_plot_fill"]
  2333. obj.outline_color = self.defaults["gerber_plot_line"]
  2334. except Exception as e:
  2335. log.warning("App.new_object() -> setting colors error. %s" % str(e))
  2336. # update the KeyWords list with the name of the file
  2337. self.myKeywords.append(obj.options['name'])
  2338. log.debug("Moving new object back to main thread.")
  2339. # Move the object to the main thread and let the app know that it is available.
  2340. obj.moveToThread(self.main_thread)
  2341. self.object_created.emit(obj, obj_plot, obj_autoselected)
  2342. return obj
  2343. def new_excellon_object(self):
  2344. """
  2345. Creates a new, blank Excellon object.
  2346. :return: None
  2347. """
  2348. self.report_usage("new_excellon_object()")
  2349. self.new_object('excellon', 'new_exc', lambda x, y: None, plot=False)
  2350. def new_geometry_object(self):
  2351. """
  2352. Creates a new, blank and single-tool Geometry object.
  2353. :return: None
  2354. """
  2355. self.report_usage("new_geometry_object()")
  2356. def initialize(obj, app):
  2357. obj.multitool = False
  2358. self.new_object('geometry', 'new_geo', initialize, plot=False)
  2359. def new_gerber_object(self):
  2360. """
  2361. Creates a new, blank Gerber object.
  2362. :return: None
  2363. """
  2364. self.report_usage("new_gerber_object()")
  2365. def initialize(grb_obj, app):
  2366. grb_obj.multitool = False
  2367. grb_obj.source_file = []
  2368. grb_obj.multigeo = False
  2369. grb_obj.follow = False
  2370. grb_obj.apertures = {}
  2371. grb_obj.solid_geometry = []
  2372. try:
  2373. grb_obj.options['xmin'] = 0
  2374. grb_obj.options['ymin'] = 0
  2375. grb_obj.options['xmax'] = 0
  2376. grb_obj.options['ymax'] = 0
  2377. except KeyError:
  2378. pass
  2379. self.new_object('gerber', 'new_grb', initialize, plot=False)
  2380. def new_script_object(self, name=None, text=None):
  2381. """
  2382. Creates a new, blank TCL Script object.
  2383. :param name: a name for the new object
  2384. :param text: pass a source file to the newly created script to be loaded in it
  2385. :return: None
  2386. """
  2387. self.report_usage("new_script_object()")
  2388. if text is not None:
  2389. new_source_file = text
  2390. else:
  2391. commands_list = "# AddCircle, AddPolygon, AddPolyline, AddRectangle, AlignDrill, " \
  2392. "AlignDrillGrid, Bbox, Bounds, ClearShell, CopperClear,\n" \
  2393. "# Cncjob, Cutout, Delete, Drillcncjob, ExportDXF, ExportExcellon, ExportGcode,\n" \
  2394. "# ExportGerber, ExportSVG, Exteriors, Follow, GeoCutout, GeoUnion, GetNames,\n" \
  2395. "# GetSys, ImportSvg, Interiors, Isolate, JoinExcellon, JoinGeometry, " \
  2396. "ListSys, MillDrills,\n" \
  2397. "# MillSlots, Mirror, New, NewExcellon, NewGeometry, NewGerber, Nregions, " \
  2398. "Offset, OpenExcellon, OpenGCode, OpenGerber, OpenProject,\n" \
  2399. "# Options, Paint, Panelize, PlotAl, PlotObjects, SaveProject, " \
  2400. "SaveSys, Scale, SetActive, SetSys, SetOrigin, Skew, SubtractPoly,\n" \
  2401. "# SubtractRectangle, Version, WriteGCode\n"
  2402. new_source_file = '# %s\n' % _('CREATE A NEW FLATCAM TCL SCRIPT') + \
  2403. '# %s:\n' % _('TCL Tutorial is here') + \
  2404. '# https://www.tcl.tk/man/tcl8.5/tutorial/tcltutorial.html\n' + '\n\n' + \
  2405. '# %s:\n' % _("FlatCAM commands list")
  2406. new_source_file += commands_list + '\n'
  2407. def initialize(obj, app):
  2408. obj.source_file = deepcopy(new_source_file)
  2409. if name is None:
  2410. outname = 'new_script'
  2411. else:
  2412. outname = name
  2413. self.new_object('script', outname, initialize, plot=False)
  2414. def new_document_object(self):
  2415. """
  2416. Creates a new, blank Document object.
  2417. :return: None
  2418. """
  2419. self.report_usage("new_document_object()")
  2420. def initialize(obj, app):
  2421. obj.source_file = ""
  2422. self.new_object('document', 'new_document', initialize, plot=False)
  2423. def on_object_created(self, obj, plot, auto_select):
  2424. """
  2425. Event callback for object creation.
  2426. It will add the new object to the collection. After that it will plot the object in a threaded way
  2427. :param obj: The newly created FlatCAM object.
  2428. :param plot: if the newly create object t obe plotted
  2429. :param auto_select: if the newly created object to be autoselected after creation
  2430. :return: None
  2431. """
  2432. t0 = time.time() # DEBUG
  2433. self.log.debug("on_object_created()")
  2434. # The Collection might change the name if there is a collision
  2435. self.collection.append(obj)
  2436. # after adding the object to the collection always update the list of objects that are in the collection
  2437. self.all_objects_list = self.collection.get_list()
  2438. # self.inform.emit('[selected] %s created & selected: %s' %
  2439. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  2440. if obj.kind == 'gerber':
  2441. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2442. kind=obj.kind.capitalize(),
  2443. color='green',
  2444. name=str(obj.options['name']), tx=_("created/selected"))
  2445. )
  2446. elif obj.kind == 'excellon':
  2447. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2448. kind=obj.kind.capitalize(),
  2449. color='brown',
  2450. name=str(obj.options['name']), tx=_("created/selected"))
  2451. )
  2452. elif obj.kind == 'cncjob':
  2453. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2454. kind=obj.kind.capitalize(),
  2455. color='blue',
  2456. name=str(obj.options['name']), tx=_("created/selected"))
  2457. )
  2458. elif obj.kind == 'geometry':
  2459. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2460. kind=obj.kind.capitalize(),
  2461. color='red',
  2462. name=str(obj.options['name']), tx=_("created/selected"))
  2463. )
  2464. elif obj.kind == 'script':
  2465. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2466. kind=obj.kind.capitalize(),
  2467. color='orange',
  2468. name=str(obj.options['name']), tx=_("created/selected"))
  2469. )
  2470. elif obj.kind == 'document':
  2471. self.inform.emit('[selected] {kind} {tx}: <span style="color:{color};">{name}</span>'.format(
  2472. kind=obj.kind.capitalize(),
  2473. color='darkCyan',
  2474. name=str(obj.options['name']), tx=_("created/selected"))
  2475. )
  2476. # update the SHELL auto-completer model with the name of the new object
  2477. self.shell._edit.set_model_data(self.myKeywords)
  2478. if auto_select:
  2479. # select the just opened object but deselect the previous ones
  2480. self.collection.set_all_inactive()
  2481. self.collection.set_active(obj.options["name"])
  2482. else:
  2483. self.collection.set_all_inactive()
  2484. # here it is done the object plotting
  2485. def worker_task(t_obj):
  2486. with self.proc_container.new(_("Plotting")):
  2487. if isinstance(t_obj, CNCJobObject):
  2488. t_obj.plot(kind=self.defaults["cncjob_plot_kind"])
  2489. else:
  2490. t_obj.plot()
  2491. t1 = time.time() # DEBUG
  2492. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  2493. self.object_plotted.emit(t_obj)
  2494. # Send to worker
  2495. # self.worker.add_task(worker_task, [self])
  2496. if plot is True:
  2497. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  2498. def on_object_changed(self, obj):
  2499. """
  2500. Called whenever the geometry of the object was changed in some way.
  2501. This require the update of it's bounding values so it can be the selected on canvas.
  2502. Update the bounding box data from obj.options
  2503. :param obj: the object that was changed
  2504. :return: None
  2505. """
  2506. xmin, ymin, xmax, ymax = obj.bounds()
  2507. obj.options['xmin'] = xmin
  2508. obj.options['ymin'] = ymin
  2509. obj.options['xmax'] = xmax
  2510. obj.options['ymax'] = ymax
  2511. log.debug("Object changed, updating the bounding box data on self.options")
  2512. # delete the old selection shape
  2513. self.delete_selection_shape()
  2514. self.should_we_save = True
  2515. def on_object_plotted(self):
  2516. """
  2517. Callback called whenever the plotted object needs to be fit into the viewport (canvas)
  2518. :return: None
  2519. """
  2520. self.on_zoom_fit(None)
  2521. def on_about(self):
  2522. """
  2523. Displays the "about" dialog found in the Menu --> Help.
  2524. :return: None
  2525. """
  2526. self.report_usage("on_about")
  2527. version = self.version
  2528. version_date = self.version_date
  2529. beta = self.beta
  2530. class AboutDialog(QtWidgets.QDialog):
  2531. def __init__(self, app, parent=None):
  2532. QtWidgets.QDialog.__init__(self, parent)
  2533. self.app = app
  2534. # Icon and title
  2535. self.setWindowIcon(parent.app_icon)
  2536. self.setWindowTitle(_("About FlatCAM"))
  2537. self.resize(600, 200)
  2538. # self.setStyleSheet("background-image: url(share/flatcam_icon256.png); background-attachment: fixed")
  2539. # self.setStyleSheet(
  2540. # "border-image: url(share/flatcam_icon256.png) 0 0 0 0 stretch stretch; "
  2541. # "background-attachment: fixed"
  2542. # )
  2543. # bgimage = QtGui.QImage(self.resource_location + '/flatcam_icon256.png')
  2544. # s_bgimage = bgimage.scaled(QtCore.QSize(self.frameGeometry().width(), self.frameGeometry().height()))
  2545. # palette = QtGui.QPalette()
  2546. # palette.setBrush(10, QtGui.QBrush(bgimage)) # 10 = Windowrole
  2547. # self.setPalette(palette)
  2548. logo = QtWidgets.QLabel()
  2549. logo.setPixmap(QtGui.QPixmap(self.app.resource_location + '/flatcam_icon256.png'))
  2550. title = QtWidgets.QLabel(
  2551. "<font size=8><B>FlatCAM</B></font><BR>"
  2552. "{title}<BR>"
  2553. "<BR>"
  2554. "<BR>"
  2555. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\"><B>{devel}</B></a><BR>"
  2556. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\"><b>{down}</B></a><BR>"
  2557. "<a href = \"https://bitbucket.org/jpcgt/flatcam/issues?status=new&status=open/\">"
  2558. "<B>{issue}</B></a><BR>".format(
  2559. title=_("2D Computer-Aided Printed Circuit Board Manufacturing"),
  2560. devel=_("Development"),
  2561. down=_("DOWNLOAD"),
  2562. issue=_("Issue tracker"))
  2563. )
  2564. title.setOpenExternalLinks(True)
  2565. closebtn = QtWidgets.QPushButton(_("Close"))
  2566. tab_widget = QtWidgets.QTabWidget()
  2567. description_label = QtWidgets.QLabel(
  2568. "FlatCAM {version} {beta} ({date}) - {arch}<br>"
  2569. "<a href = \"http://flatcam.org/\">http://flatcam.org</a><br>".format(
  2570. version=version,
  2571. beta=('BETA' if beta else ''),
  2572. date=version_date,
  2573. arch=platform.architecture()[0])
  2574. )
  2575. description_label.setOpenExternalLinks(True)
  2576. lic_lbl_header = QtWidgets.QLabel(
  2577. '%s:<br>%s<br>' % (
  2578. _('Licensed under the MIT license'),
  2579. "<a href = \"http://www.opensource.org/licenses/mit-license.php\">"
  2580. "http://www.opensource.org/licenses/mit-license.php</a>"
  2581. )
  2582. )
  2583. lic_lbl_header.setOpenExternalLinks(True)
  2584. lic_lbl_body = QtWidgets.QLabel(
  2585. _(
  2586. 'Permission is hereby granted, free of charge, to any person obtaining a copy\n'
  2587. 'of this software and associated documentation files (the "Software"), to deal\n'
  2588. 'in the Software without restriction, including without limitation the rights\n'
  2589. 'to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n'
  2590. 'copies of the Software, and to permit persons to whom the Software is\n'
  2591. 'furnished to do so, subject to the following conditions:\n\n'
  2592. 'The above copyright notice and this permission notice shall be included in\n'
  2593. 'all copies or substantial portions of the Software.\n\n'
  2594. 'THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n'
  2595. 'IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n'
  2596. 'FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n'
  2597. 'AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n'
  2598. 'LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n'
  2599. 'OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN\n'
  2600. 'THE SOFTWARE.'
  2601. )
  2602. )
  2603. attributions_label = QtWidgets.QLabel(
  2604. _(
  2605. 'Some of the icons used are from the following sources:<br>'
  2606. '<div>Icons by <a href="https://www.flaticon.com/authors/freepik" '
  2607. 'title="Freepik">Freepik</a> from <a href="https://www.flaticon.com/" '
  2608. 'title="Flaticon">www.flaticon.com</a></div>'
  2609. '<div>Icons by <a target="_blank" href="https://icons8.com">Icons8</a></div>'
  2610. 'Icons by <a href="http://www.onlinewebfonts.com">oNline Web Fonts</a>'
  2611. )
  2612. )
  2613. attributions_label.setOpenExternalLinks(True)
  2614. # layouts
  2615. layout1 = QtWidgets.QVBoxLayout()
  2616. layout1_1 = QtWidgets.QHBoxLayout()
  2617. layout1_2 = QtWidgets.QHBoxLayout()
  2618. layout2 = QtWidgets.QHBoxLayout()
  2619. layout3 = QtWidgets.QHBoxLayout()
  2620. self.setLayout(layout1)
  2621. layout1.addLayout(layout1_1)
  2622. layout1.addLayout(layout1_2)
  2623. layout1.addLayout(layout2)
  2624. layout1.addLayout(layout3)
  2625. layout1_1.addStretch()
  2626. layout1_1.addWidget(description_label)
  2627. layout1_2.addWidget(tab_widget)
  2628. self.splash_tab = QtWidgets.QWidget()
  2629. self.splash_tab.setObjectName("splash_about")
  2630. self.splash_tab_layout = QtWidgets.QHBoxLayout(self.splash_tab)
  2631. self.splash_tab_layout.setContentsMargins(2, 2, 2, 2)
  2632. tab_widget.addTab(self.splash_tab, _("Splash"))
  2633. self.programmmers_tab = QtWidgets.QWidget()
  2634. self.programmmers_tab.setObjectName("programmers_about")
  2635. self.programmmers_tab_layout = QtWidgets.QVBoxLayout(self.programmmers_tab)
  2636. self.programmmers_tab_layout.setContentsMargins(2, 2, 2, 2)
  2637. tab_widget.addTab(self.programmmers_tab, _("Programmers"))
  2638. self.translators_tab = QtWidgets.QWidget()
  2639. self.translators_tab.setObjectName("translators_about")
  2640. self.translators_tab_layout = QtWidgets.QVBoxLayout(self.translators_tab)
  2641. self.translators_tab_layout.setContentsMargins(2, 2, 2, 2)
  2642. tab_widget.addTab(self.translators_tab, _("Translators"))
  2643. self.license_tab = QtWidgets.QWidget()
  2644. self.license_tab.setObjectName("license_about")
  2645. self.license_tab_layout = QtWidgets.QVBoxLayout(self.license_tab)
  2646. self.license_tab_layout.setContentsMargins(2, 2, 2, 2)
  2647. tab_widget.addTab(self.license_tab, _("License"))
  2648. self.attributions_tab = QtWidgets.QWidget()
  2649. self.attributions_tab.setObjectName("attributions_about")
  2650. self.attributions_tab_layout = QtWidgets.QVBoxLayout(self.attributions_tab)
  2651. self.attributions_tab_layout.setContentsMargins(2, 2, 2, 2)
  2652. tab_widget.addTab(self.attributions_tab, _("Attributions"))
  2653. self.splash_tab_layout.addWidget(logo, stretch=0)
  2654. self.splash_tab_layout.addWidget(title, stretch=1)
  2655. pal = QtGui.QPalette()
  2656. pal.setColor(QtGui.QPalette.Background, Qt.white)
  2657. self.prog_grid_lay = QtWidgets.QGridLayout()
  2658. self.prog_grid_lay.setHorizontalSpacing(20)
  2659. self.prog_grid_lay.setColumnStretch(0, 0)
  2660. self.prog_grid_lay.setColumnStretch(2, 1)
  2661. prog_widget = QtWidgets.QWidget()
  2662. prog_widget.setLayout(self.prog_grid_lay)
  2663. prog_scroll = QtWidgets.QScrollArea()
  2664. prog_scroll.setWidget(prog_widget)
  2665. prog_scroll.setWidgetResizable(True)
  2666. prog_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2667. prog_scroll.setPalette(pal)
  2668. self.programmmers_tab_layout.addWidget(prog_scroll)
  2669. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Programmer")), 0, 0)
  2670. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Status")), 0, 1)
  2671. self.prog_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 2)
  2672. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Juan Pablo Caram"), 1, 0)
  2673. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Program Author"), 1, 1)
  2674. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<>"), 1, 2)
  2675. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Denis Hayrullin"), 2, 0)
  2676. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Kamil Sopko"), 3, 0)
  2677. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 0)
  2678. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % _("BETA Maintainer >= 2019")), 4, 1)
  2679. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 2)
  2680. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 5, 0)
  2681. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Alex Lazar"), 6, 0)
  2682. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Matthieu Berthomé"), 7, 0)
  2683. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Evans"), 8, 0)
  2684. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Victor Benso"), 9, 0)
  2685. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 10, 0)
  2686. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Barnaby Walters"), 11, 0)
  2687. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jørn Sandvik Nilsson"), 12, 0)
  2688. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lei Zheng"), 13, 0)
  2689. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marco A Quezada"), 14, 0)
  2690. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 12, 0)
  2691. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Cedric Dussud"), 15, 0)
  2692. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Hemingway"), 16, 0)
  2693. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Damian Wrobel"), 17, 0)
  2694. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Daniel Sallin"), 18, 0)
  2695. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 19, 0)
  2696. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Bruno Vunderl"), 20, 0)
  2697. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Gonzalo Lopez"), 21, 0)
  2698. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jakob Staudt"), 22, 0)
  2699. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Mike Smith"), 23, 0)
  2700. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 24, 0)
  2701. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Lubos Medovarsky"), 25, 0)
  2702. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Steve Martina"), 26, 0)
  2703. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Thomas Duffin"), 27, 0)
  2704. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 28, 0)
  2705. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 29, 0)
  2706. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Chris Breneman"), 30, 0)
  2707. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Eric Varsanyi"), 31, 0)
  2708. self.prog_grid_lay.addWidget(QtWidgets.QLabel(''), 34, 0)
  2709. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Idechix"), 100, 0)
  2710. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@SM"), 101, 0)
  2711. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@grbf"), 102, 0)
  2712. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@Symonty"), 103, 0)
  2713. self.prog_grid_lay.addWidget(QtWidgets.QLabel('%s' % "@mgix"), 104, 0)
  2714. self.translator_grid_lay = QtWidgets.QGridLayout()
  2715. self.translator_grid_lay.setColumnStretch(0, 0)
  2716. self.translator_grid_lay.setColumnStretch(1, 0)
  2717. self.translator_grid_lay.setColumnStretch(2, 1)
  2718. self.translator_grid_lay.setColumnStretch(3, 0)
  2719. # trans_widget = QtWidgets.QWidget()
  2720. # trans_widget.setLayout(self.translator_grid_lay)
  2721. # self.translators_tab_layout.addWidget(trans_widget)
  2722. # self.translators_tab_layout.addStretch()
  2723. trans_widget = QtWidgets.QWidget()
  2724. trans_widget.setLayout(self.translator_grid_lay)
  2725. trans_scroll = QtWidgets.QScrollArea()
  2726. trans_scroll.setWidget(trans_widget)
  2727. trans_scroll.setWidgetResizable(True)
  2728. trans_scroll.setFrameShape(QtWidgets.QFrame.NoFrame)
  2729. trans_scroll.setPalette(pal)
  2730. self.translators_tab_layout.addWidget(trans_scroll)
  2731. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Language")), 0, 0)
  2732. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Translator")), 0, 1)
  2733. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("Corrections")), 0, 2)
  2734. self.translator_grid_lay.addWidget(QtWidgets.QLabel('<b>%s</b>' % _("E-mail")), 0, 3)
  2735. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "BR - Portuguese"), 1, 0)
  2736. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Carlos Stein"), 1, 1)
  2737. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<carlos.stein@gmail.com>"), 1, 3)
  2738. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "French"), 2, 0)
  2739. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 2, 1)
  2740. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 2, 2)
  2741. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 2, 3)
  2742. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "German"), 3, 0)
  2743. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 3, 1)
  2744. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Jens Karstedt, Detlef Eckardt"), 3, 2)
  2745. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 3, 3)
  2746. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Romanian"), 4, 0)
  2747. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu"), 4, 1)
  2748. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<marius_adrian@yahoo.com>"), 4, 3)
  2749. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Russian"), 5, 0)
  2750. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Andrey Kultyapov"), 5, 1)
  2751. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "<camellan@yandex.ru>"), 5, 3)
  2752. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Spanish"), 6, 0)
  2753. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % "Marius Stanciu (Google-Tr)"), 6, 1)
  2754. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % ""), 6, 2)
  2755. self.translator_grid_lay.addWidget(QtWidgets.QLabel('%s' % " "), 6, 3)
  2756. self.translator_grid_lay.setColumnStretch(0, 0)
  2757. self.translators_tab_layout.addStretch()
  2758. self.license_tab_layout.addWidget(lic_lbl_header)
  2759. self.license_tab_layout.addWidget(lic_lbl_body)
  2760. self.license_tab_layout.addStretch()
  2761. self.attributions_tab_layout.addWidget(attributions_label)
  2762. self.attributions_tab_layout.addStretch()
  2763. layout3.addStretch()
  2764. layout3.addWidget(closebtn)
  2765. closebtn.clicked.connect(self.accept)
  2766. AboutDialog(app=self, parent=self.ui).exec_()
  2767. def install_bookmarks(self, book_dict=None):
  2768. """
  2769. Install the bookmarks actions in the Help menu -> Bookmarks
  2770. :param book_dict: a dict having the actions text as keys and the weblinks as the values
  2771. :return: None
  2772. """
  2773. if book_dict is None:
  2774. self.defaults["global_bookmarks"].update(
  2775. {
  2776. '1': ['FlatCAM', "http://flatcam.org"],
  2777. '2': ['Backup Site', ""]
  2778. }
  2779. )
  2780. else:
  2781. self.defaults["global_bookmarks"].clear()
  2782. self.defaults["global_bookmarks"].update(book_dict)
  2783. # first try to disconnect if somehow they get connected from elsewhere
  2784. for act in self.ui.menuhelp_bookmarks.actions():
  2785. try:
  2786. act.triggered.disconnect()
  2787. except TypeError:
  2788. pass
  2789. # clear all actions except the last one who is the Bookmark manager
  2790. if act is self.ui.menuhelp_bookmarks.actions()[-1]:
  2791. pass
  2792. else:
  2793. self.ui.menuhelp_bookmarks.removeAction(act)
  2794. bm_limit = int(self.defaults["global_bookmarks_limit"])
  2795. if self.defaults["global_bookmarks"]:
  2796. # order the self.defaults["global_bookmarks"] dict keys by the value as integer
  2797. # the whole convoluted things is because when serializing the self.defaults (on app close or save)
  2798. # the JSON is first making the keys as strings (therefore I have to use strings too
  2799. # or do the conversion :(
  2800. # )
  2801. # and it is ordering them (actually I want that to make the defaults easy to search within) but making
  2802. # the '10' entry jsut after '1' therefore ordering as strings
  2803. sorted_bookmarks = sorted(list(self.defaults["global_bookmarks"].items())[:bm_limit],
  2804. key=lambda x: int(x[0]))
  2805. for entry, bookmark in sorted_bookmarks:
  2806. title = bookmark[0]
  2807. weblink = bookmark[1]
  2808. act = QtWidgets.QAction(parent=self.ui.menuhelp_bookmarks)
  2809. act.setText(title)
  2810. act.setIcon(QtGui.QIcon(self.resource_location + '/link16.png'))
  2811. # from here: https://stackoverflow.com/questions/20390323/pyqt-dynamic-generate-qmenu-action-and-connect
  2812. if title == 'Backup Site' and weblink == "":
  2813. act.triggered.connect(self.on_backup_site)
  2814. else:
  2815. act.triggered.connect(lambda sig, link=weblink: webbrowser.open(link))
  2816. self.ui.menuhelp_bookmarks.insertAction(self.ui.menuhelp_bookmarks_manager, act)
  2817. self.ui.menuhelp_bookmarks_manager.triggered.connect(self.on_bookmarks_manager)
  2818. def on_bookmarks_manager(self):
  2819. """
  2820. Adds the bookmark manager in a Tab in Plot Area
  2821. :return:
  2822. """
  2823. for idx in range(self.ui.plot_tab_area.count()):
  2824. if self.ui.plot_tab_area.tabText(idx) == _("Bookmarks Manager"):
  2825. # there can be only one instance of Bookmark Manager at one time
  2826. return
  2827. # BookDialog(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui).exec_()
  2828. self.book_dialog_tab = BookmarkManager(app=self, storage=self.defaults["global_bookmarks"], parent=self.ui)
  2829. # add the tab if it was closed
  2830. self.ui.plot_tab_area.addTab(self.book_dialog_tab, _("Bookmarks Manager"))
  2831. # delete the absolute and relative position and messages in the infobar
  2832. self.ui.position_label.setText("")
  2833. self.ui.rel_position_label.setText("")
  2834. # Switch plot_area to preferences page
  2835. self.ui.plot_tab_area.setCurrentWidget(self.book_dialog_tab)
  2836. def on_backup_site(self):
  2837. msgbox = QtWidgets.QMessageBox()
  2838. msgbox.setText(_("This entry will resolve to another website if:\n\n"
  2839. "1. FlatCAM.org website is down\n"
  2840. "2. Someone forked FlatCAM project and wants to point\n"
  2841. "to his own website\n\n"
  2842. "If you can't get any informations about FlatCAM beta\n"
  2843. "use the YouTube channel link from the Help menu."))
  2844. msgbox.setWindowTitle(_("Alternative website"))
  2845. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/globe16.png'))
  2846. bt_yes = msgbox.addButton(_('Close'), QtWidgets.QMessageBox.YesRole)
  2847. msgbox.setDefaultButton(bt_yes)
  2848. msgbox.exec_()
  2849. # response = msgbox.clickedButton()
  2850. def on_file_savedefaults(self):
  2851. """
  2852. Callback for menu item File->Save Defaults. Saves application default options
  2853. ``self.defaults`` to current_defaults.FlatConfig.
  2854. :return: None
  2855. """
  2856. self.preferencesUiManager.save_defaults()
  2857. def save_toolbar_view(self):
  2858. """
  2859. Will save the toolbar view state to the defaults
  2860. :return: None
  2861. """
  2862. # Save the toolbar view
  2863. tb_status = 0
  2864. if self.ui.toolbarfile.isVisible():
  2865. tb_status += 1
  2866. if self.ui.toolbargeo.isVisible():
  2867. tb_status += 2
  2868. if self.ui.toolbarview.isVisible():
  2869. tb_status += 4
  2870. if self.ui.toolbartools.isVisible():
  2871. tb_status += 8
  2872. if self.ui.exc_edit_toolbar.isVisible():
  2873. tb_status += 16
  2874. if self.ui.geo_edit_toolbar.isVisible():
  2875. tb_status += 32
  2876. if self.ui.grb_edit_toolbar.isVisible():
  2877. tb_status += 64
  2878. if self.ui.snap_toolbar.isVisible():
  2879. tb_status += 128
  2880. if self.ui.toolbarshell.isVisible():
  2881. tb_status += 256
  2882. self.defaults["global_toolbar_view"] = tb_status
  2883. def final_save(self):
  2884. """
  2885. Callback for doing a preferences save to file whenever the application is about to quit.
  2886. If the project has changes, it will ask the user to save the project.
  2887. :return: None
  2888. """
  2889. if self.save_in_progress:
  2890. self.inform.emit('[WARNING_NOTCL] %s' % _("Application is saving the project. Please wait ..."))
  2891. return
  2892. if self.should_we_save and self.collection.get_list():
  2893. msgbox = QtWidgets.QMessageBox()
  2894. msgbox.setText(_("There are files/objects modified in FlatCAM. "
  2895. "\n"
  2896. "Do you want to Save the project?"))
  2897. msgbox.setWindowTitle(_("Save changes"))
  2898. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  2899. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  2900. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  2901. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  2902. msgbox.setDefaultButton(bt_yes)
  2903. msgbox.exec_()
  2904. response = msgbox.clickedButton()
  2905. if response == bt_yes:
  2906. try:
  2907. self.trayIcon.hide()
  2908. except Exception:
  2909. pass
  2910. self.on_file_saveprojectas(use_thread=True, quit_action=True)
  2911. elif response == bt_no:
  2912. try:
  2913. self.trayIcon.hide()
  2914. except Exception:
  2915. pass
  2916. self.quit_application()
  2917. elif response == bt_cancel:
  2918. return
  2919. else:
  2920. try:
  2921. self.trayIcon.hide()
  2922. except Exception:
  2923. pass
  2924. self.quit_application()
  2925. def quit_application(self):
  2926. """
  2927. Called (as a pyslot or not) when the application is quit.
  2928. :return: None
  2929. """
  2930. self.preferencesUiManager.save_defaults(silent=True)
  2931. log.debug("App.quit_application() --> App Defaults saved.")
  2932. if self.cmd_line_headless != 1:
  2933. # save app state to file
  2934. stgs = QSettings("Open Source", "FlatCAM")
  2935. stgs.setValue('saved_gui_state', self.ui.saveState())
  2936. stgs.setValue('maximized_gui', self.ui.isMaximized())
  2937. stgs.setValue(
  2938. 'language',
  2939. self.ui.general_defaults_form.general_app_group.language_cb.get_value()
  2940. )
  2941. stgs.setValue(
  2942. 'notebook_font_size',
  2943. self.ui.general_defaults_form.general_app_set_group.notebook_font_size_spinner.get_value()
  2944. )
  2945. stgs.setValue(
  2946. 'axis_font_size',
  2947. self.ui.general_defaults_form.general_app_set_group.axis_font_size_spinner.get_value()
  2948. )
  2949. stgs.setValue(
  2950. 'textbox_font_size',
  2951. self.ui.general_defaults_form.general_app_set_group.textbox_font_size_spinner.get_value()
  2952. )
  2953. stgs.setValue('toolbar_lock', self.ui.lock_action.isChecked())
  2954. stgs.setValue(
  2955. 'machinist',
  2956. 1 if self.ui.general_defaults_form.general_app_set_group.machinist_cb.get_value() else 0
  2957. )
  2958. # This will write the setting to the platform specific storage.
  2959. del stgs
  2960. log.debug("App.quit_application() --> App UI state saved.")
  2961. # try to quit the QThread that run ArgsThread class
  2962. try:
  2963. self.th.quit()
  2964. except Exception as e:
  2965. log.debug("App.quit_application() --> %s" % str(e))
  2966. # try to quit the Socket opened by ArgsThread class
  2967. try:
  2968. self.new_launch.listener.close()
  2969. except Exception as err:
  2970. log.debug("App.quit_application() --> %s" % str(err))
  2971. # quit app by signalling for self.kill_app() method
  2972. # self.close_app_signal.emit()
  2973. QtWidgets.qApp.quit()
  2974. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2975. # we use the following command
  2976. # sys.exit(0)
  2977. os._exit(0) # fix to work with Python 3.8
  2978. @staticmethod
  2979. def kill_app():
  2980. # QtCore.QCoreApplication.quit()
  2981. QtWidgets.qApp.quit()
  2982. # When the main event loop is not started yet in which case the qApp.quit() will do nothing
  2983. # we use the following command
  2984. sys.exit(0)
  2985. def on_portable_checked(self, state):
  2986. """
  2987. Callback called when the checkbox in Preferences GUI is checked.
  2988. It will set the application as portable by creating the preferences and recent files in the
  2989. 'config' folder found in the FlatCAM installation folder.
  2990. :param state: boolean, the state of the checkbox when clicked/checked
  2991. :return:
  2992. """
  2993. line_no = 0
  2994. data = None
  2995. if sys.platform != 'win32':
  2996. # this won't work in Linux or MacOS
  2997. return
  2998. # test if the app was frozen and choose the path for the configuration file
  2999. if getattr(sys, "frozen", False) is True:
  3000. current_data_path = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) + '\\config'
  3001. else:
  3002. current_data_path = os.path.dirname(os.path.realpath(__file__)) + '\\config'
  3003. config_file = current_data_path + '\\configuration.txt'
  3004. try:
  3005. with open(config_file, 'r') as f:
  3006. try:
  3007. data = f.readlines()
  3008. except Exception as e:
  3009. log.debug('App.__init__() -->%s' % str(e))
  3010. return
  3011. except FileNotFoundError:
  3012. pass
  3013. for line in data:
  3014. line = line.strip('\n')
  3015. param = str(line).rpartition('=')
  3016. if param[0] == 'portable':
  3017. break
  3018. line_no += 1
  3019. if state:
  3020. data[line_no] = 'portable=True\n'
  3021. # create the new defauults files
  3022. # create current_defaults.FlatConfig file if there is none
  3023. try:
  3024. f = open(current_data_path + '/current_defaults.FlatConfig')
  3025. f.close()
  3026. except IOError:
  3027. App.log.debug('Creating empty current_defaults.FlatConfig')
  3028. f = open(current_data_path + '/current_defaults.FlatConfig', 'w')
  3029. json.dump({}, f)
  3030. f.close()
  3031. # create factory_defaults.FlatConfig file if there is none
  3032. try:
  3033. f = open(current_data_path + '/factory_defaults.FlatConfig')
  3034. f.close()
  3035. except IOError:
  3036. App.log.debug('Creating empty factory_defaults.FlatConfig')
  3037. f = open(current_data_path + '/factory_defaults.FlatConfig', 'w')
  3038. json.dump({}, f)
  3039. f.close()
  3040. try:
  3041. f = open(current_data_path + '/recent.json')
  3042. f.close()
  3043. except IOError:
  3044. App.log.debug('Creating empty recent.json')
  3045. f = open(current_data_path + '/recent.json', 'w')
  3046. json.dump([], f)
  3047. f.close()
  3048. try:
  3049. fp = open(current_data_path + '/recent_projects.json')
  3050. fp.close()
  3051. except IOError:
  3052. App.log.debug('Creating empty recent_projects.json')
  3053. fp = open(current_data_path + '/recent_projects.json', 'w')
  3054. json.dump([], fp)
  3055. fp.close()
  3056. # save the current defaults to the new defaults file
  3057. self.preferencesUiManager.save_defaults(silent=True, data_path=current_data_path)
  3058. else:
  3059. data[line_no] = 'portable=False\n'
  3060. with open(config_file, 'w') as f:
  3061. f.writelines(data)
  3062. def on_register_files(self, obj_type=None):
  3063. """
  3064. Called whenever there is a need to register file extensions with FlatCAM.
  3065. Works only in Windows and should be called only when FlatCAM is run in Windows.
  3066. :param obj_type: the type of object to be register for.
  3067. Can be: 'gerber', 'excellon' or 'gcode'. 'geometry' is not used for the moment.
  3068. :return: None
  3069. """
  3070. log.debug("Manufacturing files extensions are registered with FlatCAM.")
  3071. new_reg_path = 'Software\\Classes\\'
  3072. # find if the current user is admin
  3073. try:
  3074. is_admin = os.getuid() == 0
  3075. except AttributeError:
  3076. is_admin = ctypes.windll.shell32.IsUserAnAdmin() == 1
  3077. if is_admin is True:
  3078. root_path = winreg.HKEY_LOCAL_MACHINE
  3079. else:
  3080. root_path = winreg.HKEY_CURRENT_USER
  3081. # create the keys
  3082. def set_reg(name, root_path, new_reg_path, value):
  3083. try:
  3084. winreg.CreateKey(root_path, new_reg_path)
  3085. with winreg.OpenKey(root_path, new_reg_path, 0, winreg.KEY_WRITE) as registry_key:
  3086. winreg.SetValueEx(registry_key, name, 0, winreg.REG_SZ, value)
  3087. return True
  3088. except WindowsError:
  3089. return False
  3090. # delete key in registry
  3091. def delete_reg(root_path, reg_path, key_to_del):
  3092. key_to_del_path = reg_path + key_to_del
  3093. try:
  3094. winreg.DeleteKey(root_path, key_to_del_path)
  3095. return True
  3096. except WindowsError:
  3097. return False
  3098. if obj_type is None or obj_type == 'excellon':
  3099. exc_list = \
  3100. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3101. exc_list = [x for x in exc_list if x != '']
  3102. # register all keys in the Preferences window
  3103. for ext in exc_list:
  3104. new_k = new_reg_path + '.%s' % ext
  3105. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3106. # and unregister those that are no longer in the Preferences windows but are in the file
  3107. for ext in self.defaults["fa_excellon"].replace(' ', '').split(','):
  3108. if ext not in exc_list:
  3109. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3110. # now write the updated extensions to the self.defaults
  3111. # new_ext = ''
  3112. # for ext in exc_list:
  3113. # new_ext = new_ext + ext + ', '
  3114. # self.defaults["fa_excellon"] = new_ext
  3115. self.inform.emit('[success] %s' % _("Selected Excellon file extensions registered with FlatCAM."))
  3116. if obj_type is None or obj_type == 'gcode':
  3117. gco_list = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3118. gco_list = [x for x in gco_list if x != '']
  3119. # register all keys in the Preferences window
  3120. for ext in gco_list:
  3121. new_k = new_reg_path + '.%s' % ext
  3122. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3123. # and unregister those that are no longer in the Preferences windows but are in the file
  3124. for ext in self.defaults["fa_gcode"].replace(' ', '').split(','):
  3125. if ext not in gco_list:
  3126. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3127. # now write the updated extensions to the self.defaults
  3128. # new_ext = ''
  3129. # for ext in gco_list:
  3130. # new_ext = new_ext + ext + ', '
  3131. # self.defaults["fa_gcode"] = new_ext
  3132. self.inform.emit('[success] %s' %
  3133. _("Selected GCode file extensions registered with FlatCAM."))
  3134. if obj_type is None or obj_type == 'gerber':
  3135. grb_list = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3136. grb_list = [x for x in grb_list if x != '']
  3137. # register all keys in the Preferences window
  3138. for ext in grb_list:
  3139. new_k = new_reg_path + '.%s' % ext
  3140. set_reg('', root_path=root_path, new_reg_path=new_k, value='FlatCAM')
  3141. # and unregister those that are no longer in the Preferences windows but are in the file
  3142. for ext in self.defaults["fa_gerber"].replace(' ', '').split(','):
  3143. if ext not in grb_list:
  3144. delete_reg(root_path=root_path, reg_path=new_reg_path, key_to_del='.%s' % ext)
  3145. # now write the updated extensions to the self.defaults
  3146. # new_ext = ''
  3147. # for ext in grb_list:
  3148. # new_ext = new_ext + ext + ', '
  3149. # self.defaults["fa_gerber"] = new_ext
  3150. self.inform.emit('[success] %s' %
  3151. _("Selected Gerber file extensions registered with FlatCAM."))
  3152. def add_extension(self, ext_type):
  3153. """
  3154. Add a file extension to the list for a specific object
  3155. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3156. :return:
  3157. """
  3158. if ext_type == 'excellon':
  3159. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3160. if new_ext == '':
  3161. return
  3162. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3163. if new_ext in old_val:
  3164. return
  3165. old_val.append(new_ext)
  3166. old_val.sort()
  3167. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3168. if ext_type == 'gcode':
  3169. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3170. if new_ext == '':
  3171. return
  3172. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3173. if new_ext in old_val:
  3174. return
  3175. old_val.append(new_ext)
  3176. old_val.sort()
  3177. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3178. if ext_type == 'gerber':
  3179. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3180. if new_ext == '':
  3181. return
  3182. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3183. if new_ext in old_val:
  3184. return
  3185. old_val.append(new_ext)
  3186. old_val.sort()
  3187. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3188. if ext_type == 'keyword':
  3189. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3190. if new_kw == '':
  3191. return
  3192. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3193. if new_kw in old_val:
  3194. return
  3195. old_val.append(new_kw)
  3196. old_val.sort()
  3197. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3198. # update the self.myKeywords so the model is updated
  3199. self.autocomplete_kw_list = \
  3200. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3201. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3202. self.shell._edit.set_model_data(self.myKeywords)
  3203. def del_extension(self, ext_type):
  3204. """
  3205. Remove a file extension from the list for a specific object
  3206. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3207. :return:
  3208. """
  3209. if ext_type == 'excellon':
  3210. new_ext = self.ui.util_defaults_form.fa_excellon_group.ext_entry.get_value()
  3211. if new_ext == '':
  3212. return
  3213. old_val = self.ui.util_defaults_form.fa_excellon_group.exc_list_text.get_value().replace(' ', '').split(',')
  3214. if new_ext not in old_val:
  3215. return
  3216. old_val.remove(new_ext)
  3217. old_val.sort()
  3218. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(old_val))
  3219. if ext_type == 'gcode':
  3220. new_ext = self.ui.util_defaults_form.fa_gcode_group.ext_entry.get_value()
  3221. if new_ext == '':
  3222. return
  3223. old_val = self.ui.util_defaults_form.fa_gcode_group.gco_list_text.get_value().replace(' ', '').split(',')
  3224. if new_ext not in old_val:
  3225. return
  3226. old_val.remove(new_ext)
  3227. old_val.sort()
  3228. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(old_val))
  3229. if ext_type == 'gerber':
  3230. new_ext = self.ui.util_defaults_form.fa_gerber_group.ext_entry.get_value()
  3231. if new_ext == '':
  3232. return
  3233. old_val = self.ui.util_defaults_form.fa_gerber_group.grb_list_text.get_value().replace(' ', '').split(',')
  3234. if new_ext not in old_val:
  3235. return
  3236. old_val.remove(new_ext)
  3237. old_val.sort()
  3238. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(old_val))
  3239. if ext_type == 'keyword':
  3240. new_kw = self.ui.util_defaults_form.kw_group.kw_entry.get_value()
  3241. if new_kw == '':
  3242. return
  3243. old_val = self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3244. if new_kw not in old_val:
  3245. return
  3246. old_val.remove(new_kw)
  3247. old_val.sort()
  3248. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(old_val))
  3249. # update the self.myKeywords so the model is updated
  3250. self.autocomplete_kw_list = \
  3251. self.ui.util_defaults_form.kw_group.kw_list_text.get_value().replace(' ', '').split(',')
  3252. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3253. self.shell._edit.set_model_data(self.myKeywords)
  3254. def restore_extensions(self, ext_type):
  3255. """
  3256. Restore all file extensions associations with FlatCAM, for a specific object
  3257. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3258. :return:
  3259. """
  3260. if ext_type == 'excellon':
  3261. # don't add 'txt' to the associations (too many files are .txt and not Excellon) but keep it in the list
  3262. # for the ability to open Excellon files with .txt extension
  3263. new_exc_list = deepcopy(self.exc_list)
  3264. try:
  3265. new_exc_list.remove('txt')
  3266. except ValueError:
  3267. pass
  3268. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value(', '.join(new_exc_list))
  3269. if ext_type == 'gcode':
  3270. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value(', '.join(self.gcode_list))
  3271. if ext_type == 'gerber':
  3272. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value(', '.join(self.grb_list))
  3273. if ext_type == 'keyword':
  3274. self.ui.util_defaults_form.kw_group.kw_list_text.set_value(', '.join(self.default_keywords))
  3275. # update the self.myKeywords so the model is updated
  3276. self.autocomplete_kw_list = self.default_keywords
  3277. self.myKeywords = self.tcl_commands_list + self.autocomplete_kw_list + self.tcl_keywords
  3278. self.shell._edit.set_model_data(self.myKeywords)
  3279. def delete_all_extensions(self, ext_type):
  3280. """
  3281. Delete all file extensions associations with FlatCAM, for a specific object
  3282. :param ext_type: type of FlatCAM object: excellon, gerber, geometry and then 'not FlatCAM object' keyword
  3283. :return:
  3284. """
  3285. if ext_type == 'excellon':
  3286. self.ui.util_defaults_form.fa_excellon_group.exc_list_text.set_value('')
  3287. if ext_type == 'gcode':
  3288. self.ui.util_defaults_form.fa_gcode_group.gco_list_text.set_value('')
  3289. if ext_type == 'gerber':
  3290. self.ui.util_defaults_form.fa_gerber_group.grb_list_text.set_value('')
  3291. if ext_type == 'keyword':
  3292. self.ui.util_defaults_form.kw_group.kw_list_text.set_value('')
  3293. # update the self.myKeywords so the model is updated
  3294. self.myKeywords = self.tcl_commands_list + self.tcl_keywords
  3295. self.shell._edit.set_model_data(self.myKeywords)
  3296. def on_edit_join(self, name=None):
  3297. """
  3298. Callback for Edit->Join. Joins the selected geometry objects into
  3299. a new one.
  3300. :return: None
  3301. """
  3302. self.report_usage("on_edit_join()")
  3303. obj_name_single = str(name) if name else "Combo_SingleGeo"
  3304. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  3305. geo_type_set = set()
  3306. objs = self.collection.get_selected()
  3307. if len(objs) < 2:
  3308. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3309. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3310. return 'fail'
  3311. for obj in objs:
  3312. geo_type_set.add(obj.multigeo)
  3313. # if len(geo_type_list) == 1 means that all list elements are the same
  3314. if len(geo_type_set) != 1:
  3315. self.inform.emit('[ERROR] %s' %
  3316. _("Failed join. The Geometry objects are of different types.\n"
  3317. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  3318. "convert from one to another and retry joining \n"
  3319. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  3320. "the result may not be what was expected. \n"
  3321. "Check the generated GCODE."))
  3322. return
  3323. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  3324. if True in geo_type_set:
  3325. def initialize(geo_obj, app):
  3326. GeometryObject.merge(self, geo_list=objs, geo_final=geo_obj, multigeo=True)
  3327. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3328. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3329. for v in geo_obj.tools.values():
  3330. v['data']['name'] = obj_name_multi
  3331. self.new_object("geometry", obj_name_multi, initialize)
  3332. else:
  3333. def initialize(geo_obj, app):
  3334. GeometryObject.merge(self, geo_list=objs, geo_final=geo_obj, multigeo=False)
  3335. app.inform.emit('[success] %s.' % _("Geometry merging finished"))
  3336. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  3337. for v in geo_obj.tools.values():
  3338. v['data']['name'] = obj_name_single
  3339. self.new_object("geometry", obj_name_single, initialize)
  3340. self.should_we_save = True
  3341. def on_edit_join_exc(self):
  3342. """
  3343. Callback for Edit->Join Excellon. Joins the selected Excellon objects into
  3344. a new Excellon.
  3345. :return: None
  3346. """
  3347. self.report_usage("on_edit_join_exc()")
  3348. objs = self.collection.get_selected()
  3349. for obj in objs:
  3350. if not isinstance(obj, ExcellonObject):
  3351. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Excellon joining works only on Excellon objects."))
  3352. return
  3353. if len(objs) < 2:
  3354. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3355. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3356. return 'fail'
  3357. def initialize(exc_obj, app):
  3358. ExcellonObject.merge(self, exc_list=objs, exc_final=exc_obj)
  3359. app.inform.emit('[success] %s.' % _("Excellon merging finished"))
  3360. self.new_object("excellon", 'Combo_Excellon', initialize)
  3361. self.should_we_save = True
  3362. def on_edit_join_grb(self):
  3363. """
  3364. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  3365. a new Gerber object.
  3366. :return: None
  3367. """
  3368. self.report_usage("on_edit_join_grb()")
  3369. objs = self.collection.get_selected()
  3370. for obj in objs:
  3371. if not isinstance(obj, GerberObject):
  3372. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Gerber joining works only on Gerber objects."))
  3373. return
  3374. if len(objs) < 2:
  3375. self.inform.emit('[ERROR_NOTCL] %s: %d' %
  3376. (_("At least two objects are required for join. Objects currently selected"), len(objs)))
  3377. return 'fail'
  3378. def initialize(grb_obj, app):
  3379. GerberObject.merge(self, grb_list=objs, grb_final=grb_obj)
  3380. app.inform.emit('[success] %s.' % _("Gerber merging finished"))
  3381. self.new_object("gerber", 'Combo_Gerber', initialize)
  3382. self.should_we_save = True
  3383. def on_convert_singlegeo_to_multigeo(self):
  3384. """
  3385. Called for converting a Geometry object from single-geo to multi-geo.
  3386. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3387. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3388. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3389. the solid-geometry of that tool.
  3390. :return: None
  3391. """
  3392. self.report_usage("on_convert_singlegeo_to_multigeo()")
  3393. obj = self.collection.get_active()
  3394. if obj is None:
  3395. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Select a Geometry Object and try again."))
  3396. return
  3397. if not isinstance(obj, GeometryObject):
  3398. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Expected a GeometryObject, got"), type(obj)))
  3399. return
  3400. obj.multigeo = True
  3401. for tooluid, dict_value in obj.tools.items():
  3402. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  3403. if not isinstance(obj.solid_geometry, list):
  3404. obj.solid_geometry = [obj.solid_geometry]
  3405. obj.solid_geometry[:] = []
  3406. obj.plot()
  3407. self.should_we_save = True
  3408. self.inform.emit('[success] %s' % _("A Geometry object was converted to MultiGeo type."))
  3409. def on_convert_multigeo_to_singlegeo(self):
  3410. """
  3411. Called for converting a Geometry object from multi-geo to single-geo.
  3412. Single-geo Geometry objects store their geometry data into self.solid_geometry.
  3413. Multi-geo Geometry objects store their geometry data into the self.tools dictionary, each key (a tool actually)
  3414. having as a value another dictionary. This value dictionary has one of it's keys 'solid_geometry' which holds
  3415. the solid-geometry of that tool.
  3416. :return: None
  3417. """
  3418. self.report_usage("on_convert_multigeo_to_singlegeo()")
  3419. obj = self.collection.get_active()
  3420. if obj is None:
  3421. self.inform.emit('[ERROR_NOTCL] %s' %
  3422. _("Failed. Select a Geometry Object and try again."))
  3423. return
  3424. if not isinstance(obj, GeometryObject):
  3425. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  3426. (_("Expected a GeometryObject, got"), type(obj)))
  3427. return
  3428. obj.multigeo = False
  3429. total_solid_geometry = []
  3430. for tooluid, dict_value in obj.tools.items():
  3431. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  3432. # clear the original geometry
  3433. dict_value['solid_geometry'][:] = []
  3434. obj.solid_geometry = deepcopy(total_solid_geometry)
  3435. obj.plot()
  3436. self.should_we_save = True
  3437. self.inform.emit('[success] %s' %
  3438. _("A Geometry object was converted to SingleGeo type."))
  3439. def on_defaults_dict_change(self, field):
  3440. """
  3441. Called whenever a key changed in the self.defaults dictionary. It will set the required GUI element in the
  3442. Edit -> Preferences tab window.
  3443. :param field: the key of the self.defaults dictionary that was changed.
  3444. :return: None
  3445. """
  3446. self.preferencesUiManager.defaults_write_form(field)
  3447. if field == "units":
  3448. self.set_screen_units(self.defaults['units'])
  3449. def set_screen_units(self, units):
  3450. """
  3451. Set the FlatCAM units on the status bar.
  3452. :param units: the new measuring units to be displayed in FlatCAM's status bar.
  3453. :return: None
  3454. """
  3455. self.ui.units_label.setText("[" + units.lower() + "]")
  3456. def on_toggle_units_click(self):
  3457. try:
  3458. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.disconnect()
  3459. except (TypeError, AttributeError):
  3460. pass
  3461. if self.defaults["units"] == 'MM':
  3462. self.ui.general_defaults_form.general_app_group.units_radio.set_value("IN")
  3463. else:
  3464. self.ui.general_defaults_form.general_app_group.units_radio.set_value("MM")
  3465. self.on_toggle_units(no_pref=True)
  3466. self.ui.general_defaults_form.general_app_group.units_radio.activated_custom.connect(
  3467. lambda: self.on_toggle_units(no_pref=False))
  3468. def on_toggle_units(self, no_pref=False):
  3469. """
  3470. Callback for the Units radio-button change in the Preferences tab.
  3471. Changes the application's default units adn for the project too.
  3472. If changing the project's units, the change propagates to all of
  3473. the objects in the project.
  3474. :return: None
  3475. """
  3476. self.report_usage("on_toggle_units")
  3477. if self.toggle_units_ignore:
  3478. return
  3479. new_units = self.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  3480. # If option is the same, then ignore
  3481. if new_units == self.defaults["units"].upper():
  3482. self.log.debug("on_toggle_units(): Same as defaults, so ignoring.")
  3483. return
  3484. # Options to scale
  3485. dimensions = ['gerber_isotooldia', 'gerber_noncoppermargin', 'gerber_bboxmargin', "gerber_isooverlap",
  3486. "gerber_editor_newsize", "gerber_editor_lin_pitch", "gerber_editor_buff_f",
  3487. 'excellon_cutz', 'excellon_travelz', "excellon_toolchangexy", 'excellon_offset',
  3488. 'excellon_feedrate', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  3489. 'excellon_tooldia', 'excellon_slot_tooldia', 'excellon_endz', 'excellon_endxy',
  3490. "excellon_feedrate_probe",
  3491. "excellon_z_pdepth", "excellon_editor_newdia", "excellon_editor_lin_pitch",
  3492. "excellon_editor_slot_lin_pitch",
  3493. 'geometry_cutz', "geometry_depthperpass", 'geometry_travelz', 'geometry_feedrate',
  3494. 'geometry_feedrate_rapid', "geometry_toolchangez", "geometry_feedrate_z",
  3495. "geometry_toolchangexy", 'geometry_cnctooldia', 'geometry_endz', 'geometry_endxy',
  3496. "geometry_z_pdepth",
  3497. "geometry_feedrate_probe", "geometry_startz",
  3498. 'cncjob_tooldia',
  3499. 'tools_paintmargin', 'tools_painttooldia', 'tools_paintoverlap',
  3500. "tools_ncctools", "tools_nccoverlap", "tools_nccmargin", "tools_ncccutz", "tools_ncctipdia",
  3501. "tools_nccnewdia",
  3502. "tools_2sided_drilldia", "tools_film_boundary",
  3503. "tools_cutouttooldia", 'tools_cutoutmargin', 'tools_cutoutgapsize',
  3504. "tools_panelize_constrainx", "tools_panelize_constrainy",
  3505. "tools_calc_vshape_tip_dia", "tools_calc_vshape_cut_z",
  3506. "tools_transform_skew_x", "tools_transform_skew_y", "tools_transform_offset_x",
  3507. "tools_transform_offset_y",
  3508. "tools_solderpaste_tools", "tools_solderpaste_new", "tools_solderpaste_z_start",
  3509. "tools_solderpaste_z_dispense", "tools_solderpaste_z_stop", "tools_solderpaste_z_travel",
  3510. "tools_solderpaste_z_toolchange", "tools_solderpaste_xy_toolchange", "tools_solderpaste_frxy",
  3511. "tools_solderpaste_frz", "tools_solderpaste_frz_dispense",
  3512. "tools_cr_trace_size_val", "tools_cr_c2c_val", "tools_cr_c2o_val", "tools_cr_s2s_val",
  3513. "tools_cr_s2sm_val", "tools_cr_s2o_val", "tools_cr_sm2sm_val", "tools_cr_ri_val",
  3514. "tools_cr_h2h_val", "tools_cr_dh_val", "tools_fiducials_dia", "tools_fiducials_margin",
  3515. "tools_fiducials_line_thickness",
  3516. "tools_copper_thieving_clearance", "tools_copper_thieving_margin",
  3517. "tools_copper_thieving_dots_dia", "tools_copper_thieving_dots_spacing",
  3518. "tools_copper_thieving_squares_size", "tools_copper_thieving_squares_spacing",
  3519. "tools_copper_thieving_lines_size", "tools_copper_thieving_lines_spacing",
  3520. "tools_copper_thieving_rb_margin", "tools_copper_thieving_rb_thickness",
  3521. 'global_gridx', 'global_gridy', 'global_snap_max', "global_tolerance",
  3522. 'global_tpdf_bmargin', 'global_tpdf_tmargin', 'global_tpdf_rmargin', 'global_tpdf_lmargin']
  3523. def scale_defaults(sfactor):
  3524. for dim in dimensions:
  3525. if dim == 'excellon_toolchangexy':
  3526. coordinates = self.defaults["excellon_toolchangexy"].split(",")
  3527. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3528. coords_xy[0] *= sfactor
  3529. coords_xy[1] *= sfactor
  3530. self.defaults['excellon_toolchangexy'] = "%.*f, %.*f" % (self.decimals, coords_xy[0],
  3531. self.decimals, coords_xy[1])
  3532. elif dim == 'geometry_toolchangexy':
  3533. coordinates = self.defaults["geometry_toolchangexy"].split(",")
  3534. coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3535. coords_xy[0] *= sfactor
  3536. coords_xy[1] *= sfactor
  3537. self.defaults['geometry_toolchangexy'] = "%.*f, %.*f" % (self.decimals, coords_xy[0],
  3538. self.decimals, coords_xy[1])
  3539. elif dim == 'excellon_endxy':
  3540. coordinates = self.defaults["excellon_endxy"].split(",")
  3541. end_coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3542. end_coords_xy[0] *= sfactor
  3543. end_coords_xy[1] *= sfactor
  3544. self.defaults['excellon_endxy'] = "%.*f, %.*f" % (self.decimals, end_coords_xy[0],
  3545. self.decimals, end_coords_xy[1])
  3546. elif dim == 'geometry_endxy':
  3547. coordinates = self.defaults["geometry_endxy"].split(",")
  3548. end_coords_xy = [float(eval(a)) for a in coordinates if a != '']
  3549. end_coords_xy[0] *= sfactor
  3550. end_coords_xy[1] *= sfactor
  3551. self.defaults['geometry_endxy'] = "%.*f, %.*f" % (self.decimals, end_coords_xy[0],
  3552. self.decimals, end_coords_xy[1])
  3553. elif dim == 'geometry_cnctooldia':
  3554. if type(self.defaults["geometry_cnctooldia"]) == float:
  3555. tools_diameters = [self.defaults["geometry_cnctooldia"]]
  3556. else:
  3557. try:
  3558. tools_string = self.defaults["geometry_cnctooldia"].split(",")
  3559. tools_diameters = [eval(a) for a in tools_string if a != '']
  3560. except Exception as e:
  3561. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3562. continue
  3563. self.defaults['geometry_cnctooldia'] = ''
  3564. for t in range(len(tools_diameters)):
  3565. tools_diameters[t] *= sfactor
  3566. self.defaults['geometry_cnctooldia'] += "%.*f," % (self.decimals, tools_diameters[t])
  3567. elif dim == 'tools_ncctools':
  3568. if type(self.defaults["tools_ncctools"]) == float:
  3569. ncctools = [self.defaults["tools_ncctools"]]
  3570. else:
  3571. try:
  3572. tools_string = self.defaults["tools_ncctools"].split(",")
  3573. ncctools = [eval(a) for a in tools_string if a != '']
  3574. except Exception as e:
  3575. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3576. continue
  3577. self.defaults['tools_ncctools'] = ''
  3578. for t in range(len(ncctools)):
  3579. ncctools[t] *= sfactor
  3580. self.defaults['tools_ncctools'] += "%.*f," % (self.decimals, ncctools[t])
  3581. elif dim == 'tools_solderpaste_tools':
  3582. if type(self.defaults["tools_solderpaste_tools"]) == float:
  3583. sptools = [self.defaults["tools_solderpaste_tools"]]
  3584. else:
  3585. try:
  3586. tools_string = self.defaults["tools_solderpaste_tools"].split(",")
  3587. sptools = [eval(a) for a in tools_string if a != '']
  3588. except Exception as e:
  3589. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3590. continue
  3591. self.defaults['tools_solderpaste_tools'] = ""
  3592. for t in range(len(sptools)):
  3593. sptools[t] *= sfactor
  3594. self.defaults['tools_solderpaste_tools'] += "%.*f," % (self.decimals, sptools[t])
  3595. elif dim == 'tools_solderpaste_xy_toolchange':
  3596. try:
  3597. coordinates = self.defaults["tools_solderpaste_xy_toolchange"].split(",")
  3598. sp_coords = [float(eval(a)) for a in coordinates if a != '']
  3599. sp_coords[0] *= sfactor
  3600. sp_coords[1] *= sfactor
  3601. self.defaults['tools_solderpaste_xy_toolchange'] = "%.*f, %.*f" % (self.decimals, sp_coords[0],
  3602. self.decimals, sp_coords[1])
  3603. except Exception as e:
  3604. log.debug("App.on_toggle_units().scale_options() --> %s" % str(e))
  3605. continue
  3606. elif dim == 'global_gridx' or dim == 'global_gridy':
  3607. if new_units == 'IN':
  3608. try:
  3609. val = float(self.defaults[dim]) * sfactor
  3610. except Exception as e:
  3611. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3612. continue
  3613. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  3614. else:
  3615. try:
  3616. val = float(self.defaults[dim]) * sfactor
  3617. except Exception as e:
  3618. log.debug('App.on_toggle_units().scale_defaults() --> %s' % str(e))
  3619. continue
  3620. self.defaults[dim] = float('%.*f' % (self.decimals, val))
  3621. else:
  3622. if self.defaults[dim]:
  3623. try:
  3624. val = float(self.defaults[dim]) * sfactor
  3625. except Exception as e:
  3626. log.debug('App.on_toggle_units().scale_defaults() --> Value: %s %s' % (str(dim), str(e)))
  3627. continue
  3628. self.defaults[dim] = val
  3629. # The scaling factor depending on choice of units.
  3630. factor = 25.4 if new_units == 'MM' else 1 / 25.4
  3631. # Changing project units. Warn user.
  3632. msgbox = QtWidgets.QMessageBox()
  3633. msgbox.setWindowTitle(_("Toggle Units"))
  3634. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/toggle_units32.png'))
  3635. msgbox.setText(_("Changing the units of the project\n"
  3636. "will scale all objects.\n\n"
  3637. "Do you want to continue?"))
  3638. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  3639. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  3640. msgbox.setDefaultButton(bt_ok)
  3641. msgbox.exec_()
  3642. response = msgbox.clickedButton()
  3643. if response == bt_ok:
  3644. if no_pref is False:
  3645. self.preferencesUiManager.defaults_read_form()
  3646. scale_defaults(factor)
  3647. self.preferencesUiManager.defaults_write_form(fl_units=new_units)
  3648. self.defaults["units"] = new_units
  3649. # update the defaults from form, some may assume that the conversion is enough and it's not
  3650. self.on_options_app2project()
  3651. # update the objects
  3652. for obj in self.collection.get_list():
  3653. obj.convert_units(new_units)
  3654. # make that the properties stored in the object are also updated
  3655. self.object_changed.emit(obj)
  3656. # rebuild the object UI
  3657. obj.build_ui()
  3658. # change this only if the workspace is active
  3659. if self.defaults['global_workspace'] is True:
  3660. self.plotcanvas.draw_workspace(pagesize=self.defaults['global_workspaceT'])
  3661. # adjust the grid values on the main toolbar
  3662. val_x = float(self.defaults['global_gridx']) * factor
  3663. val_y = val_x if self.ui.grid_gap_link_cb.isChecked() else float(self.defaults['global_gridx']) * factor
  3664. current = self.collection.get_active()
  3665. if current is not None:
  3666. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  3667. if not isinstance(current, GeometryObject):
  3668. current.to_form()
  3669. # replot all objects
  3670. self.plot_all()
  3671. # set the status labels to reflect the current FlatCAM units
  3672. self.set_screen_units(new_units)
  3673. # signal to the app that we changed the object properties and it shoud save the project
  3674. self.should_we_save = True
  3675. self.inform.emit('[success] %s: %s' % (_("Converted units to"), new_units))
  3676. else:
  3677. # Undo toggling
  3678. self.toggle_units_ignore = True
  3679. if self.defaults['units'].upper() == 'MM':
  3680. self.ui.general_defaults_form.general_app_group.units_radio.set_value('IN')
  3681. else:
  3682. self.ui.general_defaults_form.general_app_group.units_radio.set_value('MM')
  3683. self.toggle_units_ignore = False
  3684. # store the grid values so they are not changed in the next step
  3685. val_x = float(self.defaults['global_gridx'])
  3686. val_y = float(self.defaults['global_gridy'])
  3687. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  3688. self.preferencesUiManager.defaults_read_form()
  3689. # the self.preferencesUiManager.defaults_read_form() will update all defaults values in self.defaults from the GUI elements but
  3690. # I don't want it for the grid values, so I update them here
  3691. self.defaults['global_gridx'] = val_x
  3692. self.defaults['global_gridy'] = val_y
  3693. self.ui.grid_gap_x_entry.set_value(val_x, decimals=self.decimals)
  3694. self.ui.grid_gap_y_entry.set_value(val_y, decimals=self.decimals)
  3695. def on_fullscreen(self, disable=False):
  3696. self.report_usage("on_fullscreen()")
  3697. flags = self.ui.windowFlags()
  3698. if self.toggle_fscreen is False and disable is False:
  3699. # self.ui.showFullScreen()
  3700. self.ui.setWindowFlags(flags | Qt.FramelessWindowHint)
  3701. a = self.ui.geometry()
  3702. self.x_pos = a.x()
  3703. self.y_pos = a.y()
  3704. self.width = a.width()
  3705. self.height = a.height()
  3706. # set new geometry to full desktop rect
  3707. # Subtracting and adding the pixels below it's hack to bypass a bug in Qt5 and OpenGL that made that a
  3708. # window drawn with OpenGL in fullscreen will not show any other windows on top which means that menus and
  3709. # everything else will not work without this hack. This happen in Windows.
  3710. # https://bugreports.qt.io/browse/QTBUG-41309
  3711. desktop = QtWidgets.QApplication.desktop()
  3712. screen = desktop.screenNumber(QtGui.QCursor.pos())
  3713. rec = desktop.screenGeometry(screen)
  3714. x = rec.x() - 1
  3715. y = rec.y() - 1
  3716. h = rec.height() + 2
  3717. w = rec.width() + 2
  3718. self.ui.setGeometry(x, y, w, h)
  3719. self.ui.show()
  3720. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  3721. tb.setVisible(False)
  3722. self.ui.splitter_left.setVisible(False)
  3723. self.toggle_fscreen = True
  3724. elif self.toggle_fscreen is True or disable is True:
  3725. self.ui.setWindowFlags(flags & ~Qt.FramelessWindowHint)
  3726. self.ui.setGeometry(self.x_pos, self.y_pos, self.width, self.height)
  3727. self.ui.showNormal()
  3728. self.restore_toolbar_view()
  3729. self.ui.splitter_left.setVisible(True)
  3730. self.toggle_fscreen = False
  3731. def on_toggle_plotarea(self):
  3732. self.report_usage("on_toggle_plotarea()")
  3733. try:
  3734. name = self.ui.plot_tab_area.widget(0).objectName()
  3735. except AttributeError:
  3736. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  3737. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  3738. self.ui.plot_tab_area.protectTab(0)
  3739. return
  3740. if name != 'plotarea':
  3741. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  3742. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  3743. self.ui.plot_tab_area.protectTab(0)
  3744. else:
  3745. self.ui.plot_tab_area.closeTab(0)
  3746. def on_toggle_notebook(self):
  3747. if self.ui.splitter.sizes()[0] == 0:
  3748. self.ui.splitter.setSizes([1, 1])
  3749. self.ui.menu_toggle_nb.setChecked(True)
  3750. else:
  3751. self.ui.splitter.setSizes([0, 1])
  3752. self.ui.menu_toggle_nb.setChecked(False)
  3753. def on_toggle_axis(self):
  3754. self.report_usage("on_toggle_axis()")
  3755. if self.toggle_axis is False:
  3756. if self.is_legacy is False:
  3757. self.plotcanvas.v_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=True,
  3758. parent=self.plotcanvas.view.scene)
  3759. self.plotcanvas.h_line = InfiniteLine(pos=0, color=(0.70, 0.3, 0.3, 1.0), vertical=False,
  3760. parent=self.plotcanvas.view.scene)
  3761. else:
  3762. if self.plotcanvas.h_line not in self.plotcanvas.axes.lines and \
  3763. self.plotcanvas.v_line not in self.plotcanvas.axes.lines:
  3764. self.plotcanvas.h_line = self.plotcanvas.axes.axhline(color=(0.70, 0.3, 0.3), linewidth=2)
  3765. self.plotcanvas.v_line = self.plotcanvas.axes.axvline(color=(0.70, 0.3, 0.3), linewidth=2)
  3766. self.plotcanvas.canvas.draw()
  3767. self.toggle_axis = True
  3768. else:
  3769. if self.is_legacy is False:
  3770. self.plotcanvas.v_line.parent = None
  3771. self.plotcanvas.h_line.parent = None
  3772. else:
  3773. if self.plotcanvas.h_line in self.plotcanvas.axes.lines and \
  3774. self.plotcanvas.v_line in self.plotcanvas.axes.lines:
  3775. self.plotcanvas.axes.lines.remove(self.plotcanvas.h_line)
  3776. self.plotcanvas.axes.lines.remove(self.plotcanvas.v_line)
  3777. self.plotcanvas.canvas.draw()
  3778. self.toggle_axis = False
  3779. def on_toggle_grid(self):
  3780. self.report_usage("on_toggle_grid()")
  3781. self.ui.grid_snap_btn.trigger()
  3782. self.on_grid_snap_triggered(state=True)
  3783. def on_toggle_grid_lines(self):
  3784. self.report_usage("on_toggle_grd_lines()")
  3785. tt_settings = QtCore.QSettings("Open Source", "FlatCAM")
  3786. if tt_settings.contains("theme"):
  3787. theme = tt_settings.value('theme', type=str)
  3788. else:
  3789. theme = 'white'
  3790. if self.toggle_grid_lines is False:
  3791. if self.is_legacy is False:
  3792. if theme == 'white':
  3793. self.plotcanvas.grid._grid_color_fn['color'] = Color('dimgray').rgba
  3794. else:
  3795. self.plotcanvas.grid._grid_color_fn['color'] = Color('#dededeff').rgba
  3796. else:
  3797. self.plotcanvas.axes.grid(True)
  3798. try:
  3799. self.plotcanvas.canvas.draw()
  3800. except IndexError:
  3801. pass
  3802. pass
  3803. self.toggle_grid_lines = True
  3804. else:
  3805. if self.is_legacy is False:
  3806. if theme == 'white':
  3807. self.plotcanvas.grid._grid_color_fn['color'] = Color('#ffffffff').rgba
  3808. else:
  3809. self.plotcanvas.grid._grid_color_fn['color'] = Color('#000000FF').rgba
  3810. else:
  3811. self.plotcanvas.axes.grid(False)
  3812. try:
  3813. self.plotcanvas.canvas.draw()
  3814. except IndexError:
  3815. pass
  3816. self.toggle_grid_lines = False
  3817. if self.is_legacy is False:
  3818. # HACK: enabling/disabling the cursor seams to somehow update the shapes on screen
  3819. # - perhaps is a bug in VisPy implementation
  3820. if self.grid_status() is True:
  3821. self.app_cursor.enabled = False
  3822. self.app_cursor.enabled = True
  3823. else:
  3824. self.app_cursor.enabled = True
  3825. self.app_cursor.enabled = False
  3826. def on_update_exc_export(self, state):
  3827. """
  3828. This is handling the update of Excellon Export parameters based on the ones in the Excellon General but only
  3829. if the update_excellon_cb checkbox is checked
  3830. :param state: state of the checkbox whose signals is tied to his slot
  3831. :return:
  3832. """
  3833. if state:
  3834. # first try to disconnect
  3835. try:
  3836. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed. \
  3837. disconnect(self.on_excellon_format_changed)
  3838. except TypeError:
  3839. pass
  3840. try:
  3841. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed. \
  3842. disconnect(self.on_excellon_format_changed)
  3843. except TypeError:
  3844. pass
  3845. try:
  3846. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed. \
  3847. disconnect(self.on_excellon_format_changed)
  3848. except TypeError:
  3849. pass
  3850. try:
  3851. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed. \
  3852. disconnect(self.on_excellon_format_changed)
  3853. except TypeError:
  3854. pass
  3855. try:
  3856. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  3857. disconnect(self.on_excellon_zeros_changed)
  3858. except TypeError:
  3859. pass
  3860. try:
  3861. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  3862. disconnect(self.on_excellon_zeros_changed)
  3863. except TypeError:
  3864. pass
  3865. # the connect them
  3866. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed.connect(
  3867. self.on_excellon_format_changed)
  3868. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed.connect(
  3869. self.on_excellon_format_changed)
  3870. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed.connect(
  3871. self.on_excellon_format_changed)
  3872. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed.connect(
  3873. self.on_excellon_format_changed)
  3874. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom.connect(
  3875. self.on_excellon_zeros_changed)
  3876. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom.connect(
  3877. self.on_excellon_units_changed)
  3878. else:
  3879. # disconnect the signals
  3880. try:
  3881. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.returnPressed. \
  3882. disconnect(self.on_excellon_format_changed)
  3883. except TypeError:
  3884. pass
  3885. try:
  3886. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.returnPressed. \
  3887. disconnect(self.on_excellon_format_changed)
  3888. except TypeError:
  3889. pass
  3890. try:
  3891. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.returnPressed. \
  3892. disconnect(self.on_excellon_format_changed)
  3893. except TypeError:
  3894. pass
  3895. try:
  3896. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.returnPressed. \
  3897. disconnect(self.on_excellon_format_changed)
  3898. except TypeError:
  3899. pass
  3900. try:
  3901. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.activated_custom. \
  3902. disconnect(self.on_excellon_zeros_changed)
  3903. except TypeError:
  3904. pass
  3905. try:
  3906. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.activated_custom. \
  3907. disconnect(self.on_excellon_zeros_changed)
  3908. except TypeError:
  3909. pass
  3910. def on_excellon_format_changed(self):
  3911. """
  3912. Slot activated when the user changes the Excellon format values in Preferences -> Excellon -> Excellon General
  3913. :return: None
  3914. """
  3915. if self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value().upper() == 'METRIC':
  3916. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  3917. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry.get_value()
  3918. )
  3919. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  3920. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry.get_value()
  3921. )
  3922. else:
  3923. self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry.set_value(
  3924. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry.get_value()
  3925. )
  3926. self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry.set_value(
  3927. self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry.get_value()
  3928. )
  3929. def on_excellon_zeros_changed(self):
  3930. """
  3931. Slot activated when the user changes the Excellon zeros values in Preferences -> Excellon -> Excellon General
  3932. :return: None
  3933. """
  3934. self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio.set_value(
  3935. self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio.get_value() + 'Z'
  3936. )
  3937. def on_excellon_units_changed(self):
  3938. """
  3939. Slot activated when the user changes the Excellon unit values in Preferences -> Excellon -> Excellon General
  3940. :return: None
  3941. """
  3942. self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio.set_value(
  3943. self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio.get_value()
  3944. )
  3945. self.on_excellon_format_changed()
  3946. def on_film_color_entry(self):
  3947. self.defaults['tools_film_color'] = \
  3948. self.ui.tools_defaults_form.tools_film_group.film_color_entry.get_value()
  3949. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  3950. "background-color:%s;"
  3951. "border-color: dimgray" % str(self.defaults['tools_film_color'])
  3952. )
  3953. def on_film_color_button(self):
  3954. current_color = QtGui.QColor(self.defaults['tools_film_color'])
  3955. c_dialog = QtWidgets.QColorDialog()
  3956. film_color = c_dialog.getColor(initial=current_color)
  3957. if film_color.isValid() is False:
  3958. return
  3959. # if new color is different then mark that the Preferences are changed
  3960. if film_color != current_color:
  3961. self.on_preferences_edited()
  3962. self.ui.tools_defaults_form.tools_film_group.film_color_button.setStyleSheet(
  3963. "background-color:%s;"
  3964. "border-color: dimgray" % str(film_color.name())
  3965. )
  3966. new_val_sel = str(film_color.name())
  3967. self.ui.tools_defaults_form.tools_film_group.film_color_entry.set_value(new_val_sel)
  3968. self.defaults['tools_film_color'] = new_val_sel
  3969. def on_qrcode_fill_color_entry(self):
  3970. self.defaults['tools_qrcode_fill_color'] = \
  3971. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.get_value()
  3972. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  3973. "background-color:%s;"
  3974. "border-color: dimgray" % str(self.defaults['tools_qrcode_fill_color'])
  3975. )
  3976. def on_qrcode_fill_color_button(self):
  3977. current_color = QtGui.QColor(self.defaults['tools_qrcode_fill_color'])
  3978. c_dialog = QtWidgets.QColorDialog()
  3979. fill_color = c_dialog.getColor(initial=current_color)
  3980. if fill_color.isValid() is False:
  3981. return
  3982. # if new color is different then mark that the Preferences are changed
  3983. if fill_color != current_color:
  3984. self.on_preferences_edited()
  3985. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_button.setStyleSheet(
  3986. "background-color:%s;"
  3987. "border-color: dimgray" % str(fill_color.name())
  3988. )
  3989. new_val_sel = str(fill_color.name())
  3990. self.ui.tools2_defaults_form.tools2_qrcode_group.fill_color_entry.set_value(new_val_sel)
  3991. self.defaults['tools_qrcode_fill_color'] = new_val_sel
  3992. def on_qrcode_back_color_entry(self):
  3993. self.defaults['tools_qrcode_back_color'] = \
  3994. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.get_value()
  3995. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  3996. "background-color:%s;"
  3997. "border-color: dimgray" % str(self.defaults['tools_qrcode_back_color'])
  3998. )
  3999. def on_qrcode_back_color_button(self):
  4000. current_color = QtGui.QColor(self.defaults['tools_qrcode_back_color'])
  4001. c_dialog = QtWidgets.QColorDialog()
  4002. back_color = c_dialog.getColor(initial=current_color)
  4003. if back_color.isValid() is False:
  4004. return
  4005. # if new color is different then mark that the Preferences are changed
  4006. if back_color != current_color:
  4007. self.on_preferences_edited()
  4008. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_button.setStyleSheet(
  4009. "background-color:%s;"
  4010. "border-color: dimgray" % str(back_color.name())
  4011. )
  4012. new_val_sel = str(back_color.name())
  4013. self.ui.tools2_defaults_form.tools2_qrcode_group.back_color_entry.set_value(new_val_sel)
  4014. self.defaults['tools_qrcode_back_color'] = new_val_sel
  4015. def on_tab_rmb_click(self, checked):
  4016. self.ui.notebook.set_detachable(val=checked)
  4017. self.defaults["global_tabs_detachable"] = checked
  4018. self.ui.plot_tab_area.set_detachable(val=checked)
  4019. self.defaults["global_tabs_detachable"] = checked
  4020. def on_tab_setup_context_menu(self):
  4021. initial_checked = self.defaults["global_tabs_detachable"]
  4022. action_name = str(_("Detachable Tabs"))
  4023. action = QtWidgets.QAction(self)
  4024. action.setCheckable(True)
  4025. action.setText(action_name)
  4026. action.setChecked(initial_checked)
  4027. self.ui.notebook.tabBar.addAction(action)
  4028. self.ui.plot_tab_area.tabBar.addAction(action)
  4029. try:
  4030. action.triggered.disconnect()
  4031. except TypeError:
  4032. pass
  4033. action.triggered.connect(self.on_tab_rmb_click)
  4034. def on_deselect_all(self):
  4035. self.collection.set_all_inactive()
  4036. self.delete_selection_shape()
  4037. def on_workspace_modified(self):
  4038. # self.save_defaults(silent=True)
  4039. if self.is_legacy is True:
  4040. self.plotcanvas.delete_workspace()
  4041. self.preferencesUiManager.defaults_read_form()
  4042. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  4043. def on_workspace(self):
  4044. if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value():
  4045. self.plotcanvas.draw_workspace(workspace_size=self.defaults['global_workspaceT'])
  4046. else:
  4047. self.plotcanvas.delete_workspace()
  4048. self.preferencesUiManager.defaults_read_form()
  4049. # self.save_defaults(silent=True)
  4050. def on_workspace_toggle(self):
  4051. state = False if self.ui.general_defaults_form.general_app_set_group.workspace_cb.get_value() else True
  4052. try:
  4053. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.disconnect(self.on_workspace)
  4054. except TypeError:
  4055. pass
  4056. self.ui.general_defaults_form.general_app_set_group.workspace_cb.set_value(state)
  4057. self.ui.general_defaults_form.general_app_set_group.workspace_cb.stateChanged.connect(self.on_workspace)
  4058. self.on_workspace()
  4059. def on_cursor_type(self, val):
  4060. """
  4061. :param val: type of mouse cursor, set in Preferences ('small' or 'big')
  4062. :return: None
  4063. """
  4064. self.app_cursor.enabled = False
  4065. if val == 'small':
  4066. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(False)
  4067. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(False)
  4068. self.app_cursor = self.plotcanvas.new_cursor()
  4069. else:
  4070. self.ui.general_defaults_form.general_app_set_group.cursor_size_entry.setDisabled(True)
  4071. self.ui.general_defaults_form.general_app_set_group.cursor_size_lbl.setDisabled(True)
  4072. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  4073. if self.ui.grid_snap_btn.isChecked():
  4074. self.app_cursor.enabled = True
  4075. else:
  4076. self.app_cursor.enabled = False
  4077. def on_tool_add_keypress(self):
  4078. # ## Current application units in Upper Case
  4079. self.units = self.defaults['units'].upper()
  4080. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  4081. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  4082. if notebook_widget_name == 'selected_tab':
  4083. if self.collection.get_active().kind == 'geometry':
  4084. # Tool add works for Geometry only if Advanced is True in Preferences
  4085. if self.defaults["global_app_level"] == 'a':
  4086. tool_add_popup = FCInputDialog(title="New Tool ...",
  4087. text='Enter a Tool Diameter:',
  4088. min=0.0000, max=99.9999, decimals=4)
  4089. tool_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/letter_t_32.png'))
  4090. val, ok = tool_add_popup.get_value()
  4091. if ok:
  4092. if float(val) == 0:
  4093. self.inform.emit('[WARNING_NOTCL] %s' %
  4094. _("Please enter a tool diameter with non-zero value, in Float format."))
  4095. return
  4096. self.collection.get_active().on_tool_add(dia=float(val))
  4097. else:
  4098. self.inform.emit('[WARNING_NOTCL] %s...' % _("Adding Tool cancelled"))
  4099. else:
  4100. msgbox = QtWidgets.QMessageBox()
  4101. msgbox.setText(_("Adding Tool works only when Advanced is checked.\n"
  4102. "Go to Preferences -> General - Show Advanced Options."))
  4103. msgbox.setWindowTitle("Tool adding ...")
  4104. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/warning.png'))
  4105. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4106. msgbox.setDefaultButton(bt_ok)
  4107. msgbox.exec_()
  4108. # work only if the notebook tab on focus is the Tools_Tab
  4109. if notebook_widget_name == 'tool_tab':
  4110. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  4111. # and only if the tool is NCC Tool
  4112. if tool_widget == self.ncclear_tool.toolName:
  4113. self.ncclear_tool.on_add_tool_by_key()
  4114. # and only if the tool is Paint Area Tool
  4115. elif tool_widget == self.paint_tool.toolName:
  4116. self.paint_tool.on_add_tool_by_key()
  4117. # and only if the tool is Solder Paste Dispensing Tool
  4118. elif tool_widget == self.paste_tool.toolName:
  4119. self.paste_tool.on_add_tool_by_key()
  4120. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  4121. # See description bellow.
  4122. def on_delete_keypress(self):
  4123. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  4124. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  4125. if notebook_widget_name == 'selected_tab':
  4126. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.GeometryObject'>":
  4127. self.collection.get_active().on_tool_delete()
  4128. # work only if the notebook tab on focus is the Tools_Tab
  4129. elif notebook_widget_name == 'tool_tab':
  4130. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  4131. # and only if the tool is NCC Tool
  4132. if tool_widget == self.ncclear_tool.toolName:
  4133. self.ncclear_tool.on_tool_delete()
  4134. # and only if the tool is Paint Tool
  4135. elif tool_widget == self.paint_tool.toolName:
  4136. self.paint_tool.on_tool_delete()
  4137. # and only if the tool is Solder Paste Dispensing Tool
  4138. elif tool_widget == self.paste_tool.toolName:
  4139. self.paste_tool.on_tool_delete()
  4140. else:
  4141. self.on_delete()
  4142. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  4143. # some screens you have to be careful where you hover with your mouse.
  4144. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  4145. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  4146. # Complicated, I know :)
  4147. def on_delete(self, force_deletion=False):
  4148. """
  4149. Delete the currently selected FlatCAMObjs.
  4150. :param force_deletion: used by Tcl command
  4151. :return: None
  4152. """
  4153. self.report_usage("on_delete()")
  4154. response = None
  4155. bt_ok = None
  4156. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  4157. # a geometry object before we update it.
  4158. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False \
  4159. and self.grb_editor.editor_active is False:
  4160. if self.defaults["global_delete_confirmation"] is True and force_deletion is False:
  4161. msgbox = QtWidgets.QMessageBox()
  4162. msgbox.setWindowTitle(_("Delete objects"))
  4163. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/deleteshape32.png'))
  4164. # msgbox.setText("<B>%s</B>" % _("Change project units ..."))
  4165. msgbox.setText(_("Are you sure you want to permanently delete\n"
  4166. "the selected objects?"))
  4167. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  4168. msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  4169. msgbox.setDefaultButton(bt_ok)
  4170. msgbox.exec_()
  4171. response = msgbox.clickedButton()
  4172. if self.defaults["global_delete_confirmation"] is False or force_deletion is True:
  4173. response = bt_ok
  4174. if response == bt_ok:
  4175. if self.collection.get_active():
  4176. self.log.debug("App.on_delete()")
  4177. for obj_active in self.collection.get_selected():
  4178. # if the deleted object is GerberObject then make sure to delete the possible mark shapes
  4179. if isinstance(obj_active, GerberObject):
  4180. for el in obj_active.mark_shapes:
  4181. obj_active.mark_shapes[el].clear(update=True)
  4182. obj_active.mark_shapes[el].enabled = False
  4183. # obj_active.mark_shapes[el] = None
  4184. del el
  4185. elif isinstance(obj_active, CNCJobObject):
  4186. try:
  4187. obj_active.text_col.enabled = False
  4188. del obj_active.text_col
  4189. obj_active.annotation.clear(update=True)
  4190. del obj_active.annotation
  4191. except AttributeError as e:
  4192. log.debug(
  4193. "App.on_delete() --> delete annotations on a FlatCAMCNCJob object. %s" % str(e)
  4194. )
  4195. while self.collection.get_selected():
  4196. self.delete_first_selected()
  4197. self.inform.emit('%s...' % _("Object(s) deleted"))
  4198. # make sure that the selection shape is deleted, too
  4199. self.delete_selection_shape()
  4200. else:
  4201. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  4202. else:
  4203. self.inform.emit(_("Save the work in Editor and try again ..."))
  4204. def delete_first_selected(self):
  4205. # Keep this for later
  4206. try:
  4207. sel_obj = self.collection.get_active()
  4208. name = sel_obj.options["name"]
  4209. isPlotted = sel_obj.options["plot"]
  4210. except AttributeError:
  4211. self.log.debug("Nothing selected for deletion")
  4212. return
  4213. if self.is_legacy is True:
  4214. # Remove plot only if the object was plotted otherwise delaxes will fail
  4215. if isPlotted:
  4216. try:
  4217. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  4218. self.plotcanvas.figure.delaxes(self.collection.get_active().shapes.axes)
  4219. except Exception as e:
  4220. log.debug("App.delete_first_selected() --> %s" % str(e))
  4221. self.plotcanvas.auto_adjust_axes()
  4222. # Remove from dictionary
  4223. self.collection.delete_active()
  4224. # Clear form
  4225. self.setup_component_editor()
  4226. self.inform.emit('%s: %s' % (_("Object deleted"), name))
  4227. def on_set_origin(self):
  4228. """
  4229. Set the origin to the left mouse click position
  4230. :return: None
  4231. """
  4232. # display the message for the user
  4233. # and ask him to click on the desired position
  4234. self.report_usage("on_set_origin()")
  4235. def origin_replot():
  4236. def worker_task():
  4237. with self.proc_container.new('%s...' % _("Plotting")):
  4238. for obj in self.collection.get_list():
  4239. obj.plot()
  4240. self.plotcanvas.fit_view()
  4241. if self.is_legacy:
  4242. self.plotcanvas.graph_event_disconnect(self.mp_zc)
  4243. else:
  4244. self.plotcanvas.graph_event_disconnect('mouse_press', self.on_set_zero_click)
  4245. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4246. self.inform.emit(_('Click to set the origin ...'))
  4247. self.mp_zc = self.plotcanvas.graph_event_connect('mouse_press', self.on_set_zero_click)
  4248. # first disconnect it as it may have been used by something else
  4249. try:
  4250. self.replot_signal.disconnect()
  4251. except TypeError:
  4252. pass
  4253. self.replot_signal[list].connect(origin_replot)
  4254. def on_set_zero_click(self, event, location=None, noplot=False, use_thread=True):
  4255. """
  4256. :param event:
  4257. :param location:
  4258. :param noplot:
  4259. :param use_thread:
  4260. :return:
  4261. """
  4262. noplot_sig = noplot
  4263. def worker_task():
  4264. with self.proc_container.new(_("Setting Origin...")):
  4265. obj_list = self.collection.get_list()
  4266. for obj in obj_list:
  4267. obj.offset((x, y))
  4268. self.object_changed.emit(obj)
  4269. # Update the object bounding box options
  4270. a, b, c, d = obj.bounds()
  4271. obj.options['xmin'] = a
  4272. obj.options['ymin'] = b
  4273. obj.options['xmax'] = c
  4274. obj.options['ymax'] = d
  4275. self.inform.emit('[success] %s...' % _('Origin set'))
  4276. for obj in obj_list:
  4277. out_name = obj.options["name"]
  4278. if obj.kind == 'gerber':
  4279. obj.source_file = self.export_gerber(
  4280. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4281. elif obj.kind == 'excellon':
  4282. obj.source_file = self.export_excellon(
  4283. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4284. if noplot_sig is False:
  4285. self.replot_signal.emit([])
  4286. if location is not None:
  4287. if len(location) != 2:
  4288. self.inform.emit('[ERROR_NOTCL] %s...' % _("Origin coordinates specified but incomplete."))
  4289. return 'fail'
  4290. x, y = location
  4291. if use_thread is True:
  4292. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4293. else:
  4294. worker_task()
  4295. self.should_we_save = True
  4296. return
  4297. if event.button == 1:
  4298. if self.is_legacy is False:
  4299. event_pos = event.pos
  4300. else:
  4301. event_pos = (event.xdata, event.ydata)
  4302. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  4303. if self.grid_status():
  4304. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  4305. else:
  4306. pos = pos_canvas
  4307. x = 0 - pos[0]
  4308. y = 0 - pos[1]
  4309. if use_thread is True:
  4310. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4311. else:
  4312. worker_task()
  4313. self.should_we_save = True
  4314. def on_move2origin(self, use_thread=True):
  4315. """
  4316. Move selected objects to origin.
  4317. :param use_thread: Control if to use threaded operation. Boolean.
  4318. :return:
  4319. """
  4320. def worker_task():
  4321. with self.proc_container.new(_("Moving to Origin...")):
  4322. obj_list = self.collection.get_selected()
  4323. if not obj_list:
  4324. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. No object(s) selected..."))
  4325. return
  4326. xminlist = []
  4327. yminlist = []
  4328. # first get a bounding box to fit all
  4329. for obj in obj_list:
  4330. xmin, ymin, xmax, ymax = obj.bounds()
  4331. xminlist.append(xmin)
  4332. yminlist.append(ymin)
  4333. # get the minimum x,y for all objects selected
  4334. x = min(xminlist)
  4335. y = min(yminlist)
  4336. for obj in obj_list:
  4337. obj.offset((-x, -y))
  4338. self.object_changed.emit(obj)
  4339. # Update the object bounding box options
  4340. a, b, c, d = obj.bounds()
  4341. obj.options['xmin'] = a
  4342. obj.options['ymin'] = b
  4343. obj.options['xmax'] = c
  4344. obj.options['ymax'] = d
  4345. for obj in obj_list:
  4346. obj.plot()
  4347. for obj in obj_list:
  4348. out_name = obj.options["name"]
  4349. if obj.kind == 'gerber':
  4350. obj.source_file = self.export_gerber(
  4351. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4352. elif obj.kind == 'excellon':
  4353. obj.source_file = self.export_excellon(
  4354. obj_name=out_name, filename=None, local_use=obj, use_thread=False)
  4355. self.inform.emit('[success] %s...' % _('Origin set'))
  4356. if use_thread is True:
  4357. self.worker_task.emit({'fcn': worker_task, 'params': []})
  4358. else:
  4359. worker_task()
  4360. self.should_we_save = True
  4361. def on_jump_to(self, custom_location=None, fit_center=True):
  4362. """
  4363. Jump to a location by setting the mouse cursor location.
  4364. :param custom_location: Jump to a specified point. (x, y) tuple.
  4365. :param fit_center: If to fit view. Boolean.
  4366. :return:
  4367. """
  4368. self.report_usage("on_jump_to()")
  4369. if not custom_location:
  4370. dia_box_location = None
  4371. try:
  4372. dia_box_location = eval(self.clipboard.text())
  4373. except Exception:
  4374. pass
  4375. if type(dia_box_location) == tuple:
  4376. dia_box_location = str(dia_box_location)
  4377. else:
  4378. dia_box_location = None
  4379. # dia_box = Dialog_box(title=_("Jump to ..."),
  4380. # label=_("Enter the coordinates in format X,Y:"),
  4381. # icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  4382. # initial_text=dia_box_location)
  4383. dia_box = DialogBoxRadio(title=_("Jump to ..."),
  4384. label=_("Enter the coordinates in format X,Y:"),
  4385. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  4386. initial_text=dia_box_location,
  4387. reference=self.defaults['global_jump_ref'])
  4388. if dia_box.ok is True:
  4389. try:
  4390. location = eval(dia_box.location)
  4391. if not isinstance(location, tuple):
  4392. self.inform.emit(_("Wrong coordinates. Enter coordinates in format: X,Y"))
  4393. return
  4394. if dia_box.reference == 'rel':
  4395. rel_x = self.mouse[0] + location[0]
  4396. rel_y = self.mouse[1] + location[1]
  4397. location = (rel_x, rel_y)
  4398. self.defaults['global_jump_ref'] = dia_box.reference
  4399. except Exception:
  4400. return
  4401. else:
  4402. return
  4403. else:
  4404. location = custom_location
  4405. self.jump_signal.emit(location)
  4406. if fit_center:
  4407. self.plotcanvas.fit_center(loc=location)
  4408. cursor = QtGui.QCursor()
  4409. if self.is_legacy is False:
  4410. # I don't know where those differences come from but they are constant for the current
  4411. # execution of the application and they are multiples of a value around 0.0263mm.
  4412. # In a random way sometimes they are more sometimes they are less
  4413. # if units == 'MM':
  4414. # cal_factor = 0.0263
  4415. # else:
  4416. # cal_factor = 0.0263 / 25.4
  4417. cal_location = (location[0], location[1])
  4418. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4419. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  4420. j_pos = (
  4421. int(canvas_origin.x() + round(jump_loc[0])),
  4422. int(canvas_origin.y() + round(jump_loc[1]))
  4423. )
  4424. cursor.setPos(j_pos[0], j_pos[1])
  4425. else:
  4426. # find the canvas origin which is in the top left corner
  4427. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4428. # determine the coordinates for the lowest left point of the canvas
  4429. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  4430. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  4431. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  4432. # canvas) and the point (width, height) is in the top-right location
  4433. loc = self.plotcanvas.axes.transData.transform_point(location)
  4434. j_pos = (
  4435. int(x0 + loc[0]),
  4436. int(y0 - loc[1])
  4437. )
  4438. cursor.setPos(j_pos[0], j_pos[1])
  4439. self.plotcanvas.mouse = [location[0], location[1]]
  4440. if self.defaults["global_cursor_color_enabled"] is True:
  4441. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  4442. else:
  4443. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  4444. if self.grid_status():
  4445. # Update cursor
  4446. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  4447. symbol='++', edge_color=self.cursor_color_3D,
  4448. edge_width=self.defaults["global_cursor_width"],
  4449. size=self.defaults["global_cursor_size"])
  4450. # Set the position label
  4451. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4452. "<b>Y</b>: %.4f" % (location[0], location[1]))
  4453. # Set the relative position label
  4454. dx = location[0] - float(self.rel_point1[0])
  4455. dy = location[1] - float(self.rel_point1[1])
  4456. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4457. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  4458. self.inform.emit('[success] %s' % _("Done."))
  4459. return location
  4460. def on_locate(self, obj, fit_center=True):
  4461. """
  4462. Jump to one of the corners (or center) of an object by setting the mouse cursor location
  4463. :param obj: The object on which to locate certain points
  4464. :param fit_center: If to fit view. Boolean.
  4465. :return: A point location. (x, y) tuple.
  4466. """
  4467. self.report_usage("on_locate()")
  4468. if obj is None:
  4469. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  4470. return 'fail'
  4471. class DialogBoxChoice(QtWidgets.QDialog):
  4472. def __init__(self, title=None, icon=None, choice='bl'):
  4473. """
  4474. :param title: string with the window title
  4475. """
  4476. super(DialogBoxChoice, self).__init__()
  4477. self.ok = False
  4478. self.setWindowIcon(icon)
  4479. self.setWindowTitle(str(title))
  4480. self.form = QtWidgets.QFormLayout(self)
  4481. self.ref_radio = RadioSet([
  4482. {"label": _("Bottom-Left"), "value": "bl"},
  4483. {"label": _("Top-Left"), "value": "tl"},
  4484. {"label": _("Bottom-Right"), "value": "br"},
  4485. {"label": _("Top-Right"), "value": "tr"},
  4486. {"label": _("Center"), "value": "c"}
  4487. ], orientation='vertical', stretch=False)
  4488. self.ref_radio.set_value(choice)
  4489. self.form.addRow(self.ref_radio)
  4490. self.button_box = QtWidgets.QDialogButtonBox(
  4491. QtWidgets.QDialogButtonBox.Ok | QtWidgets.QDialogButtonBox.Cancel,
  4492. Qt.Horizontal, parent=self)
  4493. self.form.addRow(self.button_box)
  4494. self.button_box.accepted.connect(self.accept)
  4495. self.button_box.rejected.connect(self.reject)
  4496. if self.exec_() == QtWidgets.QDialog.Accepted:
  4497. self.ok = True
  4498. self.location_point = self.ref_radio.get_value()
  4499. else:
  4500. self.ok = False
  4501. self.location_point = None
  4502. dia_box = DialogBoxChoice(title=_("Locate ..."),
  4503. icon=QtGui.QIcon(self.resource_location + '/locate16.png'),
  4504. choice=self.defaults['global_locate_pt'])
  4505. if dia_box.ok is True:
  4506. try:
  4507. location_point = dia_box.location_point
  4508. self.defaults['global_locate_pt'] = dia_box.location_point
  4509. except Exception:
  4510. return
  4511. else:
  4512. return
  4513. loc_b = obj.bounds()
  4514. if location_point == 'bl':
  4515. location = (loc_b[0], loc_b[1])
  4516. elif location_point == 'tl':
  4517. location = (loc_b[0], loc_b[3])
  4518. elif location_point == 'br':
  4519. location = (loc_b[2], loc_b[1])
  4520. elif location_point == 'tr':
  4521. location = (loc_b[2], loc_b[3])
  4522. else:
  4523. # center
  4524. cx = loc_b[0] + ((loc_b[2] - loc_b[0]) / 2)
  4525. cy = loc_b[1] + ((loc_b[3] - loc_b[1]) / 2)
  4526. location = (cx, cy)
  4527. self.locate_signal.emit(location, location_point)
  4528. if fit_center:
  4529. self.plotcanvas.fit_center(loc=location)
  4530. cursor = QtGui.QCursor()
  4531. if self.is_legacy is False:
  4532. # I don't know where those differences come from but they are constant for the current
  4533. # execution of the application and they are multiples of a value around 0.0263mm.
  4534. # In a random way sometimes they are more sometimes they are less
  4535. # if units == 'MM':
  4536. # cal_factor = 0.0263
  4537. # else:
  4538. # cal_factor = 0.0263 / 25.4
  4539. cal_location = (location[0], location[1])
  4540. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4541. jump_loc = self.plotcanvas.translate_coords_2((cal_location[0], cal_location[1]))
  4542. j_pos = (
  4543. int(canvas_origin.x() + round(jump_loc[0])),
  4544. int(canvas_origin.y() + round(jump_loc[1]))
  4545. )
  4546. cursor.setPos(j_pos[0], j_pos[1])
  4547. else:
  4548. # find the canvas origin which is in the top left corner
  4549. canvas_origin = self.plotcanvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  4550. # determine the coordinates for the lowest left point of the canvas
  4551. x0, y0 = canvas_origin.x(), canvas_origin.y() + self.ui.right_layout.geometry().height()
  4552. # transform the given location from data coordinates to display coordinates. THe display coordinates are
  4553. # in pixels where the origin 0,0 is in the lowest left point of the display window (in our case is the
  4554. # canvas) and the point (width, height) is in the top-right location
  4555. loc = self.plotcanvas.axes.transData.transform_point(location)
  4556. j_pos = (
  4557. int(x0 + loc[0]),
  4558. int(y0 - loc[1])
  4559. )
  4560. cursor.setPos(j_pos[0], j_pos[1])
  4561. self.plotcanvas.mouse = [location[0], location[1]]
  4562. if self.defaults["global_cursor_color_enabled"] is True:
  4563. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1], color=self.cursor_color_3D)
  4564. else:
  4565. self.plotcanvas.draw_cursor(x_pos=location[0], y_pos=location[1])
  4566. if self.grid_status():
  4567. # Update cursor
  4568. self.app_cursor.set_data(np.asarray([(location[0], location[1])]),
  4569. symbol='++', edge_color=self.cursor_color_3D,
  4570. edge_width=self.defaults["global_cursor_width"],
  4571. size=self.defaults["global_cursor_size"])
  4572. # Set the position label
  4573. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  4574. "<b>Y</b>: %.4f" % (location[0], location[1]))
  4575. # Set the relative position label
  4576. self.dx = location[0] - float(self.rel_point1[0])
  4577. self.dy = location[1] - float(self.rel_point1[1])
  4578. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  4579. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  4580. self.inform.emit('[success] %s' % _("Done."))
  4581. return location
  4582. def on_copy_command(self):
  4583. """
  4584. Will copy a selection of objects, creating new objects.
  4585. :return:
  4586. """
  4587. self.report_usage("on_copy_command()")
  4588. def initialize(obj_init, app):
  4589. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4590. try:
  4591. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4592. except AttributeError:
  4593. pass
  4594. try:
  4595. obj_init.apertures = deepcopy(obj.apertures)
  4596. except AttributeError:
  4597. pass
  4598. try:
  4599. if obj.tools:
  4600. obj_init.tools = deepcopy(obj.tools)
  4601. except Exception as err:
  4602. log.debug("App.on_copy_command() --> %s" % str(err))
  4603. try:
  4604. obj_init.source_file = deepcopy(obj.source_file)
  4605. except (AttributeError, TypeError):
  4606. pass
  4607. def initialize_excellon(obj_init, app):
  4608. obj_init.source_file = deepcopy(obj.source_file)
  4609. obj_init.tools = deepcopy(obj.tools)
  4610. # drills are offset, so they need to be deep copied
  4611. obj_init.drills = deepcopy(obj.drills)
  4612. # slots are offset, so they need to be deep copied
  4613. obj_init.slots = deepcopy(obj.slots)
  4614. obj_init.create_geometry()
  4615. def initialize_script(obj_init, app_obj):
  4616. obj_init.source_file = deepcopy(obj.source_file)
  4617. def initialize_document(obj_init, app_obj):
  4618. obj_init.source_file = deepcopy(obj.source_file)
  4619. for obj in self.collection.get_selected():
  4620. obj_name = obj.options["name"]
  4621. try:
  4622. if isinstance(obj, ExcellonObject):
  4623. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  4624. elif isinstance(obj, GerberObject):
  4625. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  4626. elif isinstance(obj, GeometryObject):
  4627. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  4628. elif isinstance(obj, ScriptObject):
  4629. self.new_object("script", str(obj_name) + "_copy", initialize_script)
  4630. elif isinstance(obj, DocumentObject):
  4631. self.new_object("document", str(obj_name) + "_copy", initialize_document)
  4632. except Exception as e:
  4633. return "Operation failed: %s" % str(e)
  4634. def on_copy_object2(self, custom_name):
  4635. def initialize_geometry(obj_init, app):
  4636. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4637. try:
  4638. obj_init.follow_geometry = deepcopy(obj.follow_geometry)
  4639. except AttributeError:
  4640. pass
  4641. try:
  4642. obj_init.apertures = deepcopy(obj.apertures)
  4643. except AttributeError:
  4644. pass
  4645. try:
  4646. if obj.tools:
  4647. obj_init.tools = deepcopy(obj.tools)
  4648. except Exception as ee:
  4649. log.debug("on_copy_object2() --> %s" % str(ee))
  4650. def initialize_gerber(obj_init, app):
  4651. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4652. obj_init.apertures = deepcopy(obj.apertures)
  4653. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  4654. def initialize_excellon(obj_init, app):
  4655. obj_init.tools = deepcopy(obj.tools)
  4656. # drills are offset, so they need to be deep copied
  4657. obj_init.drills = deepcopy(obj.drills)
  4658. # slots are offset, so they need to be deep copied
  4659. obj_init.slots = deepcopy(obj.slots)
  4660. obj_init.create_geometry()
  4661. for obj in self.collection.get_selected():
  4662. obj_name = obj.options["name"]
  4663. try:
  4664. if isinstance(obj, ExcellonObject):
  4665. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  4666. elif isinstance(obj, GerberObject):
  4667. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  4668. elif isinstance(obj, GeometryObject):
  4669. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  4670. except Exception as er:
  4671. return "Operation failed: %s" % str(er)
  4672. def on_rename_object(self, text):
  4673. """
  4674. Will rename an object.
  4675. :param text: New name for the object.
  4676. :return:
  4677. """
  4678. self.report_usage("on_rename_object()")
  4679. named_obj = self.collection.get_active()
  4680. for obj in named_obj:
  4681. if obj is list:
  4682. self.on_rename_object(text)
  4683. else:
  4684. try:
  4685. obj.options['name'] = text
  4686. except Exception as e:
  4687. log.warning("App.on_rename_object() --> Could not rename the object in the list. --> %s" % str(e))
  4688. def convert_any2geo(self):
  4689. """
  4690. Will convert any object out of Gerber, Excellon, Geometry to Geometry object.
  4691. :return:
  4692. """
  4693. self.report_usage("convert_any2geo()")
  4694. def initialize(obj_init, app):
  4695. obj_init.solid_geometry = obj.solid_geometry
  4696. try:
  4697. obj_init.follow_geometry = obj.follow_geometry
  4698. except AttributeError:
  4699. pass
  4700. try:
  4701. obj_init.apertures = obj.apertures
  4702. except AttributeError:
  4703. pass
  4704. try:
  4705. if obj.tools:
  4706. obj_init.tools = obj.tools
  4707. except AttributeError:
  4708. pass
  4709. def initialize_excellon(obj_init, app):
  4710. # objs = self.collection.get_selected()
  4711. # GeometryObject.merge(objs, obj)
  4712. solid_geo = []
  4713. for tool in obj.tools:
  4714. for geo in obj.tools[tool]['solid_geometry']:
  4715. solid_geo.append(geo)
  4716. obj_init.solid_geometry = deepcopy(solid_geo)
  4717. if not self.collection.get_selected():
  4718. log.warning("App.convert_any2geo --> No object selected")
  4719. self.inform.emit('[WARNING_NOTCL] %s' %
  4720. _("No object is selected. Select an object and try again."))
  4721. return
  4722. for obj in self.collection.get_selected():
  4723. obj_name = obj.options["name"]
  4724. try:
  4725. if isinstance(obj, ExcellonObject):
  4726. self.new_object("geometry", str(obj_name) + "_conv", initialize_excellon)
  4727. else:
  4728. self.new_object("geometry", str(obj_name) + "_conv", initialize)
  4729. except Exception as e:
  4730. return "Operation failed: %s" % str(e)
  4731. def convert_any2gerber(self):
  4732. """
  4733. Will convert any object out of Gerber, Excellon, Geometry to Gerber object.
  4734. :return:
  4735. """
  4736. self.report_usage("convert_any2gerber()")
  4737. def initialize_geometry(obj_init, app):
  4738. apertures = {}
  4739. apid = 0
  4740. apertures[str(apid)] = {}
  4741. apertures[str(apid)]['geometry'] = []
  4742. for obj_orig in obj.solid_geometry:
  4743. new_elem = {}
  4744. new_elem['solid'] = obj_orig
  4745. try:
  4746. new_elem['follow'] = obj_orig.exterior
  4747. except AttributeError:
  4748. pass
  4749. apertures[str(apid)]['geometry'].append(deepcopy(new_elem))
  4750. apertures[str(apid)]['size'] = 0.0
  4751. apertures[str(apid)]['type'] = 'C'
  4752. obj_init.solid_geometry = deepcopy(obj.solid_geometry)
  4753. obj_init.apertures = deepcopy(apertures)
  4754. def initialize_excellon(obj_init, app):
  4755. apertures = {}
  4756. apid = 10
  4757. for tool in obj.tools:
  4758. apertures[str(apid)] = {}
  4759. apertures[str(apid)]['geometry'] = []
  4760. for geo in obj.tools[tool]['solid_geometry']:
  4761. new_el = {}
  4762. new_el['solid'] = geo
  4763. new_el['follow'] = geo.exterior
  4764. apertures[str(apid)]['geometry'].append(deepcopy(new_el))
  4765. apertures[str(apid)]['size'] = float(obj.tools[tool]['C'])
  4766. apertures[str(apid)]['type'] = 'C'
  4767. apid += 1
  4768. # create solid_geometry
  4769. solid_geometry = []
  4770. for apid in apertures:
  4771. for geo_el in apertures[apid]['geometry']:
  4772. solid_geometry.append(geo_el['solid'])
  4773. solid_geometry = MultiPolygon(solid_geometry)
  4774. solid_geometry = solid_geometry.buffer(0.0000001)
  4775. obj_init.solid_geometry = deepcopy(solid_geometry)
  4776. obj_init.apertures = deepcopy(apertures)
  4777. # clear the working objects (perhaps not necessary due of Python GC)
  4778. apertures.clear()
  4779. if not self.collection.get_selected():
  4780. log.warning("App.convert_any2gerber --> No object selected")
  4781. self.inform.emit('[WARNING_NOTCL] %s' %
  4782. _("No object is selected. Select an object and try again."))
  4783. return
  4784. for obj in self.collection.get_selected():
  4785. obj_name = obj.options["name"]
  4786. try:
  4787. if isinstance(obj, ExcellonObject):
  4788. self.new_object("gerber", str(obj_name) + "_conv", initialize_excellon)
  4789. elif isinstance(obj, GeometryObject):
  4790. self.new_object("gerber", str(obj_name) + "_conv", initialize_geometry)
  4791. else:
  4792. log.warning("App.convert_any2gerber --> This is no vaild object for conversion.")
  4793. except Exception as e:
  4794. return "Operation failed: %s" % str(e)
  4795. def abort_all_tasks(self):
  4796. """
  4797. Executed when a certain key combo is pressed (Ctrl+Alt+X). Will abort current task
  4798. on the first possible occasion.
  4799. :return:
  4800. """
  4801. if self.abort_flag is False:
  4802. self.inform.emit(_("Aborting. The current task will be gracefully closed as soon as possible..."))
  4803. self.abort_flag = True
  4804. self.cleanup.emit()
  4805. def app_is_idle(self):
  4806. if self.abort_flag:
  4807. self.inform.emit('[WARNING_NOTCL] %s' % _("The current task was gracefully closed on user request..."))
  4808. self.abort_flag = False
  4809. def on_selectall(self):
  4810. """
  4811. Will draw a selection box shape around the selected objects.
  4812. :return:
  4813. """
  4814. self.report_usage("on_selectall()")
  4815. # delete the possible selection box around a possible selected object
  4816. self.delete_selection_shape()
  4817. for name in self.collection.get_names():
  4818. self.collection.set_active(name)
  4819. curr_sel_obj = self.collection.get_by_name(name)
  4820. # create the selection box around the selected object
  4821. if self.defaults['global_selection_shape'] is True:
  4822. self.draw_selection_shape(curr_sel_obj)
  4823. def on_preferences(self):
  4824. """
  4825. Adds the Preferences in a Tab in Plot Area
  4826. :return:
  4827. """
  4828. # add the tab if it was closed
  4829. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, _("Preferences"))
  4830. # delete the absolute and relative position and messages in the infobar
  4831. self.ui.position_label.setText("")
  4832. self.ui.rel_position_label.setText("")
  4833. # Switch plot_area to preferences page
  4834. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  4835. # self.ui.show()
  4836. # detect changes in the preferences
  4837. for idx in range(self.ui.pref_tab_area.count()):
  4838. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  4839. try:
  4840. try:
  4841. tb.textEdited.disconnect(self.on_preferences_edited)
  4842. except (TypeError, AttributeError):
  4843. pass
  4844. tb.textEdited.connect(self.on_preferences_edited)
  4845. except AttributeError:
  4846. pass
  4847. try:
  4848. try:
  4849. tb.modificationChanged.disconnect(self.on_preferences_edited)
  4850. except (TypeError, AttributeError):
  4851. pass
  4852. tb.modificationChanged.connect(self.on_preferences_edited)
  4853. except AttributeError:
  4854. pass
  4855. try:
  4856. try:
  4857. tb.toggled.disconnect(self.on_preferences_edited)
  4858. except (TypeError, AttributeError):
  4859. pass
  4860. tb.toggled.connect(self.on_preferences_edited)
  4861. except AttributeError:
  4862. pass
  4863. try:
  4864. try:
  4865. tb.valueChanged.disconnect(self.on_preferences_edited)
  4866. except (TypeError, AttributeError):
  4867. pass
  4868. tb.valueChanged.connect(self.on_preferences_edited)
  4869. except AttributeError:
  4870. pass
  4871. try:
  4872. try:
  4873. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  4874. except (TypeError, AttributeError):
  4875. pass
  4876. tb.currentIndexChanged.connect(self.on_preferences_edited)
  4877. except AttributeError:
  4878. pass
  4879. def on_preferences_edited(self):
  4880. """
  4881. Executed when a preference was changed in the Edit -> Preferences tab.
  4882. Will color the Preferences tab text to Red color.
  4883. :return:
  4884. """
  4885. if self.preferencesUiManager.preferences_changed_flag is False:
  4886. self.inform.emit('[WARNING_NOTCL] %s' % _("Preferences edited but not saved."))
  4887. for idx in range(self.ui.plot_tab_area.count()):
  4888. if self.ui.plot_tab_area.tabText(idx) == _("Preferences"):
  4889. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  4890. self.ui.pref_apply_button.setStyleSheet("QPushButton {color: red;}")
  4891. self.preferencesUiManager.preferences_changed_flag = True
  4892. def on_tools_database(self, source='app'):
  4893. """
  4894. Adds the Tools Database in a Tab in Plot Area.
  4895. :return:
  4896. """
  4897. for idx in range(self.ui.plot_tab_area.count()):
  4898. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4899. # there can be only one instance of Tools Database at one time
  4900. return
  4901. if source == 'app':
  4902. self.tools_db_tab = ToolsDB2(
  4903. app=self,
  4904. parent=self.ui,
  4905. callback_on_edited=self.on_tools_db_edited,
  4906. callback_on_tool_request=self.on_geometry_tool_add_from_db_executed
  4907. )
  4908. elif source == 'ncc':
  4909. self.tools_db_tab = ToolsDB2(
  4910. app=self,
  4911. parent=self.ui,
  4912. callback_on_edited=self.on_tools_db_edited,
  4913. callback_on_tool_request=self.ncclear_tool.on_ncc_tool_add_from_db_executed
  4914. )
  4915. elif source == 'paint':
  4916. self.tools_db_tab = ToolsDB2(
  4917. app=self,
  4918. parent=self.ui,
  4919. callback_on_edited=self.on_tools_db_edited,
  4920. callback_on_tool_request=self.paint_tool.on_paint_tool_add_from_db_executed
  4921. )
  4922. # add the tab if it was closed
  4923. try:
  4924. self.ui.plot_tab_area.addTab(self.tools_db_tab, _("Tools Database"))
  4925. self.tools_db_tab.setObjectName("database_tab")
  4926. except Exception as e:
  4927. log.debug("App.on_tools_database() --> %s" % str(e))
  4928. return
  4929. # delete the absolute and relative position and messages in the infobar
  4930. self.ui.position_label.setText("")
  4931. self.ui.rel_position_label.setText("")
  4932. # Switch plot_area to preferences page
  4933. self.ui.plot_tab_area.setCurrentWidget(self.tools_db_tab)
  4934. # detect changes in the Tools in Tools DB, connect signals from table widget in tab
  4935. self.tools_db_tab.ui_connect()
  4936. def on_tools_db_edited(self):
  4937. """
  4938. Executed whenever a tool is edited in Tools Database.
  4939. Will color the text of the Tools Database tab to Red color.
  4940. :return:
  4941. """
  4942. self.inform.emit('[WARNING_NOTCL] %s' % _("Tools in Tools Database edited but not saved."))
  4943. for idx in range(self.ui.plot_tab_area.count()):
  4944. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4945. self.ui.plot_tab_area.tabBar.setTabTextColor(idx, QtGui.QColor('red'))
  4946. self.tools_db_changed_flag = True
  4947. def on_geometry_tool_add_from_db_executed(self, tool):
  4948. """
  4949. Here add the tool from DB in the selected geometry object.
  4950. :return:
  4951. """
  4952. tool_from_db = deepcopy(tool)
  4953. obj = self.collection.get_active()
  4954. if isinstance(obj, GeometryObject):
  4955. obj.on_tool_from_db_inserted(tool=tool_from_db)
  4956. # close the tab and delete it
  4957. for idx in range(self.ui.plot_tab_area.count()):
  4958. if self.ui.plot_tab_area.tabText(idx) == _("Tools Database"):
  4959. wdg = self.ui.plot_tab_area.widget(idx)
  4960. wdg.deleteLater()
  4961. self.ui.plot_tab_area.removeTab(idx)
  4962. self.inform.emit('[success] %s' % _("Tool from DB added in Tool Table."))
  4963. else:
  4964. self.inform.emit('[ERROR_NOTCL] %s' % _("Adding tool from DB is not allowed for this object."))
  4965. def on_plot_area_tab_closed(self, title):
  4966. """
  4967. Executed whenever a tab is closed in the Plot Area.
  4968. :param title: The name of the tab that was closed.
  4969. :return:
  4970. """
  4971. if title == _("Preferences"):
  4972. # disconnect
  4973. for idx in range(self.ui.pref_tab_area.count()):
  4974. for tb in self.ui.pref_tab_area.widget(idx).findChildren(QtCore.QObject):
  4975. try:
  4976. tb.textEdited.disconnect(self.on_preferences_edited)
  4977. except (TypeError, AttributeError):
  4978. pass
  4979. try:
  4980. tb.modificationChanged.disconnect(self.on_preferences_edited)
  4981. except (TypeError, AttributeError):
  4982. pass
  4983. try:
  4984. tb.toggled.disconnect(self.on_preferences_edited)
  4985. except (TypeError, AttributeError):
  4986. pass
  4987. try:
  4988. tb.valueChanged.disconnect(self.on_preferences_edited)
  4989. except (TypeError, AttributeError):
  4990. pass
  4991. try:
  4992. tb.currentIndexChanged.disconnect(self.on_preferences_edited)
  4993. except (TypeError, AttributeError):
  4994. pass
  4995. if self.preferencesUiManager.preferences_changed_flag is True:
  4996. msgbox = QtWidgets.QMessageBox()
  4997. msgbox.setText(_("One or more values are changed.\n"
  4998. "Do you want to save the Preferences?"))
  4999. msgbox.setWindowTitle(_("Save Preferences"))
  5000. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  5001. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  5002. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  5003. msgbox.setDefaultButton(bt_yes)
  5004. msgbox.exec_()
  5005. response = msgbox.clickedButton()
  5006. if response == bt_yes:
  5007. self.preferencesUiManager.on_save_button(save_to_file=True)
  5008. self.inform.emit('[success] %s' % _("Preferences saved."))
  5009. else:
  5010. self.preferencesUiManager.preferences_changed_flag = False
  5011. self.inform.emit('')
  5012. return
  5013. if title == _("Tools Database"):
  5014. # disconnect the signals from the table widget in tab
  5015. self.tools_db_tab.ui_disconnect()
  5016. if self.tools_db_changed_flag is True:
  5017. msgbox = QtWidgets.QMessageBox()
  5018. msgbox.setText(_("One or more Tools are edited.\n"
  5019. "Do you want to update the Tools Database?"))
  5020. msgbox.setWindowTitle(_("Save Tools Database"))
  5021. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  5022. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  5023. msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  5024. msgbox.setDefaultButton(bt_yes)
  5025. msgbox.exec_()
  5026. response = msgbox.clickedButton()
  5027. if response == bt_yes:
  5028. self.tools_db_tab.on_save_tools_db()
  5029. self.inform.emit('[success] %s' % "Tools DB saved to file.")
  5030. else:
  5031. self.tools_db_changed_flag = False
  5032. self.inform.emit('')
  5033. return
  5034. self.tools_db_tab.deleteLater()
  5035. if title == _("Code Editor"):
  5036. self.toggle_codeeditor = False
  5037. if title == _("Bookmarks Manager"):
  5038. self.book_dialog_tab.rebuild_actions()
  5039. self.book_dialog_tab.deleteLater()
  5040. def on_flipy(self):
  5041. """
  5042. Executed when the menu entry in Options -> Flip on Y axis is clicked.
  5043. :return:
  5044. """
  5045. self.report_usage("on_flipy()")
  5046. obj_list = self.collection.get_selected()
  5047. xminlist = []
  5048. yminlist = []
  5049. xmaxlist = []
  5050. ymaxlist = []
  5051. if not obj_list:
  5052. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Flip on Y axis."))
  5053. else:
  5054. try:
  5055. # first get a bounding box to fit all
  5056. for obj in obj_list:
  5057. xmin, ymin, xmax, ymax = obj.bounds()
  5058. xminlist.append(xmin)
  5059. yminlist.append(ymin)
  5060. xmaxlist.append(xmax)
  5061. ymaxlist.append(ymax)
  5062. # get the minimum x,y and maximum x,y for all objects selected
  5063. xminimal = min(xminlist)
  5064. yminimal = min(yminlist)
  5065. xmaximal = max(xmaxlist)
  5066. ymaximal = max(ymaxlist)
  5067. px = 0.5 * (xminimal + xmaximal)
  5068. py = 0.5 * (yminimal + ymaximal)
  5069. # execute mirroring
  5070. for obj in obj_list:
  5071. obj.mirror('X', [px, py])
  5072. obj.plot()
  5073. self.object_changed.emit(obj)
  5074. self.inform.emit('[success] %s' %
  5075. _("Flip on Y axis done."))
  5076. except Exception as e:
  5077. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  5078. return
  5079. def on_flipx(self):
  5080. """
  5081. Executed when the menu entry in Options -> Flip on X axis is clicked.
  5082. :return:
  5083. """
  5084. self.report_usage("on_flipx()")
  5085. obj_list = self.collection.get_selected()
  5086. xminlist = []
  5087. yminlist = []
  5088. xmaxlist = []
  5089. ymaxlist = []
  5090. if not obj_list:
  5091. self.inform.emit('[WARNING_NOTCL] %s' %
  5092. _("No object selected to Flip on X axis."))
  5093. else:
  5094. try:
  5095. # first get a bounding box to fit all
  5096. for obj in obj_list:
  5097. xmin, ymin, xmax, ymax = obj.bounds()
  5098. xminlist.append(xmin)
  5099. yminlist.append(ymin)
  5100. xmaxlist.append(xmax)
  5101. ymaxlist.append(ymax)
  5102. # get the minimum x,y and maximum x,y for all objects selected
  5103. xminimal = min(xminlist)
  5104. yminimal = min(yminlist)
  5105. xmaximal = max(xmaxlist)
  5106. ymaximal = max(ymaxlist)
  5107. px = 0.5 * (xminimal + xmaximal)
  5108. py = 0.5 * (yminimal + ymaximal)
  5109. # execute mirroring
  5110. for obj in obj_list:
  5111. obj.mirror('Y', [px, py])
  5112. obj.plot()
  5113. self.object_changed.emit(obj)
  5114. self.inform.emit('[success] %s' %
  5115. _("Flip on X axis done."))
  5116. except Exception as e:
  5117. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Flip action was not executed."), str(e)))
  5118. return
  5119. def on_rotate(self, silent=False, preset=None):
  5120. """
  5121. Executed when Options -> Rotate Selection menu entry is clicked.
  5122. :param silent: If silent is True then use the preset value for the angle of the rotation.
  5123. :param preset: A value to be used as predefined angle for rotation.
  5124. :return:
  5125. """
  5126. self.report_usage("on_rotate()")
  5127. obj_list = self.collection.get_selected()
  5128. xminlist = []
  5129. yminlist = []
  5130. xmaxlist = []
  5131. ymaxlist = []
  5132. if not obj_list:
  5133. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected to Rotate."))
  5134. else:
  5135. if silent is False:
  5136. rotatebox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5137. min=-360, max=360, decimals=4,
  5138. init_val=float(self.defaults['tools_transform_rotate']))
  5139. num, ok = rotatebox.get_value()
  5140. else:
  5141. num = preset
  5142. ok = True
  5143. if ok:
  5144. try:
  5145. # first get a bounding box to fit all
  5146. for obj in obj_list:
  5147. xmin, ymin, xmax, ymax = obj.bounds()
  5148. xminlist.append(xmin)
  5149. yminlist.append(ymin)
  5150. xmaxlist.append(xmax)
  5151. ymaxlist.append(ymax)
  5152. # get the minimum x,y and maximum x,y for all objects selected
  5153. xminimal = min(xminlist)
  5154. yminimal = min(yminlist)
  5155. xmaximal = max(xmaxlist)
  5156. ymaximal = max(ymaxlist)
  5157. px = 0.5 * (xminimal + xmaximal)
  5158. py = 0.5 * (yminimal + ymaximal)
  5159. for sel_obj in obj_list:
  5160. sel_obj.rotate(-float(num), point=(px, py))
  5161. sel_obj.plot()
  5162. self.object_changed.emit(sel_obj)
  5163. self.inform.emit('[success] %s' %
  5164. _("Rotation done."))
  5165. except Exception as e:
  5166. self.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Rotation movement was not executed."), str(e)))
  5167. return
  5168. def on_skewx(self):
  5169. """
  5170. Executed when the menu entry in Options -> Skew on X axis is clicked.
  5171. :return:
  5172. """
  5173. self.report_usage("on_skewx()")
  5174. obj_list = self.collection.get_selected()
  5175. xminlist = []
  5176. yminlist = []
  5177. if not obj_list:
  5178. self.inform.emit('[WARNING_NOTCL] %s' %
  5179. _("No object selected to Skew/Shear on X axis."))
  5180. else:
  5181. skewxbox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5182. min=-360, max=360, decimals=4,
  5183. init_val=float(self.defaults['tools_transform_skew_x']))
  5184. num, ok = skewxbox.get_value()
  5185. if ok:
  5186. # first get a bounding box to fit all
  5187. for obj in obj_list:
  5188. xmin, ymin, xmax, ymax = obj.bounds()
  5189. xminlist.append(xmin)
  5190. yminlist.append(ymin)
  5191. # get the minimum x,y and maximum x,y for all objects selected
  5192. xminimal = min(xminlist)
  5193. yminimal = min(yminlist)
  5194. for obj in obj_list:
  5195. obj.skew(num, 0, point=(xminimal, yminimal))
  5196. obj.plot()
  5197. self.object_changed.emit(obj)
  5198. self.inform.emit('[success] %s' %
  5199. _("Skew on X axis done."))
  5200. def on_skewy(self):
  5201. """
  5202. Executed when the menu entry in Options -> Skew on Y axis is clicked.
  5203. :return:
  5204. """
  5205. self.report_usage("on_skewy()")
  5206. obj_list = self.collection.get_selected()
  5207. xminlist = []
  5208. yminlist = []
  5209. if not obj_list:
  5210. self.inform.emit('[WARNING_NOTCL] %s' %
  5211. _("No object selected to Skew/Shear on Y axis."))
  5212. else:
  5213. skewybox = FCInputDialog(title=_("Transform"), text=_("Enter the Angle value:"),
  5214. min=-360, max=360, decimals=4,
  5215. init_val=float(self.defaults['tools_transform_skew_y']))
  5216. num, ok = skewybox.get_value()
  5217. if ok:
  5218. # first get a bounding box to fit all
  5219. for obj in obj_list:
  5220. xmin, ymin, xmax, ymax = obj.bounds()
  5221. xminlist.append(xmin)
  5222. yminlist.append(ymin)
  5223. # get the minimum x,y and maximum x,y for all objects selected
  5224. xminimal = min(xminlist)
  5225. yminimal = min(yminlist)
  5226. for obj in obj_list:
  5227. obj.skew(0, num, point=(xminimal, yminimal))
  5228. obj.plot()
  5229. self.object_changed.emit(obj)
  5230. self.inform.emit('[success] %s' %
  5231. _("Skew on Y axis done."))
  5232. def on_plots_updated(self):
  5233. """
  5234. Callback used to report when the plots have changed.
  5235. Adjust axes and zooms to fit.
  5236. :return: None
  5237. """
  5238. if self.is_legacy is False:
  5239. self.plotcanvas.update()
  5240. else:
  5241. self.plotcanvas.auto_adjust_axes()
  5242. self.on_zoom_fit(None)
  5243. self.collection.update_view()
  5244. # self.inform.emit(_("Plots updated ..."))
  5245. def on_toolbar_replot(self):
  5246. """
  5247. Callback for toolbar button. Re-plots all objects.
  5248. :return: None
  5249. """
  5250. self.report_usage("on_toolbar_replot")
  5251. self.log.debug("on_toolbar_replot()")
  5252. try:
  5253. self.collection.get_active().read_form()
  5254. except AttributeError:
  5255. self.log.debug("on_toolbar_replot(): AttributeError")
  5256. pass
  5257. self.plot_all()
  5258. def on_row_activated(self, index):
  5259. if index.isValid():
  5260. if index.internalPointer().parent_item != self.collection.root_item:
  5261. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5262. self.collection.on_item_activated(index)
  5263. def on_row_selected(self, obj_name):
  5264. """
  5265. This is a special string; when received it will make all Menu -> Objects entries unchecked
  5266. It mean we clicked outside of the items and deselected all
  5267. :param obj_name:
  5268. :return:
  5269. """
  5270. if obj_name == 'none':
  5271. for act in self.ui.menuobjects.actions():
  5272. act.setChecked(False)
  5273. return
  5274. # get the name of the selected objects and add them to a list
  5275. name_list = []
  5276. for obj in self.collection.get_selected():
  5277. name_list.append(obj.options['name'])
  5278. # set all actions as unchecked but the ones selected make them checked
  5279. for act in self.ui.menuobjects.actions():
  5280. act.setChecked(False)
  5281. if act.text() in name_list:
  5282. act.setChecked(True)
  5283. def on_collection_updated(self, obj, state, old_name):
  5284. """
  5285. Create a menu from the object loaded in the collection.
  5286. :param obj: object that was changed (added, deleted, renamed)
  5287. :param state: what was done with the object. Can be: added, deleted, delete_all, renamed
  5288. :param old_name: the old name of the object before the action that triggered this slot happened
  5289. :return: None
  5290. """
  5291. icon_files = {
  5292. "gerber": self.resource_location + "/flatcam_icon16.png",
  5293. "excellon": self.resource_location + "/drill16.png",
  5294. "cncjob": self.resource_location + "/cnc16.png",
  5295. "geometry": self.resource_location + "/geometry16.png",
  5296. "script": self.resource_location + "/script_new16.png",
  5297. "document": self.resource_location + "/notes16_1.png"
  5298. }
  5299. if state == 'append':
  5300. for act in self.ui.menuobjects.actions():
  5301. try:
  5302. act.triggered.disconnect()
  5303. except TypeError:
  5304. pass
  5305. self.ui.menuobjects.clear()
  5306. gerber_list = []
  5307. exc_list = []
  5308. cncjob_list = []
  5309. geo_list = []
  5310. script_list = []
  5311. doc_list = []
  5312. for name in self.collection.get_names():
  5313. obj_named = self.collection.get_by_name(name)
  5314. if obj_named.kind == 'gerber':
  5315. gerber_list.append(name)
  5316. elif obj_named.kind == 'excellon':
  5317. exc_list.append(name)
  5318. elif obj_named.kind == 'cncjob':
  5319. cncjob_list.append(name)
  5320. elif obj_named.kind == 'geometry':
  5321. geo_list.append(name)
  5322. elif obj_named.kind == 'script':
  5323. script_list.append(name)
  5324. elif obj_named.kind == 'document':
  5325. doc_list.append(name)
  5326. def add_act(o_name):
  5327. obj_for_icon = self.collection.get_by_name(o_name)
  5328. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  5329. add_action.setCheckable(True)
  5330. add_action.setText(o_name)
  5331. add_action.setIcon(QtGui.QIcon(icon_files[obj_for_icon.kind]))
  5332. add_action.triggered.connect(
  5333. lambda: self.collection.set_active(o_name) if add_action.isChecked() is True else
  5334. self.collection.set_inactive(o_name))
  5335. self.ui.menuobjects.addAction(add_action)
  5336. for name in gerber_list:
  5337. add_act(name)
  5338. self.ui.menuobjects.addSeparator()
  5339. for name in exc_list:
  5340. add_act(name)
  5341. self.ui.menuobjects.addSeparator()
  5342. for name in cncjob_list:
  5343. add_act(name)
  5344. self.ui.menuobjects.addSeparator()
  5345. for name in geo_list:
  5346. add_act(name)
  5347. self.ui.menuobjects.addSeparator()
  5348. for name in script_list:
  5349. add_act(name)
  5350. self.ui.menuobjects.addSeparator()
  5351. for name in doc_list:
  5352. add_act(name)
  5353. self.ui.menuobjects.addSeparator()
  5354. self.ui.menuobjects_selall = self.ui.menuobjects.addAction(
  5355. QtGui.QIcon(self.resource_location + '/select_all.png'),
  5356. _('Select All')
  5357. )
  5358. self.ui.menuobjects_unselall = self.ui.menuobjects.addAction(
  5359. QtGui.QIcon(self.resource_location + '/deselect_all32.png'),
  5360. _('Deselect All')
  5361. )
  5362. self.ui.menuobjects_selall.triggered.connect(lambda: self.on_objects_selection(True))
  5363. self.ui.menuobjects_unselall.triggered.connect(lambda: self.on_objects_selection(False))
  5364. elif state == 'delete':
  5365. for act in self.ui.menuobjects.actions():
  5366. if act.text() == obj.options['name']:
  5367. try:
  5368. act.triggered.disconnect()
  5369. except TypeError:
  5370. pass
  5371. self.ui.menuobjects.removeAction(act)
  5372. break
  5373. elif state == 'rename':
  5374. for act in self.ui.menuobjects.actions():
  5375. if act.text() == old_name:
  5376. add_action = QtWidgets.QAction(parent=self.ui.menuobjects)
  5377. add_action.setText(obj.options['name'])
  5378. add_action.setIcon(QtGui.QIcon(icon_files[obj.kind]))
  5379. add_action.triggered.connect(
  5380. lambda: self.collection.set_active(obj.options['name']) if add_action.isChecked() is True else
  5381. self.collection.set_inactive(obj.options['name']))
  5382. self.ui.menuobjects.insertAction(act, add_action)
  5383. try:
  5384. act.triggered.disconnect()
  5385. except TypeError:
  5386. pass
  5387. self.ui.menuobjects.removeAction(act)
  5388. break
  5389. elif state == 'delete_all':
  5390. for act in self.ui.menuobjects.actions():
  5391. try:
  5392. act.triggered.disconnect()
  5393. except TypeError:
  5394. pass
  5395. self.ui.menuobjects.clear()
  5396. self.ui.menuobjects.addSeparator()
  5397. self.ui.menuobjects_selall = self.ui.menuobjects.addAction(
  5398. QtGui.QIcon(self.resource_location + '/select_all.png'),
  5399. _('Select All')
  5400. )
  5401. self.ui.menuobjects_unselall = self.ui.menuobjects.addAction(
  5402. QtGui.QIcon(self.resource_location + '/deselect_all32.png'),
  5403. _('Deselect All')
  5404. )
  5405. self.ui.menuobjects_selall.triggered.connect(lambda: self.on_objects_selection(True))
  5406. self.ui.menuobjects_unselall.triggered.connect(lambda: self.on_objects_selection(False))
  5407. def on_objects_selection(self, on_off):
  5408. obj_list = self.collection.get_names()
  5409. if on_off is True:
  5410. self.collection.set_all_active()
  5411. for act in self.ui.menuobjects.actions():
  5412. try:
  5413. act.setChecked(True)
  5414. except Exception:
  5415. pass
  5416. if obj_list:
  5417. self.inform.emit('[selected] %s' % _("All objects are selected."))
  5418. else:
  5419. self.collection.set_all_inactive()
  5420. for act in self.ui.menuobjects.actions():
  5421. try:
  5422. act.setChecked(False)
  5423. except Exception:
  5424. pass
  5425. if obj_list:
  5426. self.inform.emit('%s' % _("Objects selection is cleared."))
  5427. else:
  5428. self.inform.emit('')
  5429. def grid_status(self):
  5430. if self.ui.grid_snap_btn.isChecked():
  5431. return True
  5432. else:
  5433. return False
  5434. def populate_cmenu_grids(self):
  5435. units = self.defaults['units'].lower()
  5436. # for act in self.ui.cmenu_gridmenu.actions():
  5437. # act.triggered.disconnect()
  5438. self.ui.cmenu_gridmenu.clear()
  5439. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  5440. grid_toggle = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  5441. _("Grid On/Off"))
  5442. grid_toggle.setCheckable(True)
  5443. grid_toggle.setChecked(True) if self.grid_status() else grid_toggle.setChecked(False)
  5444. self.ui.cmenu_gridmenu.addSeparator()
  5445. for grid in sorted_list:
  5446. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/grid32_menu.png'),
  5447. "%s" % str(grid))
  5448. action.triggered.connect(self.set_grid)
  5449. self.ui.cmenu_gridmenu.addSeparator()
  5450. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/plus32.png'),
  5451. _("Add"))
  5452. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon(self.resource_location + '/delete32.png'),
  5453. _("Delete"))
  5454. grid_add.triggered.connect(self.on_grid_add)
  5455. grid_delete.triggered.connect(self.on_grid_delete)
  5456. grid_toggle.triggered.connect(lambda: self.ui.grid_snap_btn.trigger())
  5457. def set_grid(self):
  5458. menu_action = self.sender()
  5459. assert isinstance(menu_action, QtWidgets.QAction), "Expected QAction got %s" % type(menu_action)
  5460. self.ui.grid_gap_x_entry.setText(menu_action.text())
  5461. self.ui.grid_gap_y_entry.setText(menu_action.text())
  5462. def on_grid_add(self):
  5463. # ## Current application units in lower Case
  5464. units = self.defaults['units'].lower()
  5465. grid_add_popup = FCInputDialog(title=_("New Grid ..."),
  5466. text=_('Enter a Grid Value:'),
  5467. min=0.0000, max=99.9999, decimals=4)
  5468. grid_add_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/plus32.png'))
  5469. val, ok = grid_add_popup.get_value()
  5470. if ok:
  5471. if float(val) == 0:
  5472. self.inform.emit('[WARNING_NOTCL] %s' %
  5473. _("Please enter a grid value with non-zero value, in Float format."))
  5474. return
  5475. else:
  5476. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  5477. self.defaults["global_grid_context_menu"][str(units)].append(val)
  5478. self.inform.emit('[success] %s...' %
  5479. _("New Grid added"))
  5480. else:
  5481. self.inform.emit('[WARNING_NOTCL] %s...' %
  5482. _("Grid already exists"))
  5483. else:
  5484. self.inform.emit('[WARNING_NOTCL] %s...' %
  5485. _("Adding New Grid cancelled"))
  5486. def on_grid_delete(self):
  5487. # ## Current application units in lower Case
  5488. units = self.defaults['units'].lower()
  5489. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  5490. text='Enter a Grid Value:',
  5491. min=0.0000, max=99.9999, decimals=4)
  5492. grid_del_popup.setWindowIcon(QtGui.QIcon(self.resource_location + '/delete32.png'))
  5493. val, ok = grid_del_popup.get_value()
  5494. if ok:
  5495. if float(val) == 0:
  5496. self.inform.emit('[WARNING_NOTCL] %s' %
  5497. _("Please enter a grid value with non-zero value, in Float format."))
  5498. return
  5499. else:
  5500. try:
  5501. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  5502. except ValueError:
  5503. self.inform.emit('[ERROR_NOTCL]%s...' %
  5504. _(" Grid Value does not exist"))
  5505. return
  5506. self.inform.emit('[success] %s...' %
  5507. _("Grid Value deleted"))
  5508. else:
  5509. self.inform.emit('[WARNING_NOTCL] %s...' %
  5510. _("Delete Grid value cancelled"))
  5511. def on_shortcut_list(self):
  5512. self.report_usage("on_shortcut_list()")
  5513. # add the tab if it was closed
  5514. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, _("Key Shortcut List"))
  5515. # delete the absolute and relative position and messages in the infobar
  5516. self.ui.position_label.setText("")
  5517. self.ui.rel_position_label.setText("")
  5518. # Switch plot_area to preferences page
  5519. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  5520. # self.ui.show()
  5521. def on_select_tab(self, name):
  5522. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  5523. if self.ui.splitter.sizes()[0] == 0:
  5524. self.ui.splitter.setSizes([1, 1])
  5525. else:
  5526. if self.ui.notebook.currentWidget().objectName() == name + '_tab':
  5527. self.ui.splitter.setSizes([0, 1])
  5528. if name == 'project':
  5529. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5530. elif name == 'selected':
  5531. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5532. elif name == 'tool':
  5533. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  5534. def on_copy_name(self):
  5535. self.report_usage("on_copy_name()")
  5536. obj = self.collection.get_active()
  5537. try:
  5538. name = obj.options["name"]
  5539. except AttributeError:
  5540. log.debug("on_copy_name() --> No object selected to copy it's name")
  5541. self.inform.emit('[WARNING_NOTCL]%s' %
  5542. _(" No object selected to copy it's name"))
  5543. return
  5544. self.clipboard.setText(name)
  5545. self.inform.emit(_("Name copied on clipboard ..."))
  5546. def on_mouse_click_over_plot(self, event):
  5547. """
  5548. Default actions are:
  5549. :param event: Contains information about the event, like which button
  5550. was clicked, the pixel coordinates and the axes coordinates.
  5551. :return: None
  5552. """
  5553. self.pos = []
  5554. if self.is_legacy is False:
  5555. event_pos = event.pos
  5556. # pan_button = 2 if self.defaults["global_pan_button"] == '2'else 3
  5557. # # Set the mouse button for panning
  5558. # self.plotcanvas.view.camera.pan_button_setting = pan_button
  5559. else:
  5560. event_pos = (event.xdata, event.ydata)
  5561. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5562. # pan_button = 3 if self.defaults["global_pan_button"] == '2' else 2
  5563. # So it can receive key presses
  5564. self.plotcanvas.native.setFocus()
  5565. self.pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5566. if self.grid_status():
  5567. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  5568. else:
  5569. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  5570. try:
  5571. if event.button == 1:
  5572. # Reset here the relative coordinates so there is a new reference on the click position
  5573. if self.rel_point1 is None:
  5574. self.rel_point1 = self.pos
  5575. else:
  5576. self.rel_point2 = copy(self.rel_point1)
  5577. self.rel_point1 = self.pos
  5578. self.on_mouse_move_over_plot(event, origin_click=True)
  5579. except Exception as e:
  5580. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  5581. def on_mouse_double_click_over_plot(self, event):
  5582. if event.button == 1:
  5583. self.doubleclick = True
  5584. def on_mouse_move_over_plot(self, event, origin_click=None):
  5585. """
  5586. Callback for the mouse motion event over the plot.
  5587. :param event: Contains information about the event.
  5588. :param origin_click
  5589. :return: None
  5590. """
  5591. if self.is_legacy is False:
  5592. event_pos = event.pos
  5593. if self.defaults["global_pan_button"] == '2':
  5594. pan_button = 2
  5595. else:
  5596. pan_button = 3
  5597. self.event_is_dragging = event.is_dragging
  5598. else:
  5599. event_pos = (event.xdata, event.ydata)
  5600. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5601. if self.defaults["global_pan_button"] == '2':
  5602. pan_button = 3
  5603. else:
  5604. pan_button = 2
  5605. self.event_is_dragging = self.plotcanvas.is_dragging
  5606. # So it can receive key presses but not when the Tcl Shell is active
  5607. if not self.ui.shell_dock.isVisible():
  5608. if not self.plotcanvas.native.hasFocus():
  5609. self.plotcanvas.native.setFocus()
  5610. self.pos_jump = event_pos
  5611. self.ui.popMenu.mouse_is_panning = False
  5612. if origin_click is None:
  5613. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  5614. if event.button == pan_button and self.event_is_dragging == 1:
  5615. # if a popup menu is active don't change mouse_is_panning variable because is not True
  5616. if self.ui.popMenu.popup_active:
  5617. self.ui.popMenu.popup_active = False
  5618. return
  5619. self.ui.popMenu.mouse_is_panning = True
  5620. return
  5621. if self.rel_point1 is not None:
  5622. try: # May fail in case mouse not within axes
  5623. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5624. if self.grid_status():
  5625. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5626. # Update cursor
  5627. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]),
  5628. symbol='++', edge_color=self.cursor_color_3D,
  5629. edge_width=self.defaults["global_cursor_width"],
  5630. size=self.defaults["global_cursor_size"])
  5631. else:
  5632. pos = (pos_canvas[0], pos_canvas[1])
  5633. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  5634. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  5635. self.dx = pos[0] - float(self.rel_point1[0])
  5636. self.dy = pos[1] - float(self.rel_point1[1])
  5637. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  5638. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (self.dx, self.dy))
  5639. self.mouse = [pos[0], pos[1]]
  5640. # if the mouse is moved and the LMB is clicked then the action is a selection
  5641. if self.event_is_dragging == 1 and event.button == 1:
  5642. self.delete_selection_shape()
  5643. if self.dx < 0:
  5644. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  5645. face_color=self.defaults['global_alt_sel_fill'])
  5646. self.selection_type = False
  5647. elif self.dx >= 0:
  5648. self.draw_moving_selection_shape(self.pos, pos)
  5649. self.selection_type = True
  5650. else:
  5651. self.selection_type = None
  5652. else:
  5653. self.selection_type = None
  5654. # hover effect - enabled in Preferences -> General -> GUI Settings
  5655. if self.defaults['global_hover']:
  5656. for obj in self.collection.get_list():
  5657. try:
  5658. # select the object(s) only if it is enabled (plotted)
  5659. if obj.options['plot']:
  5660. if obj not in self.collection.get_selected():
  5661. poly_obj = Polygon(
  5662. [(obj.options['xmin'], obj.options['ymin']),
  5663. (obj.options['xmax'], obj.options['ymin']),
  5664. (obj.options['xmax'], obj.options['ymax']),
  5665. (obj.options['xmin'], obj.options['ymax'])]
  5666. )
  5667. if Point(pos).within(poly_obj):
  5668. if obj.isHovering is False:
  5669. obj.isHovering = True
  5670. obj.notHovering = True
  5671. # create the selection box around the selected object
  5672. self.draw_hover_shape(obj, color='#d1e0e0FF')
  5673. else:
  5674. if obj.notHovering is True:
  5675. obj.notHovering = False
  5676. obj.isHovering = False
  5677. self.delete_hover_shape()
  5678. except Exception:
  5679. # the Exception here will happen if we try to select on screen and we have an
  5680. # newly (and empty) just created Geometry or Excellon object that do not have the
  5681. # xmin, xmax, ymin, ymax options.
  5682. # In this case poly_obj creation (see above) will fail
  5683. pass
  5684. except Exception:
  5685. self.ui.position_label.setText("")
  5686. self.ui.rel_position_label.setText("")
  5687. self.mouse = None
  5688. def on_mouse_click_release_over_plot(self, event):
  5689. """
  5690. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  5691. and has been registered in ''self.__init__()''.
  5692. :param event: contains information about the event.
  5693. :return:
  5694. """
  5695. if self.is_legacy is False:
  5696. event_pos = event.pos
  5697. right_button = 2
  5698. else:
  5699. event_pos = (event.xdata, event.ydata)
  5700. # Matplotlib has the middle and right buttons mapped in reverse compared with VisPy
  5701. right_button = 3
  5702. pos_canvas = self.plotcanvas.translate_coords(event_pos)
  5703. if self.grid_status():
  5704. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  5705. else:
  5706. pos = (pos_canvas[0], pos_canvas[1])
  5707. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  5708. # canvas menu
  5709. if event.button == right_button and self.ui.popMenu.mouse_is_panning is False: # right click
  5710. self.ui.popMenu.mouse_is_panning = False
  5711. self.cursor = QtGui.QCursor()
  5712. self.populate_cmenu_grids()
  5713. self.ui.popMenu.popup(self.cursor.pos())
  5714. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  5715. # selection and then select a type of selection ("enclosing" or "touching")
  5716. if event.button == 1: # left click
  5717. modifiers = QtWidgets.QApplication.keyboardModifiers()
  5718. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  5719. if modifiers == QtCore.Qt.ShiftModifier:
  5720. # do not auto open the Project Tab
  5721. self.click_noproject = True
  5722. self.clipboard.setText(
  5723. self.defaults["global_point_clipboard_format"] %
  5724. (self.decimals, self.pos[0], self.decimals, self.pos[1])
  5725. )
  5726. self.inform.emit('[success] %s' % _("Coordinates copied to clipboard."))
  5727. return
  5728. if self.doubleclick is True:
  5729. self.doubleclick = False
  5730. if self.collection.get_selected():
  5731. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  5732. if self.ui.splitter.sizes()[0] == 0:
  5733. self.ui.splitter.setSizes([1, 1])
  5734. try:
  5735. # delete the selection shape(S) as it may be in the way
  5736. self.delete_selection_shape()
  5737. self.delete_hover_shape()
  5738. except Exception as e:
  5739. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() double click --> Error: %s" % str(e))
  5740. return
  5741. else:
  5742. # WORKAROUND for LEGACY MODE
  5743. if self.is_legacy is True:
  5744. # if there is no move on canvas then we have no dragging selection
  5745. if self.dx == 0 or self.dy == 0:
  5746. self.selection_type = None
  5747. if self.selection_type is not None:
  5748. try:
  5749. self.selection_area_handler(self.pos, pos, self.selection_type)
  5750. self.selection_type = None
  5751. except Exception as e:
  5752. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select area --> Error: %s" % str(e))
  5753. return
  5754. else:
  5755. key_modifier = QtWidgets.QApplication.keyboardModifiers()
  5756. if key_modifier == QtCore.Qt.ShiftModifier:
  5757. mod_key = 'Shift'
  5758. elif key_modifier == QtCore.Qt.ControlModifier:
  5759. mod_key = 'Control'
  5760. else:
  5761. mod_key = None
  5762. try:
  5763. if mod_key == self.defaults["global_mselect_key"]:
  5764. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will
  5765. # deselect, and if it's not selected then it will be selected
  5766. # If there is no active command (self.command_active is None) then we check if we clicked
  5767. # on a object by checking the bounding limits against mouse click position
  5768. if self.command_active is None:
  5769. self.select_objects(key='multisel')
  5770. self.delete_hover_shape()
  5771. else:
  5772. # If there is no active command (self.command_active is None) then we check if we clicked
  5773. # on a object by checking the bounding limits against mouse click position
  5774. if self.command_active is None:
  5775. self.select_objects()
  5776. self.delete_hover_shape()
  5777. except Exception as e:
  5778. log.warning("FlatCAMApp.on_mouse_click_release_over_plot() select click --> Error: %s" % str(e))
  5779. return
  5780. def selection_area_handler(self, start_pos, end_pos, sel_type):
  5781. """
  5782. :param start_pos: mouse position when the selection LMB click was done
  5783. :param end_pos: mouse position when the left mouse button is released
  5784. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  5785. :return:
  5786. """
  5787. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  5788. # delete previous selection shape
  5789. self.delete_selection_shape()
  5790. # make all objects inactive
  5791. self.collection.set_all_inactive()
  5792. for obj in self.collection.get_list():
  5793. try:
  5794. # select the object(s) only if it is enabled (plotted)
  5795. if obj.options['plot']:
  5796. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']),
  5797. (obj.options['xmax'], obj.options['ymin']),
  5798. (obj.options['xmax'], obj.options['ymax']),
  5799. (obj.options['xmin'], obj.options['ymax'])])
  5800. if sel_type is True:
  5801. if poly_obj.within(poly_selection):
  5802. # create the selection box around the selected object
  5803. if self.defaults['global_selection_shape'] is True:
  5804. self.draw_selection_shape(obj)
  5805. self.collection.set_active(obj.options['name'])
  5806. else:
  5807. if poly_selection.intersects(poly_obj):
  5808. # create the selection box around the selected object
  5809. if self.defaults['global_selection_shape'] is True:
  5810. self.draw_selection_shape(obj)
  5811. self.collection.set_active(obj.options['name'])
  5812. obj.selection_shape_drawn = True
  5813. except Exception as e:
  5814. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  5815. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  5816. # In this case poly_obj creation (see above) will fail
  5817. log.debug("App.selection_area_handler() --> %s" % str(e))
  5818. def select_objects(self, key=None):
  5819. """
  5820. Will select objects clicked on canvas
  5821. :param key: for future use in cumulative selection
  5822. :return:
  5823. """
  5824. # list where we store the overlapped objects under our mouse left click position
  5825. if key is None:
  5826. self.objects_under_the_click_list = []
  5827. # Populate the list with the overlapped objects on the click position
  5828. curr_x, curr_y = self.pos
  5829. for obj in self.all_objects_list:
  5830. # ScriptObject and DocumentObject objects can't be selected
  5831. if isinstance(obj, ScriptObject) or isinstance(obj, DocumentObject):
  5832. continue
  5833. if key == 'multisel' and obj.options['name'] in self.objects_under_the_click_list:
  5834. continue
  5835. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  5836. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  5837. if obj.options['name'] not in self.objects_under_the_click_list:
  5838. if obj.options['plot']:
  5839. # add objects to the objects_under_the_click list only if the object is plotted
  5840. # (active and not disabled)
  5841. self.objects_under_the_click_list.append(obj.options['name'])
  5842. try:
  5843. if self.objects_under_the_click_list:
  5844. curr_sel_obj = self.collection.get_active()
  5845. # case when there is only an object under the click and we toggle it
  5846. if len(self.objects_under_the_click_list) == 1:
  5847. if curr_sel_obj is None:
  5848. self.collection.set_active(self.objects_under_the_click_list[0])
  5849. curr_sel_obj = self.collection.get_active()
  5850. # create the selection box around the selected object
  5851. if self.defaults['global_selection_shape'] is True:
  5852. self.draw_selection_shape(curr_sel_obj)
  5853. curr_sel_obj.selection_shape_drawn = True
  5854. elif curr_sel_obj.options['name'] not in self.objects_under_the_click_list:
  5855. self.on_objects_selection(False)
  5856. self.delete_selection_shape()
  5857. curr_sel_obj.selection_shape_drawn = False
  5858. self.collection.set_active(self.objects_under_the_click_list[0])
  5859. curr_sel_obj = self.collection.get_active()
  5860. # create the selection box around the selected object
  5861. if self.defaults['global_selection_shape'] is True:
  5862. self.draw_selection_shape(curr_sel_obj)
  5863. curr_sel_obj.selection_shape_drawn = True
  5864. self.selected_message(curr_sel_obj=curr_sel_obj)
  5865. elif curr_sel_obj.selection_shape_drawn is False:
  5866. if self.defaults['global_selection_shape'] is True:
  5867. self.draw_selection_shape(curr_sel_obj)
  5868. curr_sel_obj.selection_shape_drawn = True
  5869. else:
  5870. self.on_objects_selection(False)
  5871. self.delete_selection_shape()
  5872. if self.call_source != 'app':
  5873. self.call_source = 'app'
  5874. self.selected_message(curr_sel_obj=curr_sel_obj)
  5875. else:
  5876. # If there is no selected object
  5877. # make active the first element of the overlapped objects list
  5878. if self.collection.get_active() is None:
  5879. self.collection.set_active(self.objects_under_the_click_list[0])
  5880. self.collection.get_by_name(self.objects_under_the_click_list[0]).selection_shape_drawn = True
  5881. name_sel_obj = self.collection.get_active().options['name']
  5882. # In case that there is a selected object but it is not in the overlapped object list
  5883. # make that object inactive and activate the first element in the overlapped object list
  5884. if name_sel_obj not in self.objects_under_the_click_list:
  5885. self.collection.set_inactive(name_sel_obj)
  5886. name_sel_obj = self.objects_under_the_click_list[0]
  5887. self.collection.set_active(name_sel_obj)
  5888. else:
  5889. sel_idx = self.objects_under_the_click_list.index(name_sel_obj)
  5890. self.collection.set_all_inactive()
  5891. self.collection.set_active(
  5892. self.objects_under_the_click_list[(sel_idx + 1) % len(self.objects_under_the_click_list)])
  5893. curr_sel_obj = self.collection.get_active()
  5894. # delete the possible selection box around a possible selected object
  5895. self.delete_selection_shape()
  5896. curr_sel_obj.selection_shape_drawn = False
  5897. # create the selection box around the selected object
  5898. if self.defaults['global_selection_shape'] is True:
  5899. self.draw_selection_shape(curr_sel_obj)
  5900. curr_sel_obj.selection_shape_drawn = True
  5901. self.selected_message(curr_sel_obj=curr_sel_obj)
  5902. else:
  5903. # deselect everything
  5904. self.on_objects_selection(False)
  5905. # delete the possible selection box around a possible selected object
  5906. self.delete_selection_shape()
  5907. for o in self.collection.get_list():
  5908. o.selection_shape_drawn = False
  5909. # and as a convenience move the focus to the Project tab because Selected tab is now empty but
  5910. # only when working on App
  5911. if self.call_source == 'app':
  5912. if self.click_noproject is False:
  5913. # if the Tool Tab is in focus don't change focus to Project Tab
  5914. if not self.ui.notebook.currentWidget() is self.ui.tool_tab:
  5915. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  5916. else:
  5917. # restore auto open the Project Tab
  5918. self.click_noproject = False
  5919. # delete any text in the status bar, implicitly the last object name that was selected
  5920. # self.inform.emit("")
  5921. else:
  5922. self.call_source = 'app'
  5923. except Exception as e:
  5924. log.error("[ERROR] Something went bad in App.select_objects(). %s" % str(e))
  5925. def selected_message(self, curr_sel_obj):
  5926. if curr_sel_obj:
  5927. if curr_sel_obj.kind == 'gerber':
  5928. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5929. color='green',
  5930. name=str(curr_sel_obj.options['name']),
  5931. tx=_("selected"))
  5932. )
  5933. elif curr_sel_obj.kind == 'excellon':
  5934. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5935. color='brown',
  5936. name=str(curr_sel_obj.options['name']),
  5937. tx=_("selected"))
  5938. )
  5939. elif curr_sel_obj.kind == 'cncjob':
  5940. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5941. color='blue',
  5942. name=str(curr_sel_obj.options['name']),
  5943. tx=_("selected"))
  5944. )
  5945. elif curr_sel_obj.kind == 'geometry':
  5946. self.inform.emit('[selected]<span style="color:{color};">{name}</span> {tx}'.format(
  5947. color='red',
  5948. name=str(curr_sel_obj.options['name']),
  5949. tx=_("selected"))
  5950. )
  5951. def delete_hover_shape(self):
  5952. self.hover_shapes.clear()
  5953. self.hover_shapes.redraw()
  5954. def draw_hover_shape(self, sel_obj, color=None):
  5955. """
  5956. :param sel_obj: The object for which the hover shape must be drawn
  5957. :param color: The color of the hover shape
  5958. :return: None
  5959. """
  5960. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  5961. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  5962. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  5963. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  5964. hover_rect = Polygon([pt1, pt2, pt3, pt4])
  5965. if self.defaults['units'].upper() == 'MM':
  5966. hover_rect = hover_rect.buffer(-0.1)
  5967. hover_rect = hover_rect.buffer(0.2)
  5968. else:
  5969. hover_rect = hover_rect.buffer(-0.00393)
  5970. hover_rect = hover_rect.buffer(0.00787)
  5971. # if color:
  5972. # face = Color(color)
  5973. # face.alpha = 0.2
  5974. # outline = Color(color, alpha=0.8)
  5975. # else:
  5976. # face = Color(self.defaults['global_sel_fill'])
  5977. # face.alpha = 0.2
  5978. # outline = self.defaults['global_sel_line']
  5979. if color:
  5980. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  5981. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  5982. else:
  5983. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  5984. outline = self.defaults['global_sel_line']
  5985. self.hover_shapes.add(hover_rect, color=outline, face_color=face, update=True, layer=0, tolerance=None)
  5986. if self.is_legacy is True:
  5987. self.hover_shapes.redraw()
  5988. def delete_selection_shape(self):
  5989. self.move_tool.sel_shapes.clear()
  5990. self.move_tool.sel_shapes.redraw()
  5991. def draw_selection_shape(self, sel_obj, color=None):
  5992. """
  5993. Will draw a selection shape around the selected object.
  5994. :param sel_obj: The object for which the selection shape must be drawn
  5995. :param color: The color for the selection shape.
  5996. :return: None
  5997. """
  5998. if sel_obj is None:
  5999. return
  6000. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  6001. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  6002. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  6003. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  6004. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  6005. if self.defaults['units'].upper() == 'MM':
  6006. sel_rect = sel_rect.buffer(-0.1)
  6007. sel_rect = sel_rect.buffer(0.2)
  6008. else:
  6009. sel_rect = sel_rect.buffer(-0.00393)
  6010. sel_rect = sel_rect.buffer(0.00787)
  6011. if color:
  6012. face = color[:-2] + str(hex(int(0.2 * 255)))[2:]
  6013. outline = color[:-2] + str(hex(int(0.8 * 255)))[2:]
  6014. else:
  6015. if self.is_legacy is False:
  6016. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.2 * 255)))[2:]
  6017. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(0.8 * 255)))[2:]
  6018. else:
  6019. face = self.defaults['global_sel_fill'][:-2] + str(hex(int(0.4 * 255)))[2:]
  6020. outline = self.defaults['global_sel_line'][:-2] + str(hex(int(1.0 * 255)))[2:]
  6021. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect,
  6022. color=outline,
  6023. face_color=face,
  6024. update=True,
  6025. layer=0,
  6026. tolerance=None))
  6027. if self.is_legacy is True:
  6028. self.move_tool.sel_shapes.redraw()
  6029. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  6030. """
  6031. Will draw a selection shape when dragging mouse on canvas.
  6032. :param old_coords: Old coordinates
  6033. :param coords: New coordinates
  6034. :param kwargs: Keyword arguments
  6035. :return:
  6036. """
  6037. if 'color' in kwargs:
  6038. color = kwargs['color']
  6039. else:
  6040. color = self.defaults['global_sel_line']
  6041. if 'face_color' in kwargs:
  6042. face_color = kwargs['face_color']
  6043. else:
  6044. face_color = self.defaults['global_sel_fill']
  6045. if 'face_alpha' in kwargs:
  6046. face_alpha = kwargs['face_alpha']
  6047. else:
  6048. face_alpha = 0.3
  6049. x0, y0 = old_coords
  6050. x1, y1 = coords
  6051. pt1 = (x0, y0)
  6052. pt2 = (x1, y0)
  6053. pt3 = (x1, y1)
  6054. pt4 = (x0, y1)
  6055. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  6056. # color_t = Color(face_color)
  6057. # color_t.alpha = face_alpha
  6058. color_t = face_color[:-2] + str(hex(int(face_alpha * 255)))[2:]
  6059. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  6060. layer=0, tolerance=None)
  6061. if self.is_legacy is True:
  6062. self.move_tool.sel_shapes.redraw()
  6063. def on_file_new_click(self):
  6064. """
  6065. Callback for menu item File -> New.
  6066. Executed on clicking the Menu -> File -> New Project
  6067. :return:
  6068. """
  6069. if self.collection.get_list() and self.should_we_save:
  6070. msgbox = QtWidgets.QMessageBox()
  6071. # msgbox.setText("<B>Save changes ...</B>")
  6072. msgbox.setText(_("There are files/objects opened in FlatCAM.\n"
  6073. "Creating a New project will delete them.\n"
  6074. "Do you want to Save the project?"))
  6075. msgbox.setWindowTitle(_("Save changes"))
  6076. msgbox.setWindowIcon(QtGui.QIcon(self.resource_location + '/save_as.png'))
  6077. bt_yes = msgbox.addButton(_('Yes'), QtWidgets.QMessageBox.YesRole)
  6078. bt_no = msgbox.addButton(_('No'), QtWidgets.QMessageBox.NoRole)
  6079. bt_cancel = msgbox.addButton(_('Cancel'), QtWidgets.QMessageBox.RejectRole)
  6080. msgbox.setDefaultButton(bt_yes)
  6081. msgbox.exec_()
  6082. response = msgbox.clickedButton()
  6083. if response == bt_yes:
  6084. self.on_file_saveprojectas()
  6085. elif response == bt_cancel:
  6086. return
  6087. elif response == bt_no:
  6088. self.on_file_new()
  6089. else:
  6090. self.on_file_new()
  6091. self.inform.emit('[success] %s...' % _("New Project created"))
  6092. def on_file_new(self, cli=None):
  6093. """
  6094. Returns the application to its startup state. This method is thread-safe.
  6095. :param cli: Boolean. If True this method was run from command line
  6096. :return: None
  6097. """
  6098. self.report_usage("on_file_new")
  6099. # Remove everything from memory
  6100. App.log.debug("on_file_new()")
  6101. if self.call_source != 'app':
  6102. self.editor2object(cleanup=True)
  6103. # ## EDITOR section
  6104. self.geo_editor = FlatCAMGeoEditor(self)
  6105. self.exc_editor = FlatCAMExcEditor(self)
  6106. self.grb_editor = FlatCAMGrbEditor(self)
  6107. # Clear pool
  6108. self.clear_pool()
  6109. for obj in self.collection.get_list():
  6110. # delete shapes left drawn from mark shape_collections, if any
  6111. if isinstance(obj, GerberObject):
  6112. try:
  6113. for el in obj.mark_shapes:
  6114. obj.mark_shapes[el].clear(update=True)
  6115. obj.mark_shapes[el].enabled = False
  6116. del el
  6117. except AttributeError:
  6118. pass
  6119. # also delete annotation shapes, if any
  6120. elif isinstance(obj, CNCJobObject):
  6121. try:
  6122. obj.text_col.enabled = False
  6123. del obj.text_col
  6124. obj.annotation.clear(update=True)
  6125. del obj.annotation
  6126. except AttributeError:
  6127. pass
  6128. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  6129. self.init_tcl()
  6130. self.delete_selection_shape()
  6131. self.collection.delete_all()
  6132. self.setup_component_editor()
  6133. # Clear project filename
  6134. self.project_filename = None
  6135. # Load the application defaults
  6136. self.load_defaults(filename='current_defaults')
  6137. # Re-fresh project options
  6138. self.on_options_app2project()
  6139. # Init Tools
  6140. self.init_tools()
  6141. if cli is None:
  6142. # Close any Tabs opened in the Plot Tab Area section
  6143. for index in range(self.ui.plot_tab_area.count()):
  6144. self.ui.plot_tab_area.closeTab(index)
  6145. # for whatever reason previous command does not close the last tab so I do it manually
  6146. self.ui.plot_tab_area.closeTab(0)
  6147. # # And then add again the Plot Area
  6148. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  6149. self.ui.plot_tab_area.protectTab(0)
  6150. # take the focus of the Notebook on Project Tab.
  6151. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  6152. self.set_ui_title(name=_("New Project - Not saved"))
  6153. def obj_properties(self):
  6154. """
  6155. Will launch the object Properties Tool
  6156. :return:
  6157. """
  6158. self.report_usage("obj_properties()")
  6159. self.properties_tool.run(toggle=False)
  6160. def on_project_context_save(self):
  6161. """
  6162. Wrapper, will save the object function of it's type
  6163. :return:
  6164. """
  6165. obj = self.collection.get_active()
  6166. if type(obj) == GeometryObject:
  6167. self.on_file_exportdxf()
  6168. elif type(obj) == ExcellonObject:
  6169. self.on_file_saveexcellon()
  6170. elif type(obj) == CNCJobObject:
  6171. obj.on_exportgcode_button_click()
  6172. elif type(obj) == GerberObject:
  6173. self.on_file_savegerber()
  6174. elif type(obj) == ScriptObject:
  6175. self.on_file_savescript()
  6176. elif type(obj) == DocumentObject:
  6177. self.on_file_savedocument()
  6178. def obj_move(self):
  6179. """
  6180. Callback for the Move menu entry in various Context Menu's.
  6181. :return:
  6182. """
  6183. self.report_usage("obj_move()")
  6184. self.move_tool.run(toggle=False)
  6185. def on_fileopengerber(self, signal, name=None):
  6186. """
  6187. File menu callback for opening a Gerber.
  6188. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6189. :param name:
  6190. :return: None
  6191. """
  6192. self.report_usage("on_fileopengerber")
  6193. App.log.debug("on_fileopengerber()")
  6194. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *" \
  6195. ".gko *.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  6196. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd);;" \
  6197. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  6198. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim " \
  6199. "*.mil);;" \
  6200. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  6201. "Allegro Files (*.art);;" \
  6202. "Mentor Files (*.pho *.gdo);;" \
  6203. "All Files (*.*)"
  6204. if name is None:
  6205. try:
  6206. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"),
  6207. directory=self.get_last_folder(),
  6208. filter=_filter_)
  6209. except TypeError:
  6210. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Gerber"), filter=_filter_)
  6211. filenames = [str(filename) for filename in filenames]
  6212. else:
  6213. filenames = [name]
  6214. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6215. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6216. _("Opening Gerber file.")),
  6217. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6218. color=QtGui.QColor("gray"))
  6219. if len(filenames) == 0:
  6220. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6221. else:
  6222. for filename in filenames:
  6223. if filename != '':
  6224. self.worker_task.emit({'fcn': self.open_gerber, 'params': [filename]})
  6225. def on_fileopenexcellon(self, signal, name=None):
  6226. """
  6227. File menu callback for opening an Excellon file.
  6228. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6229. :param name:
  6230. :return: None
  6231. """
  6232. self.report_usage("on_fileopenexcellon")
  6233. App.log.debug("on_fileopenexcellon()")
  6234. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc *.ncd);;" \
  6235. "All Files (*.*)"
  6236. if name is None:
  6237. try:
  6238. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"),
  6239. directory=self.get_last_folder(),
  6240. filter=_filter_)
  6241. except TypeError:
  6242. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open Excellon"), filter=_filter_)
  6243. filenames = [str(filename) for filename in filenames]
  6244. else:
  6245. filenames = [str(name)]
  6246. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6247. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6248. _("Opening Excellon file.")),
  6249. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6250. color=QtGui.QColor("gray"))
  6251. if len(filenames) == 0:
  6252. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  6253. else:
  6254. for filename in filenames:
  6255. if filename != '':
  6256. self.worker_task.emit({'fcn': self.open_excellon, 'params': [filename]})
  6257. def on_fileopengcode(self, signal, name=None):
  6258. """
  6259. File menu call back for opening gcode.
  6260. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6261. :param name:
  6262. :return:
  6263. """
  6264. self.report_usage("on_fileopengcode")
  6265. App.log.debug("on_fileopengcode()")
  6266. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  6267. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  6268. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.sbp *.mpf);;" \
  6269. "All Files (*.*)"
  6270. if name is None:
  6271. try:
  6272. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"),
  6273. directory=self.get_last_folder(),
  6274. filter=_filter_)
  6275. except TypeError:
  6276. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open G-Code"), filter=_filter_)
  6277. filenames = [str(filename) for filename in filenames]
  6278. else:
  6279. filenames = [name]
  6280. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6281. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6282. _("Opening G-Code file.")),
  6283. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6284. color=QtGui.QColor("gray"))
  6285. if len(filenames) == 0:
  6286. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6287. else:
  6288. for filename in filenames:
  6289. if filename != '':
  6290. self.worker_task.emit({'fcn': self.open_gcode, 'params': [filename, None, True]})
  6291. def on_file_openproject(self, signal):
  6292. """
  6293. File menu callback for opening a project.
  6294. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6295. :return: None
  6296. """
  6297. self.report_usage("on_file_openproject")
  6298. App.log.debug("on_file_openproject()")
  6299. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  6300. try:
  6301. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"),
  6302. directory=self.get_last_folder(), filter=_filter_)
  6303. except TypeError:
  6304. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Project"), filter=_filter_)
  6305. # The Qt methods above will return a QString which can cause problems later.
  6306. # So far json.dump() will fail to serialize it.
  6307. # TODO: Improve the serialization methods and remove this fix.
  6308. filename = str(filename)
  6309. if filename == "":
  6310. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6311. else:
  6312. # self.worker_task.emit({'fcn': self.open_project,
  6313. # 'params': [filename]})
  6314. # The above was failing because open_project() is not
  6315. # thread safe. The new_project()
  6316. self.open_project(filename)
  6317. def on_fileopenhpgl2(self, signal, name=None):
  6318. """
  6319. File menu callback for opening a HPGL2.
  6320. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6321. :param name:
  6322. :return: None
  6323. """
  6324. self.report_usage("on_fileopenhpgl2")
  6325. App.log.debug("on_fileopenhpgl2()")
  6326. _filter_ = "HPGL2 Files (*.plt);;" \
  6327. "All Files (*.*)"
  6328. if name is None:
  6329. try:
  6330. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"),
  6331. directory=self.get_last_folder(),
  6332. filter=_filter_)
  6333. except TypeError:
  6334. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open HPGL2"), filter=_filter_)
  6335. filenames = [str(filename) for filename in filenames]
  6336. else:
  6337. filenames = [name]
  6338. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  6339. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6340. _("Opening HPGL2 file.")),
  6341. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6342. color=QtGui.QColor("gray"))
  6343. if len(filenames) == 0:
  6344. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6345. else:
  6346. for filename in filenames:
  6347. if filename != '':
  6348. self.worker_task.emit({'fcn': self.open_hpgl2, 'params': [filename]})
  6349. def on_file_openconfig(self, signal):
  6350. """
  6351. File menu callback for opening a config file.
  6352. :param signal: required because clicking the entry will generate a checked signal which needs a container
  6353. :return: None
  6354. """
  6355. self.report_usage("on_file_openconfig")
  6356. App.log.debug("on_file_openconfig()")
  6357. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  6358. try:
  6359. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6360. directory=self.data_path, filter=_filter_)
  6361. except TypeError:
  6362. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Open Configuration File"),
  6363. filter=_filter_)
  6364. if filename == "":
  6365. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6366. else:
  6367. self.open_config_file(filename)
  6368. def on_file_exportsvg(self):
  6369. """
  6370. Callback for menu item File->Export SVG.
  6371. :return: None
  6372. """
  6373. self.report_usage("on_file_exportsvg")
  6374. App.log.debug("on_file_exportsvg()")
  6375. obj = self.collection.get_active()
  6376. if obj is None:
  6377. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6378. msg = _("Please Select a Geometry object to export")
  6379. msgbox = QtWidgets.QMessageBox()
  6380. msgbox.setInformativeText(msg)
  6381. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6382. msgbox.setDefaultButton(bt_ok)
  6383. msgbox.exec_()
  6384. return
  6385. # Check for more compatible types and add as required
  6386. if (not isinstance(obj, GeometryObject)
  6387. and not isinstance(obj, GerberObject)
  6388. and not isinstance(obj, CNCJobObject)
  6389. and not isinstance(obj, ExcellonObject)):
  6390. msg = '[ERROR_NOTCL] %s' % \
  6391. _("Only Geometry, Gerber and CNCJob objects can be used.")
  6392. msgbox = QtWidgets.QMessageBox()
  6393. msgbox.setInformativeText(msg)
  6394. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6395. msgbox.setDefaultButton(bt_ok)
  6396. msgbox.exec_()
  6397. return
  6398. name = obj.options["name"]
  6399. _filter = "SVG File (*.svg);;All Files (*.*)"
  6400. try:
  6401. filename, _f = FCFileSaveDialog.get_saved_filename(
  6402. caption=_("Export SVG"),
  6403. directory=self.get_last_save_folder() + '/' + str(name) + '_svg',
  6404. filter=_filter)
  6405. except TypeError:
  6406. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export SVG"), filter=_filter)
  6407. filename = str(filename)
  6408. if filename == "":
  6409. self.inform.emit('[WARNING_NOTCL]%s' % _("Cancelled."))
  6410. return
  6411. else:
  6412. self.export_svg(name, filename)
  6413. if self.defaults["global_open_style"] is False:
  6414. self.file_opened.emit("SVG", filename)
  6415. self.file_saved.emit("SVG", filename)
  6416. def on_file_exportpng(self):
  6417. self.report_usage("on_file_exportpng")
  6418. App.log.debug("on_file_exportpng()")
  6419. self.date = str(datetime.today()).rpartition('.')[0]
  6420. self.date = ''.join(c for c in self.date if c not in ':-')
  6421. self.date = self.date.replace(' ', '_')
  6422. if self.is_legacy is False:
  6423. image = _screenshot()
  6424. data = np.asarray(image)
  6425. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  6426. self.inform.emit('[[WARNING_NOTCL]] %s' % _('Data must be a 3D array with last dimension 3 or 4'))
  6427. return
  6428. filter_ = "PNG File (*.png);;All Files (*.*)"
  6429. try:
  6430. filename, _f = FCFileSaveDialog.get_saved_filename(
  6431. caption=_("Export PNG Image"),
  6432. directory=self.get_last_save_folder() + '/png_' + self.date,
  6433. filter=filter_)
  6434. except TypeError:
  6435. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export PNG Image"), filter=filter_)
  6436. filename = str(filename)
  6437. if filename == "":
  6438. self.inform.emit(_("Cancelled."))
  6439. return
  6440. else:
  6441. if self.is_legacy is False:
  6442. write_png(filename, data)
  6443. else:
  6444. self.plotcanvas.figure.savefig(filename)
  6445. if self.defaults["global_open_style"] is False:
  6446. self.file_opened.emit("png", filename)
  6447. self.file_saved.emit("png", filename)
  6448. def on_file_savegerber(self):
  6449. """
  6450. Callback for menu item in Project context menu.
  6451. :return: None
  6452. """
  6453. self.report_usage("on_file_savegerber")
  6454. App.log.debug("on_file_savegerber()")
  6455. obj = self.collection.get_active()
  6456. if obj is None:
  6457. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6458. return
  6459. # Check for more compatible types and add as required
  6460. if not isinstance(obj, GerberObject):
  6461. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6462. return
  6463. name = self.collection.get_active().options["name"]
  6464. _filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  6465. try:
  6466. filename, _f = FCFileSaveDialog.get_saved_filename(
  6467. caption="Save Gerber source file",
  6468. directory=self.get_last_save_folder() + '/' + name,
  6469. filter=_filter)
  6470. except TypeError:
  6471. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Gerber source file"), filter=_filter)
  6472. filename = str(filename)
  6473. if filename == "":
  6474. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6475. return
  6476. else:
  6477. self.save_source_file(name, filename)
  6478. if self.defaults["global_open_style"] is False:
  6479. self.file_opened.emit("Gerber", filename)
  6480. self.file_saved.emit("Gerber", filename)
  6481. def on_file_savescript(self):
  6482. """
  6483. Callback for menu item in Project context menu.
  6484. :return: None
  6485. """
  6486. self.report_usage("on_file_savescript")
  6487. App.log.debug("on_file_savescript()")
  6488. obj = self.collection.get_active()
  6489. if obj is None:
  6490. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6491. return
  6492. # Check for more compatible types and add as required
  6493. if not isinstance(obj, ScriptObject):
  6494. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Script objects can be saved as TCL Script files..."))
  6495. return
  6496. name = self.collection.get_active().options["name"]
  6497. _filter = "FlatCAM Scripts (*.FlatScript);;All Files (*.*)"
  6498. try:
  6499. filename, _f = FCFileSaveDialog.get_saved_filename(
  6500. caption="Save Script source file",
  6501. directory=self.get_last_save_folder() + '/' + name,
  6502. filter=_filter)
  6503. except TypeError:
  6504. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Script source file"), filter=_filter)
  6505. filename = str(filename)
  6506. if filename == "":
  6507. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6508. return
  6509. else:
  6510. self.save_source_file(name, filename)
  6511. if self.defaults["global_open_style"] is False:
  6512. self.file_opened.emit("Script", filename)
  6513. self.file_saved.emit("Script", filename)
  6514. def on_file_savedocument(self):
  6515. """
  6516. Callback for menu item in Project context menu.
  6517. :return: None
  6518. """
  6519. self.report_usage("on_file_savedocument")
  6520. App.log.debug("on_file_savedocument()")
  6521. obj = self.collection.get_active()
  6522. if obj is None:
  6523. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6524. return
  6525. # Check for more compatible types and add as required
  6526. if not isinstance(obj, ScriptObject):
  6527. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Document objects can be saved as Document files..."))
  6528. return
  6529. name = self.collection.get_active().options["name"]
  6530. _filter = "FlatCAM Documents (*.FlatDoc);;All Files (*.*)"
  6531. try:
  6532. filename, _f = FCFileSaveDialog.get_saved_filename(
  6533. caption="Save Document source file",
  6534. directory=self.get_last_save_folder() + '/' + name,
  6535. filter=_filter)
  6536. except TypeError:
  6537. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Document source file"), filter=_filter)
  6538. filename = str(filename)
  6539. if filename == "":
  6540. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6541. return
  6542. else:
  6543. self.save_source_file(name, filename)
  6544. if self.defaults["global_open_style"] is False:
  6545. self.file_opened.emit("Document", filename)
  6546. self.file_saved.emit("Document", filename)
  6547. def on_file_saveexcellon(self):
  6548. """
  6549. Callback for menu item in project context menu.
  6550. :return: None
  6551. """
  6552. self.report_usage("on_file_saveexcellon")
  6553. App.log.debug("on_file_saveexcellon()")
  6554. obj = self.collection.get_active()
  6555. if obj is None:
  6556. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6557. return
  6558. # Check for more compatible types and add as required
  6559. if not isinstance(obj, ExcellonObject):
  6560. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6561. return
  6562. name = self.collection.get_active().options["name"]
  6563. _filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  6564. try:
  6565. filename, _f = FCFileSaveDialog.get_saved_filename(
  6566. caption=_("Save Excellon source file"),
  6567. directory=self.get_last_save_folder() + '/' + name,
  6568. filter=_filter)
  6569. except TypeError:
  6570. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Excellon source file"), filter=_filter)
  6571. filename = str(filename)
  6572. if filename == "":
  6573. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6574. return
  6575. else:
  6576. self.save_source_file(name, filename)
  6577. if self.defaults["global_open_style"] is False:
  6578. self.file_opened.emit("Excellon", filename)
  6579. self.file_saved.emit("Excellon", filename)
  6580. def on_file_exportexcellon(self):
  6581. """
  6582. Callback for menu item File->Export->Excellon.
  6583. :return: None
  6584. """
  6585. self.report_usage("on_file_exportexcellon")
  6586. App.log.debug("on_file_exportexcellon()")
  6587. obj = self.collection.get_active()
  6588. if obj is None:
  6589. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6590. return
  6591. # Check for more compatible types and add as required
  6592. if not isinstance(obj, ExcellonObject):
  6593. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Excellon objects can be saved as Excellon files..."))
  6594. return
  6595. name = self.collection.get_active().options["name"]
  6596. _filter = self.defaults["excellon_save_filters"]
  6597. try:
  6598. filename, _f = FCFileSaveDialog.get_saved_filename(
  6599. caption=_("Export Excellon"),
  6600. directory=self.get_last_save_folder() + '/' + name,
  6601. filter=_filter)
  6602. except TypeError:
  6603. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Excellon"), filter=_filter)
  6604. filename = str(filename)
  6605. if filename == "":
  6606. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6607. return
  6608. else:
  6609. used_extension = filename.rpartition('.')[2]
  6610. obj.update_filters(last_ext=used_extension, filter_string='excellon_save_filters')
  6611. self.export_excellon(name, filename)
  6612. if self.defaults["global_open_style"] is False:
  6613. self.file_opened.emit("Excellon", filename)
  6614. self.file_saved.emit("Excellon", filename)
  6615. def on_file_exportgerber(self):
  6616. """
  6617. Callback for menu item File->Export->Gerber.
  6618. :return: None
  6619. """
  6620. self.report_usage("on_file_exportgerber")
  6621. App.log.debug("on_file_exportgerber()")
  6622. obj = self.collection.get_active()
  6623. if obj is None:
  6624. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6625. return
  6626. # Check for more compatible types and add as required
  6627. if not isinstance(obj, GerberObject):
  6628. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed. Only Gerber objects can be saved as Gerber files..."))
  6629. return
  6630. name = self.collection.get_active().options["name"]
  6631. _filter_ = self.defaults['gerber_save_filters']
  6632. try:
  6633. filename, _f = FCFileSaveDialog.get_saved_filename(
  6634. caption=_("Export Gerber"),
  6635. directory=self.get_last_save_folder() + '/' + name,
  6636. filter=_filter_)
  6637. except TypeError:
  6638. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export Gerber"), filter=_filter_)
  6639. filename = str(filename)
  6640. if filename == "":
  6641. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6642. return
  6643. else:
  6644. used_extension = filename.rpartition('.')[2]
  6645. obj.update_filters(last_ext=used_extension, filter_string='gerber_save_filters')
  6646. self.export_gerber(name, filename)
  6647. if self.defaults["global_open_style"] is False:
  6648. self.file_opened.emit("Gerber", filename)
  6649. self.file_saved.emit("Gerber", filename)
  6650. def on_file_exportdxf(self):
  6651. """
  6652. Callback for menu item File->Export DXF.
  6653. :return: None
  6654. """
  6655. self.report_usage("on_file_exportdxf")
  6656. App.log.debug("on_file_exportdxf()")
  6657. obj = self.collection.get_active()
  6658. if obj is None:
  6659. self.inform.emit('[WARNING_NOTCL] %s' % _("No object selected."))
  6660. msg = _("Please Select a Geometry object to export")
  6661. msgbox = QtWidgets.QMessageBox()
  6662. msgbox.setInformativeText(msg)
  6663. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6664. msgbox.setDefaultButton(bt_ok)
  6665. msgbox.exec_()
  6666. return
  6667. # Check for more compatible types and add as required
  6668. if not isinstance(obj, GeometryObject):
  6669. msg = '[ERROR_NOTCL] %s' % _("Only Geometry objects can be used.")
  6670. msgbox = QtWidgets.QMessageBox()
  6671. msgbox.setInformativeText(msg)
  6672. bt_ok = msgbox.addButton(_('Ok'), QtWidgets.QMessageBox.AcceptRole)
  6673. msgbox.setDefaultButton(bt_ok)
  6674. msgbox.exec_()
  6675. return
  6676. name = self.collection.get_active().options["name"]
  6677. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  6678. try:
  6679. filename, _f = FCFileSaveDialog.get_saved_filename(
  6680. caption=_("Export DXF"),
  6681. directory=self.get_last_save_folder() + '/' + name,
  6682. filter=_filter_)
  6683. except TypeError:
  6684. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Export DXF"), filter=_filter_)
  6685. filename = str(filename)
  6686. if filename == "":
  6687. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6688. return
  6689. else:
  6690. self.export_dxf(name, filename)
  6691. if self.defaults["global_open_style"] is False:
  6692. self.file_opened.emit("DXF", filename)
  6693. self.file_saved.emit("DXF", filename)
  6694. def on_file_importsvg(self, type_of_obj):
  6695. """
  6696. Callback for menu item File->Import SVG.
  6697. :param type_of_obj: to import the SVG as Geometry or as Gerber
  6698. :type type_of_obj: str
  6699. :return: None
  6700. """
  6701. self.report_usage("on_file_importsvg")
  6702. App.log.debug("on_file_importsvg()")
  6703. _filter_ = "SVG File .svg (*.svg);;All Files (*.*)"
  6704. try:
  6705. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6706. directory=self.get_last_folder(), filter=_filter_)
  6707. except TypeError:
  6708. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import SVG"),
  6709. filter=_filter_)
  6710. if type_of_obj != "geometry" and type_of_obj != "gerber":
  6711. type_of_obj = "geometry"
  6712. filenames = [str(filename) for filename in filenames]
  6713. if len(filenames) == 0:
  6714. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6715. else:
  6716. for filename in filenames:
  6717. if filename != '':
  6718. self.worker_task.emit({'fcn': self.import_svg,
  6719. 'params': [filename, type_of_obj]})
  6720. def on_file_importdxf(self, type_of_obj):
  6721. """
  6722. Callback for menu item File->Import DXF.
  6723. :param type_of_obj: to import the DXF as Geometry or as Gerber
  6724. :type type_of_obj: str
  6725. :return: None
  6726. """
  6727. self.report_usage("on_file_importdxf")
  6728. App.log.debug("on_file_importdxf()")
  6729. _filter_ = "DXF File .dxf (*.DXF);;All Files (*.*)"
  6730. try:
  6731. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6732. directory=self.get_last_folder(),
  6733. filter=_filter_)
  6734. except TypeError:
  6735. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Import DXF"),
  6736. filter=_filter_)
  6737. if type_of_obj != "geometry" and type_of_obj != "gerber":
  6738. type_of_obj = "geometry"
  6739. filenames = [str(filename) for filename in filenames]
  6740. if len(filenames) == 0:
  6741. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6742. else:
  6743. for filename in filenames:
  6744. if filename != '':
  6745. self.worker_task.emit({'fcn': self.import_dxf,
  6746. 'params': [filename, type_of_obj]})
  6747. # ###############################################################################################################
  6748. # ### The following section has the functions that are displayed and call the Editor tab CNCJob Tab #############
  6749. # ###############################################################################################################
  6750. def init_code_editor(self, name):
  6751. self.text_editor_tab = TextEditor(app=self, plain_text=True)
  6752. # add the tab if it was closed
  6753. self.ui.plot_tab_area.addTab(self.text_editor_tab, '%s' % name)
  6754. self.text_editor_tab.setObjectName('text_editor_tab')
  6755. # delete the absolute and relative position and messages in the infobar
  6756. self.ui.position_label.setText("")
  6757. self.ui.rel_position_label.setText("")
  6758. # first clear previous text in text editor (if any)
  6759. self.text_editor_tab.code_editor.clear()
  6760. self.text_editor_tab.code_editor.setReadOnly(False)
  6761. self.toggle_codeeditor = True
  6762. self.text_editor_tab.code_editor.completer_enable = False
  6763. self.text_editor_tab.buttonRun.hide()
  6764. # make sure to keep a reference to the code editor
  6765. self.reference_code_editor = self.text_editor_tab.code_editor
  6766. # Switch plot_area to CNCJob tab
  6767. self.ui.plot_tab_area.setCurrentWidget(self.text_editor_tab)
  6768. def on_view_source(self):
  6769. """
  6770. Called when the user wants to see the source file of the selected object
  6771. :return:
  6772. """
  6773. self.inform.emit('%s' % _("Viewing the source code of the selected object."))
  6774. self.proc_container.view.set_busy(_("Loading..."))
  6775. try:
  6776. obj = self.collection.get_active()
  6777. except Exception as e:
  6778. log.debug("App.on_view_source() --> %s" % str(e))
  6779. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  6780. return 'fail'
  6781. if obj is None:
  6782. self.inform.emit('[WARNING_NOTCL] %s' % _("Select an Gerber or Excellon file to view it's source file."))
  6783. return 'fail'
  6784. flt = "All Files (*.*)"
  6785. if obj.kind == 'gerber':
  6786. flt = "Gerber Files .gbr (*.GBR);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6787. elif obj.kind == 'excellon':
  6788. flt = "Excellon Files .drl (*.DRL);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6789. elif obj.kind == 'cncjob':
  6790. flt = "GCode Files .nc (*.NC);;PDF Files .pdf (*.PDF);;All Files (*.*)"
  6791. self.source_editor_tab = TextEditor(app=self, plain_text=True)
  6792. # add the tab if it was closed
  6793. self.ui.plot_tab_area.addTab(self.source_editor_tab, '%s' % _("Source Editor"))
  6794. self.source_editor_tab.setObjectName('source_editor_tab')
  6795. # delete the absolute and relative position and messages in the infobar
  6796. self.ui.position_label.setText("")
  6797. self.ui.rel_position_label.setText("")
  6798. # first clear previous text in text editor (if any)
  6799. self.source_editor_tab.code_editor.clear()
  6800. self.source_editor_tab.code_editor.setReadOnly(False)
  6801. self.source_editor_tab.code_editor.completer_enable = False
  6802. self.source_editor_tab.buttonRun.hide()
  6803. # Switch plot_area to CNCJob tab
  6804. self.ui.plot_tab_area.setCurrentWidget(self.source_editor_tab)
  6805. try:
  6806. self.source_editor_tab.buttonOpen.clicked.disconnect()
  6807. except TypeError:
  6808. pass
  6809. self.source_editor_tab.buttonOpen.clicked.connect(lambda: self.source_editor_tab.handleOpen(filt=flt))
  6810. try:
  6811. self.source_editor_tab.buttonSave.clicked.disconnect()
  6812. except TypeError:
  6813. pass
  6814. self.source_editor_tab.buttonSave.clicked.connect(lambda: self.source_editor_tab.handleSaveGCode(filt=flt))
  6815. # then append the text from GCode to the text editor
  6816. if obj.kind == 'cncjob':
  6817. try:
  6818. file = obj.export_gcode(
  6819. preamble=self.defaults["cncjob_prepend"],
  6820. postamble=self.defaults["cncjob_append"],
  6821. to_file=True)
  6822. if file == 'fail':
  6823. return 'fail'
  6824. except AttributeError:
  6825. self.inform.emit('[WARNING_NOTCL] %s' %
  6826. _("There is no selected object for which to see it's source file code."))
  6827. return 'fail'
  6828. else:
  6829. try:
  6830. file = StringIO(obj.source_file)
  6831. except (AttributeError, TypeError):
  6832. self.inform.emit('[WARNING_NOTCL] %s' %
  6833. _("There is no selected object for which to see it's source file code."))
  6834. return 'fail'
  6835. self.source_editor_tab.t_frame.hide()
  6836. try:
  6837. self.source_editor_tab.code_editor.setPlainText(file.getvalue())
  6838. # for line in file:
  6839. # QtWidgets.QApplication.processEvents()
  6840. # proc_line = str(line).strip('\n')
  6841. # self.source_editor_tab.code_editor.append(proc_line)
  6842. except Exception as e:
  6843. log.debug('App.on_view_source() -->%s' % str(e))
  6844. self.inform.emit('[ERROR] %s: %s' % (_('Failed to load the source code for the selected object'), str(e)))
  6845. return
  6846. self.source_editor_tab.handleTextChanged()
  6847. self.source_editor_tab.t_frame.show()
  6848. self.source_editor_tab.code_editor.moveCursor(QtGui.QTextCursor.Start)
  6849. self.proc_container.view.set_idle()
  6850. # self.ui.show()
  6851. def on_toggle_code_editor(self):
  6852. self.report_usage("on_toggle_code_editor()")
  6853. if self.toggle_codeeditor is False:
  6854. self.init_code_editor(name=_("Code Editor"))
  6855. self.text_editor_tab.buttonOpen.clicked.disconnect()
  6856. self.text_editor_tab.buttonOpen.clicked.connect(self.text_editor_tab.handleOpen)
  6857. self.text_editor_tab.buttonSave.clicked.disconnect()
  6858. self.text_editor_tab.buttonSave.clicked.connect(self.text_editor_tab.handleSaveGCode)
  6859. else:
  6860. for idx in range(self.ui.plot_tab_area.count()):
  6861. if self.ui.plot_tab_area.widget(idx).objectName() == "text_editor_tab":
  6862. self.ui.plot_tab_area.closeTab(idx)
  6863. break
  6864. self.toggle_codeeditor = False
  6865. def on_code_editor_close(self):
  6866. self.toggle_codeeditor = False
  6867. def goto_text_line(self):
  6868. """
  6869. Will scroll a text to the specified text line.
  6870. :return: None
  6871. """
  6872. dia_box = Dialog_box(title=_("Go to Line ..."),
  6873. label=_("Line:"),
  6874. icon=QtGui.QIcon(self.resource_location + '/jump_to16.png'),
  6875. initial_text='')
  6876. try:
  6877. line = int(dia_box.location) - 1
  6878. except (ValueError, TypeError):
  6879. line = 0
  6880. if dia_box.ok:
  6881. # make sure to move first the cursor at the end so after finding the line the line will be positioned
  6882. # at the top of the window
  6883. self.ui.plot_tab_area.currentWidget().code_editor.moveCursor(QTextCursor.End)
  6884. # get the document() of the TextEditor
  6885. doc = self.ui.plot_tab_area.currentWidget().code_editor.document()
  6886. # create a Text Cursor based on the searched line
  6887. cursor = QTextCursor(doc.findBlockByLineNumber(line))
  6888. # set cursor of the code editor with the cursor at the searcehd line
  6889. self.ui.plot_tab_area.currentWidget().code_editor.setTextCursor(cursor)
  6890. def on_filenewscript(self, silent=False, name=None, text=None):
  6891. """
  6892. Will create a new script file and open it in the Code Editor
  6893. :param silent: if True will not display status messages
  6894. :param name: if specified will be the name of the new script
  6895. :param text: pass a source file to the newly created script to be loaded in it
  6896. :return: None
  6897. """
  6898. if silent is False:
  6899. self.inform.emit('[success] %s' % _("New TCL script file created in Code Editor."))
  6900. # delete the absolute and relative position and messages in the infobar
  6901. self.ui.position_label.setText("")
  6902. self.ui.rel_position_label.setText("")
  6903. if name is not None:
  6904. self.new_script_object(name=name, text=text)
  6905. else:
  6906. self.new_script_object(text=text)
  6907. # script_text = script_obj.source_file
  6908. #
  6909. # self.proc_container.view.set_busy(_("Loading..."))
  6910. # script_obj.script_editor_tab.t_frame.hide()
  6911. #
  6912. # script_obj.script_editor_tab.t_frame.show()
  6913. # self.proc_container.view.set_idle()
  6914. def on_fileopenscript(self, name=None, silent=False):
  6915. """
  6916. Will open a Tcl script file into the Code Editor
  6917. :param silent: if True will not display status messages
  6918. :param name: name of a Tcl script file to open
  6919. :return:
  6920. """
  6921. self.report_usage("on_fileopenscript")
  6922. App.log.debug("on_fileopenscript()")
  6923. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6924. "All Files (*.*)"
  6925. if name:
  6926. filenames = [name]
  6927. else:
  6928. try:
  6929. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(
  6930. caption=_("Open TCL script"), directory=self.get_last_folder(), filter=_filter_)
  6931. except TypeError:
  6932. filenames, _f = QtWidgets.QFileDialog.getOpenFileNames(caption=_("Open TCL script"), filter=_filter_)
  6933. if len(filenames) == 0:
  6934. if silent is False:
  6935. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6936. else:
  6937. for filename in filenames:
  6938. if filename != '':
  6939. self.worker_task.emit({'fcn': self.open_script, 'params': [filename]})
  6940. def on_filerunscript(self, name=None, silent=False):
  6941. """
  6942. File menu callback for loading and running a TCL script.
  6943. :param silent: if True will not display status messages
  6944. :param name: name of a Tcl script file to be run by FlatCAM
  6945. :return: None
  6946. """
  6947. self.report_usage("on_filerunscript")
  6948. App.log.debug("on_file_runscript()")
  6949. if name:
  6950. filename = name
  6951. if self.cmd_line_headless != 1:
  6952. self.splash.showMessage('%s: %ssec\n%s' %
  6953. (_("Canvas initialization started.\n"
  6954. "Canvas initialization finished in"), '%.2f' % self.used_time,
  6955. _("Executing ScriptObject file.")
  6956. ),
  6957. alignment=Qt.AlignBottom | Qt.AlignLeft,
  6958. color=QtGui.QColor("gray"))
  6959. else:
  6960. _filter_ = "TCL script .FlatScript (*.FlatScript);;TCL script .tcl (*.TCL);;TCL script .txt (*.TXT);;" \
  6961. "All Files (*.*)"
  6962. try:
  6963. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"),
  6964. directory=self.get_last_folder(), filter=_filter_)
  6965. except TypeError:
  6966. filename, _f = QtWidgets.QFileDialog.getOpenFileName(caption=_("Run TCL script"), filter=_filter_)
  6967. # The Qt methods above will return a QString which can cause problems later.
  6968. # So far json.dump() will fail to serialize it.
  6969. filename = str(filename)
  6970. if filename == "":
  6971. if silent is False:
  6972. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  6973. else:
  6974. if self.cmd_line_headless != 1:
  6975. if self.ui.shell_dock.isHidden():
  6976. self.ui.shell_dock.show()
  6977. try:
  6978. with open(filename, "r") as tcl_script:
  6979. cmd_line_shellfile_content = tcl_script.read()
  6980. if self.cmd_line_headless != 1:
  6981. self.shell.exec_command(cmd_line_shellfile_content)
  6982. else:
  6983. self.shell.exec_command(cmd_line_shellfile_content, no_echo=True)
  6984. if silent is False:
  6985. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor and executed."))
  6986. except Exception as e:
  6987. log.debug("App.on_filerunscript() -> %s" % str(e))
  6988. sys.exit(2)
  6989. def on_file_saveproject(self, silent=False):
  6990. """
  6991. Callback for menu item File->Save Project. Saves the project to
  6992. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  6993. if set to None. The project is saved by calling ``self.save_project()``.
  6994. :param silent: if True will not display status messages
  6995. :return: None
  6996. """
  6997. self.report_usage("on_file_saveproject")
  6998. if self.project_filename is None:
  6999. self.on_file_saveprojectas()
  7000. else:
  7001. self.worker_task.emit({'fcn': self.save_project,
  7002. 'params': [self.project_filename, silent]})
  7003. if self.defaults["global_open_style"] is False:
  7004. self.file_opened.emit("project", self.project_filename)
  7005. self.file_saved.emit("project", self.project_filename)
  7006. self.set_ui_title(name=self.project_filename)
  7007. self.should_we_save = False
  7008. def on_file_saveprojectas(self, make_copy=False, use_thread=True, quit_action=False):
  7009. """
  7010. Callback for menu item File->Save Project As... Opens a file
  7011. chooser and saves the project to the given file via
  7012. ``self.save_project()``.
  7013. :param make_copy if to be create a copy of the project; boolean
  7014. :param use_thread: if to be run in a separate thread; boolean
  7015. :param quit_action: if to be followed by quiting the application; boolean
  7016. :return: None
  7017. """
  7018. self.report_usage("on_file_saveprojectas")
  7019. self.date = str(datetime.today()).rpartition('.')[0]
  7020. self.date = ''.join(c for c in self.date if c not in ':-')
  7021. self.date = self.date.replace(' ', '_')
  7022. filter_ = "FlatCAM Project .FlatPrj (*.FlatPrj);; All Files (*.*)"
  7023. try:
  7024. filename, _f = FCFileSaveDialog.get_saved_filename(
  7025. caption=_("Save Project As ..."),
  7026. directory='{l_save}/{proj}_{date}'.format(l_save=str(self.get_last_save_folder()), date=self.date,
  7027. proj=_("Project")),
  7028. filter=filter_
  7029. )
  7030. except TypeError:
  7031. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Project As ..."), filter=filter_)
  7032. filename = str(filename)
  7033. if filename == '':
  7034. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7035. return
  7036. if use_thread is True:
  7037. self.worker_task.emit({'fcn': self.save_project,
  7038. 'params': [filename, quit_action]})
  7039. else:
  7040. self.save_project(filename, quit_action)
  7041. # self.save_project(filename)
  7042. if self.defaults["global_open_style"] is False:
  7043. self.file_opened.emit("project", filename)
  7044. self.file_saved.emit("project", filename)
  7045. if not make_copy:
  7046. self.project_filename = filename
  7047. self.set_ui_title(name=self.project_filename)
  7048. self.should_we_save = False
  7049. def on_file_save_objects_pdf(self, use_thread=True):
  7050. self.date = str(datetime.today()).rpartition('.')[0]
  7051. self.date = ''.join(c for c in self.date if c not in ':-')
  7052. self.date = self.date.replace(' ', '_')
  7053. try:
  7054. obj_selection = self.collection.get_selected()
  7055. if len(obj_selection) == 1:
  7056. obj_name = str(obj_selection[0].options['name'])
  7057. else:
  7058. obj_name = _("FlatCAM objects print")
  7059. except AttributeError as err:
  7060. log.debug("App.on_file_save_object_pdf() --> %s" % str(err))
  7061. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  7062. return
  7063. if not obj_selection:
  7064. self.inform.emit('[ERROR_NOTCL] %s' % _("No object selected."))
  7065. return
  7066. filter_ = "PDF File .pdf (*.PDF);; All Files (*.*)"
  7067. try:
  7068. filename, _f = FCFileSaveDialog.get_saved_filename(
  7069. caption=_("Save Object as PDF ..."),
  7070. directory='{l_save}/{obj_name}_{date}'.format(l_save=str(self.get_last_save_folder()),
  7071. obj_name=obj_name,
  7072. date=self.date),
  7073. filter=filter_
  7074. )
  7075. except TypeError:
  7076. filename, _f = FCFileSaveDialog.get_saved_filename(caption=_("Save Object as PDF ..."), filter=filter_)
  7077. filename = str(filename)
  7078. if filename == '':
  7079. self.inform.emit('[WARNING_NOTCL] %s' % _("Cancelled."))
  7080. return
  7081. if use_thread is True:
  7082. proc = self.proc_container.new(_("Printing PDF ... Please wait."))
  7083. self.worker_task.emit({'fcn': self.save_pdf, 'params': [filename, obj_selection]})
  7084. else:
  7085. self.save_pdf(filename, obj_selection)
  7086. # self.save_project(filename)
  7087. if self.defaults["global_open_style"] is False:
  7088. self.file_opened.emit("pdf", filename)
  7089. self.file_saved.emit("pdf", filename)
  7090. def save_pdf(self, file_name, obj_selection):
  7091. p_size = self.defaults['global_workspaceT']
  7092. orientation = self.defaults['global_workspace_orientation']
  7093. color = 'black'
  7094. transparency_level = 1.0
  7095. self.pagesize = {}
  7096. self.pagesize.update(
  7097. {
  7098. 'Bounds': None,
  7099. 'A0': (841 * mm, 1189 * mm),
  7100. 'A1': (594 * mm, 841 * mm),
  7101. 'A2': (420 * mm, 594 * mm),
  7102. 'A3': (297 * mm, 420 * mm),
  7103. 'A4': (210 * mm, 297 * mm),
  7104. 'A5': (148 * mm, 210 * mm),
  7105. 'A6': (105 * mm, 148 * mm),
  7106. 'A7': (74 * mm, 105 * mm),
  7107. 'A8': (52 * mm, 74 * mm),
  7108. 'A9': (37 * mm, 52 * mm),
  7109. 'A10': (26 * mm, 37 * mm),
  7110. 'B0': (1000 * mm, 1414 * mm),
  7111. 'B1': (707 * mm, 1000 * mm),
  7112. 'B2': (500 * mm, 707 * mm),
  7113. 'B3': (353 * mm, 500 * mm),
  7114. 'B4': (250 * mm, 353 * mm),
  7115. 'B5': (176 * mm, 250 * mm),
  7116. 'B6': (125 * mm, 176 * mm),
  7117. 'B7': (88 * mm, 125 * mm),
  7118. 'B8': (62 * mm, 88 * mm),
  7119. 'B9': (44 * mm, 62 * mm),
  7120. 'B10': (31 * mm, 44 * mm),
  7121. 'C0': (917 * mm, 1297 * mm),
  7122. 'C1': (648 * mm, 917 * mm),
  7123. 'C2': (458 * mm, 648 * mm),
  7124. 'C3': (324 * mm, 458 * mm),
  7125. 'C4': (229 * mm, 324 * mm),
  7126. 'C5': (162 * mm, 229 * mm),
  7127. 'C6': (114 * mm, 162 * mm),
  7128. 'C7': (81 * mm, 114 * mm),
  7129. 'C8': (57 * mm, 81 * mm),
  7130. 'C9': (40 * mm, 57 * mm),
  7131. 'C10': (28 * mm, 40 * mm),
  7132. # American paper sizes
  7133. 'LETTER': (8.5 * inch, 11 * inch),
  7134. 'LEGAL': (8.5 * inch, 14 * inch),
  7135. 'ELEVENSEVENTEEN': (11 * inch, 17 * inch),
  7136. # From https://en.wikipedia.org/wiki/Paper_size
  7137. 'JUNIOR_LEGAL': (5 * inch, 8 * inch),
  7138. 'HALF_LETTER': (5.5 * inch, 8 * inch),
  7139. 'GOV_LETTER': (8 * inch, 10.5 * inch),
  7140. 'GOV_LEGAL': (8.5 * inch, 13 * inch),
  7141. 'LEDGER': (17 * inch, 11 * inch),
  7142. }
  7143. )
  7144. exported_svg = []
  7145. for obj in obj_selection:
  7146. svg_obj = obj.export_svg(scale_stroke_factor=0.0,
  7147. scale_factor_x=None, scale_factor_y=None,
  7148. skew_factor_x=None, skew_factor_y=None,
  7149. mirror=None)
  7150. if obj.kind.lower() == 'gerber':
  7151. # color = self.defaults["gerber_plot_fill"][:-2]
  7152. color = obj.fill_color[:-2]
  7153. elif obj.kind.lower() == 'excellon':
  7154. color = '#C40000'
  7155. elif obj.kind.lower() == 'geometry':
  7156. color = self.defaults["global_draw_color"]
  7157. # Change the attributes of the exported SVG
  7158. # We don't need stroke-width
  7159. # We set opacity to maximum
  7160. # We set the colour to WHITE
  7161. root = ET.fromstring(svg_obj)
  7162. for child in root:
  7163. child.set('fill', str(color))
  7164. child.set('opacity', str(transparency_level))
  7165. child.set('stroke', str(color))
  7166. exported_svg.append(ET.tostring(root))
  7167. xmin = Inf
  7168. ymin = Inf
  7169. xmax = -Inf
  7170. ymax = -Inf
  7171. for obj in obj_selection:
  7172. try:
  7173. gxmin, gymin, gxmax, gymax = obj.bounds()
  7174. xmin = min([xmin, gxmin])
  7175. ymin = min([ymin, gymin])
  7176. xmax = max([xmax, gxmax])
  7177. ymax = max([ymax, gymax])
  7178. except Exception as e:
  7179. log.warning("DEV WARNING: Tried to get bounds of empty geometry in App.save_pdf(). %s" % str(e))
  7180. # Determine bounding area for svg export
  7181. bounds = [xmin, ymin, xmax, ymax]
  7182. size = bounds[2] - bounds[0], bounds[3] - bounds[1]
  7183. # This contain the measure units
  7184. uom = obj_selection[0].units.lower()
  7185. # Define a boundary around SVG of about 1.0mm (~39mils)
  7186. if uom in "mm":
  7187. boundary = 1.0
  7188. else:
  7189. boundary = 0.0393701
  7190. # Convert everything to strings for use in the xml doc
  7191. svgwidth = str(size[0] + (2 * boundary))
  7192. svgheight = str(size[1] + (2 * boundary))
  7193. minx = str(bounds[0] - boundary)
  7194. miny = str(bounds[1] + boundary + size[1])
  7195. # Add a SVG Header and footer to the svg output from shapely
  7196. # The transform flips the Y Axis so that everything renders
  7197. # properly within svg apps such as inkscape
  7198. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7199. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7200. svg_header += 'width="' + svgwidth + uom + '" '
  7201. svg_header += 'height="' + svgheight + uom + '" '
  7202. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  7203. svg_header += '>'
  7204. svg_header += '<g transform="scale(1,-1)">'
  7205. svg_footer = '</g> </svg>'
  7206. svg_elem = str(svg_header)
  7207. for svg_item in exported_svg:
  7208. svg_elem += str(svg_item)
  7209. svg_elem += str(svg_footer)
  7210. # Parse the xml through a xml parser just to add line feeds
  7211. # and to make it look more pretty for the output
  7212. doc = parse_xml_string(svg_elem)
  7213. doc_final = doc.toprettyxml()
  7214. try:
  7215. if self.defaults['units'].upper() == 'IN':
  7216. unit = inch
  7217. else:
  7218. unit = mm
  7219. doc_final = StringIO(doc_final)
  7220. drawing = svg2rlg(doc_final)
  7221. if p_size == 'Bounds':
  7222. renderPDF.drawToFile(drawing, file_name)
  7223. else:
  7224. if orientation == 'p':
  7225. page_size = portrait(self.pagesize[p_size])
  7226. else:
  7227. page_size = landscape(self.pagesize[p_size])
  7228. my_canvas = canvas.Canvas(file_name, pagesize=page_size)
  7229. my_canvas.translate(bounds[0] * unit, bounds[1] * unit)
  7230. renderPDF.draw(drawing, my_canvas, 0, 0)
  7231. my_canvas.save()
  7232. except Exception as e:
  7233. log.debug("App.save_pdf() --> PDF output --> %s" % str(e))
  7234. return 'fail'
  7235. self.inform.emit('[success] %s: %s' % (_("PDF file saved to"), file_name))
  7236. def export_svg(self, obj_name, filename, scale_stroke_factor=0.00):
  7237. """
  7238. Exports a Geometry Object to an SVG file.
  7239. :param obj_name: the name of the FlatCAM object to be saved as SVG
  7240. :param filename: Path to the SVG file to save to.
  7241. :param scale_stroke_factor: factor by which to change/scale the thickness of the features
  7242. :return:
  7243. """
  7244. self.report_usage("export_svg()")
  7245. if filename is None:
  7246. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7247. is not None else self.defaults["global_last_folder"]
  7248. self.log.debug("export_svg()")
  7249. try:
  7250. obj = self.collection.get_by_name(str(obj_name))
  7251. except Exception:
  7252. # TODO: The return behavior has not been established... should raise exception?
  7253. return "Could not retrieve object: %s" % obj_name
  7254. with self.proc_container.new(_("Exporting SVG")) as proc:
  7255. exported_svg = obj.export_svg(scale_stroke_factor=scale_stroke_factor)
  7256. # Determine bounding area for svg export
  7257. bounds = obj.bounds()
  7258. size = obj.size()
  7259. # Convert everything to strings for use in the xml doc
  7260. svgwidth = str(size[0])
  7261. svgheight = str(size[1])
  7262. minx = str(bounds[0])
  7263. miny = str(bounds[1] - size[1])
  7264. uom = obj.units.lower()
  7265. # Add a SVG Header and footer to the svg output from shapely
  7266. # The transform flips the Y Axis so that everything renders
  7267. # properly within svg apps such as inkscape
  7268. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  7269. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  7270. svg_header += 'width="' + svgwidth + uom + '" '
  7271. svg_header += 'height="' + svgheight + uom + '" '
  7272. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  7273. svg_header += '<g transform="scale(1,-1)">'
  7274. svg_footer = '</g> </svg>'
  7275. svg_elem = svg_header + exported_svg + svg_footer
  7276. # Parse the xml through a xml parser just to add line feeds
  7277. # and to make it look more pretty for the output
  7278. svgcode = parse_xml_string(svg_elem)
  7279. svgcode = svgcode.toprettyxml()
  7280. try:
  7281. with open(filename, 'w') as fp:
  7282. fp.write(svgcode)
  7283. except PermissionError:
  7284. self.inform.emit('[WARNING] %s' %
  7285. _("Permission denied, saving not possible.\n"
  7286. "Most likely another app is holding the file open and not accessible."))
  7287. return 'fail'
  7288. if self.defaults["global_open_style"] is False:
  7289. self.file_opened.emit("SVG", filename)
  7290. self.file_saved.emit("SVG", filename)
  7291. self.inform.emit('[success] %s: %s' % (_("SVG file exported to"), filename))
  7292. def save_source_file(self, obj_name, filename, use_thread=True):
  7293. """
  7294. Exports a FlatCAM Object to an Gerber/Excellon file.
  7295. :param obj_name: the name of the FlatCAM object for which to save it's embedded source file
  7296. :param filename: Path to the Gerber file to save to.
  7297. :param use_thread: if to be run in a separate thread
  7298. :return:
  7299. """
  7300. self.report_usage("save source file()")
  7301. if filename is None:
  7302. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7303. is not None else self.defaults["global_last_folder"]
  7304. self.log.debug("save source file()")
  7305. obj = self.collection.get_by_name(obj_name)
  7306. file_string = StringIO(obj.source_file)
  7307. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7308. if file_string.getvalue() == '':
  7309. self.inform.emit('[ERROR_NOTCL] %s' %
  7310. _("Save cancelled because source file is empty. Try to export the Gerber file."))
  7311. return 'fail'
  7312. try:
  7313. with open(filename, 'w') as file:
  7314. file.writelines('G04*\n')
  7315. file.writelines('G04 %s (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  7316. (obj.kind.upper(), str(self.version), str(self.version_date)))
  7317. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  7318. file.writelines('G04 Created on : %s*\n' % time_string)
  7319. for line in file_string:
  7320. file.writelines(line)
  7321. except PermissionError:
  7322. self.inform.emit('[WARNING] %s' %
  7323. _("Permission denied, saving not possible.\n"
  7324. "Most likely another app is holding the file open and not accessible."))
  7325. return 'fail'
  7326. def export_excellon(self, obj_name, filename, local_use=None, use_thread=True):
  7327. """
  7328. Exports a Excellon Object to an Excellon file.
  7329. :param obj_name: the name of the FlatCAM object to be saved as Excellon
  7330. :param filename: Path to the Excellon file to save to.
  7331. :param local_use:
  7332. :param use_thread: if to be run in a separate thread
  7333. :return:
  7334. """
  7335. self.report_usage("export_excellon()")
  7336. if filename is None:
  7337. if self.defaults["global_last_save_folder"]:
  7338. filename = self.defaults["global_last_save_folder"] + '/' + 'exported_excellon'
  7339. else:
  7340. filename = self.defaults["global_last_folder"] + '/' + 'exported_excellon'
  7341. self.log.debug("export_excellon()")
  7342. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  7343. self.defaults["excellon_exp_decimals"]
  7344. )
  7345. if local_use is None:
  7346. try:
  7347. obj = self.collection.get_by_name(str(obj_name))
  7348. except Exception:
  7349. return "Could not retrieve object: %s" % obj_name
  7350. else:
  7351. obj = local_use
  7352. if not isinstance(obj, ExcellonObject):
  7353. self.inform.emit('[ERROR_NOTCL] %s' %
  7354. _("Failed. Only Excellon objects can be saved as Excellon files..."))
  7355. return
  7356. # updated units
  7357. eunits = self.defaults["excellon_exp_units"]
  7358. ewhole = self.defaults["excellon_exp_integer"]
  7359. efract = self.defaults["excellon_exp_decimals"]
  7360. ezeros = self.defaults["excellon_exp_zeros"]
  7361. eformat = self.defaults["excellon_exp_format"]
  7362. slot_type = self.defaults["excellon_exp_slot_type"]
  7363. fc_units = self.defaults['units'].upper()
  7364. if fc_units == 'MM':
  7365. factor = 1 if eunits == 'METRIC' else 0.03937
  7366. else:
  7367. factor = 25.4 if eunits == 'METRIC' else 1
  7368. def make_excellon():
  7369. try:
  7370. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7371. header = 'M48\n'
  7372. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  7373. (str(self.version), str(self.version_date))
  7374. header += ';Filename: %s' % str(obj_name) + '\n'
  7375. header += ';Created on : %s' % time_str + '\n'
  7376. if eformat == 'dec':
  7377. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor, slot_type=slot_type)
  7378. header += eunits + '\n'
  7379. for tool in obj.tools:
  7380. if eunits == 'METRIC':
  7381. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7382. tool=str(tool),
  7383. dec=2)
  7384. else:
  7385. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7386. tool=str(tool),
  7387. dec=4)
  7388. else:
  7389. if ezeros == 'LZ':
  7390. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7391. form='ndec', e_zeros='LZ', factor=factor,
  7392. slot_type=slot_type)
  7393. header += '%s,%s\n' % (eunits, 'LZ')
  7394. header += format_exc
  7395. for tool in obj.tools:
  7396. if eunits == 'METRIC':
  7397. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7398. tool=str(tool),
  7399. dec=2)
  7400. else:
  7401. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7402. tool=str(tool),
  7403. dec=4)
  7404. else:
  7405. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  7406. form='ndec', e_zeros='TZ', factor=factor,
  7407. slot_type=slot_type)
  7408. header += '%s,%s\n' % (eunits, 'TZ')
  7409. header += format_exc
  7410. for tool in obj.tools:
  7411. if eunits == 'METRIC':
  7412. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7413. tool=str(tool),
  7414. dec=2)
  7415. else:
  7416. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  7417. tool=str(tool),
  7418. dec=4)
  7419. header += '%\n'
  7420. footer = 'M30\n'
  7421. exported_excellon = header
  7422. exported_excellon += excellon_code
  7423. exported_excellon += footer
  7424. if local_use is None:
  7425. try:
  7426. with open(filename, 'w') as fp:
  7427. fp.write(exported_excellon)
  7428. except PermissionError:
  7429. self.inform.emit('[WARNING] %s' %
  7430. _("Permission denied, saving not possible.\n"
  7431. "Most likely another app is holding the file open and not accessible."))
  7432. return 'fail'
  7433. if self.defaults["global_open_style"] is False:
  7434. self.file_opened.emit("Excellon", filename)
  7435. self.file_saved.emit("Excellon", filename)
  7436. self.inform.emit('[success] %s: %s' % (_("Excellon file exported to"), filename))
  7437. else:
  7438. return exported_excellon
  7439. except Exception as e:
  7440. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  7441. return 'fail'
  7442. if use_thread is True:
  7443. with self.proc_container.new(_("Exporting Excellon")) as proc:
  7444. def job_thread_exc(app_obj):
  7445. ret = make_excellon()
  7446. if ret == 'fail':
  7447. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  7448. return
  7449. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7450. else:
  7451. eret = make_excellon()
  7452. if eret == 'fail':
  7453. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Excellon file.'))
  7454. return 'fail'
  7455. if local_use is not None:
  7456. return eret
  7457. def export_gerber(self, obj_name, filename, local_use=None, use_thread=True):
  7458. """
  7459. Exports a Gerber Object to an Gerber file.
  7460. :param obj_name: the name of the FlatCAM object to be saved as Gerber
  7461. :param filename: Path to the Gerber file to save to.
  7462. :param local_use: if the Gerber code is to be saved to a file (None) or used within FlatCAM.
  7463. When not None, the value will be the actual Gerber object for which to create the Gerber code
  7464. :param use_thread: if to be run in a separate thread
  7465. :return:
  7466. """
  7467. self.report_usage("export_gerber()")
  7468. if filename is None:
  7469. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7470. is not None else self.defaults["global_last_folder"]
  7471. self.log.debug("export_gerber()")
  7472. if local_use is None:
  7473. try:
  7474. obj = self.collection.get_by_name(str(obj_name))
  7475. except Exception:
  7476. return "Could not retrieve object: %s" % obj_name
  7477. else:
  7478. obj = local_use
  7479. # updated units
  7480. gunits = self.defaults["gerber_exp_units"]
  7481. gwhole = self.defaults["gerber_exp_integer"]
  7482. gfract = self.defaults["gerber_exp_decimals"]
  7483. gzeros = self.defaults["gerber_exp_zeros"]
  7484. fc_units = self.defaults['units'].upper()
  7485. if fc_units == 'MM':
  7486. factor = 1 if gunits == 'MM' else 0.03937
  7487. else:
  7488. factor = 25.4 if gunits == 'MM' else 1
  7489. def make_gerber():
  7490. try:
  7491. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  7492. header = 'G04*\n'
  7493. header += 'G04 RS-274X GERBER GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' % \
  7494. (str(self.version), str(self.version_date))
  7495. header += 'G04 Filename: %s*' % str(obj_name) + '\n'
  7496. header += 'G04 Created on : %s*' % time_str + '\n'
  7497. header += '%%FS%sAX%s%sY%s%s*%%\n' % (gzeros, gwhole, gfract, gwhole, gfract)
  7498. header += "%MO{units}*%\n".format(units=gunits)
  7499. for apid in obj.apertures:
  7500. if obj.apertures[apid]['type'] == 'C':
  7501. header += "%ADD{apid}{type},{size}*%\n".format(
  7502. apid=str(apid),
  7503. type='C',
  7504. size=(factor * obj.apertures[apid]['size'])
  7505. )
  7506. elif obj.apertures[apid]['type'] == 'R':
  7507. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7508. apid=str(apid),
  7509. type='R',
  7510. width=(factor * obj.apertures[apid]['width']),
  7511. height=(factor * obj.apertures[apid]['height'])
  7512. )
  7513. elif obj.apertures[apid]['type'] == 'O':
  7514. header += "%ADD{apid}{type},{width}X{height}*%\n".format(
  7515. apid=str(apid),
  7516. type='O',
  7517. width=(factor * obj.apertures[apid]['width']),
  7518. height=(factor * obj.apertures[apid]['height'])
  7519. )
  7520. header += '\n'
  7521. # obsolete units but some software may need it
  7522. if gunits == 'IN':
  7523. header += 'G70*\n'
  7524. else:
  7525. header += 'G71*\n'
  7526. # Absolute Mode
  7527. header += 'G90*\n'
  7528. header += 'G01*\n'
  7529. # positive polarity
  7530. header += '%LPD*%\n'
  7531. footer = 'M02*\n'
  7532. gerber_code = obj.export_gerber(gwhole, gfract, g_zeros=gzeros, factor=factor)
  7533. exported_gerber = header
  7534. exported_gerber += gerber_code
  7535. exported_gerber += footer
  7536. if local_use is None:
  7537. try:
  7538. with open(filename, 'w') as fp:
  7539. fp.write(exported_gerber)
  7540. except PermissionError:
  7541. self.inform.emit('[WARNING] %s' %
  7542. _("Permission denied, saving not possible.\n"
  7543. "Most likely another app is holding the file open and not accessible."))
  7544. return 'fail'
  7545. if self.defaults["global_open_style"] is False:
  7546. self.file_opened.emit("Gerber", filename)
  7547. self.file_saved.emit("Gerber", filename)
  7548. self.inform.emit('[success] %s: %s' % (_("Gerber file exported to"), filename))
  7549. else:
  7550. return exported_gerber
  7551. except Exception as e:
  7552. log.debug("App.export_gerber.make_gerber() --> %s" % str(e))
  7553. return 'fail'
  7554. if use_thread is True:
  7555. with self.proc_container.new(_("Exporting Gerber")) as proc:
  7556. def job_thread_grb(app_obj):
  7557. ret = make_gerber()
  7558. if ret == 'fail':
  7559. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  7560. return
  7561. self.worker_task.emit({'fcn': job_thread_grb, 'params': [self]})
  7562. else:
  7563. gret = make_gerber()
  7564. if gret == 'fail':
  7565. self.inform.emit('[ERROR_NOTCL] %s' % _('Could not export Gerber file.'))
  7566. return 'fail'
  7567. if local_use is not None:
  7568. return gret
  7569. def export_dxf(self, obj_name, filename, use_thread=True):
  7570. """
  7571. Exports a Geometry Object to an DXF file.
  7572. :param obj_name: the name of the FlatCAM object to be saved as DXF
  7573. :param filename: Path to the DXF file to save to.
  7574. :param use_thread: if to be run in a separate thread
  7575. :return:
  7576. """
  7577. self.report_usage("export_dxf()")
  7578. if filename is None:
  7579. filename = self.defaults["global_last_save_folder"] if self.defaults["global_last_save_folder"] \
  7580. is not None else self.defaults["global_last_folder"]
  7581. self.log.debug("export_dxf()")
  7582. try:
  7583. obj = self.collection.get_by_name(str(obj_name))
  7584. except Exception:
  7585. # TODO: The return behavior has not been established... should raise exception?
  7586. return "Could not retrieve object: %s" % obj_name
  7587. def make_dxf():
  7588. try:
  7589. dxf_code = obj.export_dxf()
  7590. dxf_code.saveas(filename)
  7591. if self.defaults["global_open_style"] is False:
  7592. self.file_opened.emit("DXF", filename)
  7593. self.file_saved.emit("DXF", filename)
  7594. self.inform.emit('[success] %s: %s' % (_("DXF file exported to"), filename))
  7595. except Exception:
  7596. return 'fail'
  7597. if use_thread is True:
  7598. with self.proc_container.new(_("Exporting DXF")) as proc:
  7599. def job_thread_exc(app_obj):
  7600. ret_dxf_val = make_dxf()
  7601. if ret_dxf_val == 'fail':
  7602. app_obj.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  7603. return
  7604. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  7605. else:
  7606. ret = make_dxf()
  7607. if ret == 'fail':
  7608. self.inform.emit('[WARNING_NOTCL] %s' % _('Could not export DXF file.'))
  7609. return
  7610. def import_svg(self, filename, geo_type='geometry', outname=None):
  7611. """
  7612. Adds a new Geometry Object to the projects and populates
  7613. it with shapes extracted from the SVG file.
  7614. :param filename: Path to the SVG file.
  7615. :param geo_type: Type of FlatCAM object that will be created from SVG
  7616. :param outname:
  7617. :return:
  7618. """
  7619. self.report_usage("import_svg()")
  7620. log.debug("App.import_svg()")
  7621. obj_type = ""
  7622. if geo_type is None or geo_type == "geometry":
  7623. obj_type = "geometry"
  7624. elif geo_type == "gerber":
  7625. obj_type = "gerber"
  7626. else:
  7627. self.inform.emit('[ERROR_NOTCL] %s' %
  7628. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  7629. return
  7630. units = self.defaults['units'].upper()
  7631. def obj_init(geo_obj, app_obj):
  7632. geo_obj.import_svg(filename, obj_type, units=units)
  7633. geo_obj.multigeo = False
  7634. geo_obj.source_file = self.export_gerber(obj_name=name, filename=None, local_use=geo_obj, use_thread=False)
  7635. with self.proc_container.new(_("Importing SVG")) as proc:
  7636. # Object name
  7637. name = outname or filename.split('/')[-1].split('\\')[-1]
  7638. self.new_object(obj_type, name, obj_init, autoselected=False)
  7639. # Register recent file
  7640. self.file_opened.emit("svg", filename)
  7641. # GUI feedback
  7642. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7643. def import_dxf(self, filename, geo_type='geometry', outname=None):
  7644. """
  7645. Adds a new Geometry Object to the projects and populates
  7646. it with shapes extracted from the DXF file.
  7647. :param filename: Path to the DXF file.
  7648. :param geo_type: Type of FlatCAM object that will be created from DXF
  7649. :param outname: Name for the imported Geometry
  7650. :return:
  7651. """
  7652. self.report_usage("import_dxf()")
  7653. obj_type = ""
  7654. if geo_type is None or geo_type == "geometry":
  7655. obj_type = "geometry"
  7656. elif geo_type == "gerber":
  7657. obj_type = geo_type
  7658. else:
  7659. self.inform.emit('[ERROR_NOTCL] %s' %
  7660. _("Not supported type is picked as parameter. Only Geometry and Gerber are supported"))
  7661. return
  7662. units = self.defaults['units'].upper()
  7663. def obj_init(geo_obj, app_obj):
  7664. geo_obj.import_dxf(filename, obj_type, units=units)
  7665. geo_obj.multigeo = False
  7666. with self.proc_container.new(_("Importing DXF")) as proc:
  7667. # Object name
  7668. name = outname or filename.split('/')[-1].split('\\')[-1]
  7669. self.new_object(obj_type, name, obj_init, autoselected=False)
  7670. # Register recent file
  7671. self.file_opened.emit("dxf", filename)
  7672. # GUI feedback
  7673. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7674. def open_gerber(self, filename, outname=None):
  7675. """
  7676. Opens a Gerber file, parses it and creates a new object for
  7677. it in the program. Thread-safe.
  7678. :param outname: Name of the resulting object. None causes the
  7679. name to be that of the file. Str.
  7680. :param filename: Gerber file filename
  7681. :type filename: str
  7682. :return: None
  7683. """
  7684. # How the object should be initialized
  7685. def obj_init(gerber_obj, app_obj):
  7686. assert isinstance(gerber_obj, GerberObject), \
  7687. "Expected to initialize a GerberObject but got %s" % type(gerber_obj)
  7688. # Opening the file happens here
  7689. try:
  7690. gerber_obj.parse_file(filename)
  7691. except IOError:
  7692. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7693. return "fail"
  7694. except ParseError as err:
  7695. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7696. app_obj.log.error(str(err))
  7697. return "fail"
  7698. except Exception as e:
  7699. log.debug("App.open_gerber() --> %s" % str(e))
  7700. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7701. msg += traceback.format_exc()
  7702. app_obj.inform.emit(msg)
  7703. return "fail"
  7704. if gerber_obj.is_empty():
  7705. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7706. _("Object is not Gerber file or empty. Aborting object creation."))
  7707. return "fail"
  7708. App.log.debug("open_gerber()")
  7709. with self.proc_container.new(_("Opening Gerber")) as proc:
  7710. # Object name
  7711. name = outname or filename.split('/')[-1].split('\\')[-1]
  7712. # # ## Object creation # ##
  7713. ret = self.new_object("gerber", name, obj_init, autoselected=False)
  7714. if ret == 'fail':
  7715. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open Gerber failed. Probable not a Gerber file.'))
  7716. return 'fail'
  7717. # Register recent file
  7718. self.file_opened.emit("gerber", filename)
  7719. # GUI feedback
  7720. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7721. def open_excellon(self, filename, outname=None, plot=True):
  7722. """
  7723. Opens an Excellon file, parses it and creates a new object for
  7724. it in the program. Thread-safe.
  7725. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7726. :param filename: Excellon file filename
  7727. :type filename: str
  7728. :param plot: boolean, to plot or not the resulting object
  7729. :return: None
  7730. """
  7731. App.log.debug("open_excellon()")
  7732. # How the object should be initialized
  7733. def obj_init(excellon_obj, app_obj):
  7734. try:
  7735. ret = excellon_obj.parse_file(filename=filename)
  7736. if ret == "fail":
  7737. log.debug("Excellon parsing failed.")
  7738. self.inform.emit('[ERROR_NOTCL] %s' %
  7739. _("This is not Excellon file."))
  7740. return "fail"
  7741. except IOError:
  7742. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  7743. (_("Cannot open file"), filename))
  7744. log.debug("Could not open Excellon object.")
  7745. return "fail"
  7746. except Exception:
  7747. msg = '[ERROR_NOTCL] %s' % \
  7748. _("An internal error has occurred. See shell.\n")
  7749. msg += traceback.format_exc()
  7750. app_obj.inform.emit(msg)
  7751. return "fail"
  7752. ret = excellon_obj.create_geometry()
  7753. if ret == 'fail':
  7754. log.debug("Could not create geometry for Excellon object.")
  7755. return "fail"
  7756. for tool in excellon_obj.tools:
  7757. if excellon_obj.tools[tool]['solid_geometry']:
  7758. return
  7759. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' %
  7760. (_("No geometry found in file"), filename))
  7761. return "fail"
  7762. with self.proc_container.new(_("Opening Excellon.")):
  7763. # Object name
  7764. name = outname or filename.split('/')[-1].split('\\')[-1]
  7765. ret_val = self.new_object("excellon", name, obj_init, autoselected=False, plot=plot)
  7766. if ret_val == 'fail':
  7767. self.inform.emit('[ERROR_NOTCL] %s' %
  7768. _('Open Excellon file failed. Probable not an Excellon file.'))
  7769. return
  7770. # Register recent file
  7771. self.file_opened.emit("excellon", filename)
  7772. # GUI feedback
  7773. self.inform.emit('[success] %s: %s' %
  7774. (_("Opened"), filename))
  7775. def open_gcode(self, filename, outname=None, force_parsing=None, plot=True):
  7776. """
  7777. Opens a G-gcode file, parses it and creates a new object for
  7778. it in the program. Thread-safe.
  7779. :param filename: G-code file filename
  7780. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7781. :param force_parsing:
  7782. :param plot:
  7783. :return: None
  7784. """
  7785. App.log.debug("open_gcode()")
  7786. # How the object should be initialized
  7787. def obj_init(job_obj, app_obj_):
  7788. """
  7789. :param job_obj: the resulting object
  7790. :type app_obj_: App
  7791. """
  7792. assert isinstance(app_obj_, App), \
  7793. "Initializer expected App, got %s" % type(app_obj_)
  7794. app_obj_.inform.emit('%s...' % _("Reading GCode file"))
  7795. try:
  7796. f = open(filename)
  7797. gcode = f.read()
  7798. f.close()
  7799. except IOError:
  7800. app_obj_.inform.emit('[ERROR_NOTCL] %s: %s' %
  7801. (_("Failed to open"), filename))
  7802. return "fail"
  7803. job_obj.gcode = gcode
  7804. gcode_ret = job_obj.gcode_parse(force_parsing=force_parsing)
  7805. if gcode_ret == "fail":
  7806. self.inform.emit('[ERROR_NOTCL] %s' %
  7807. _("This is not GCODE"))
  7808. return "fail"
  7809. job_obj.create_geometry()
  7810. with self.proc_container.new(_("Opening G-Code.")):
  7811. # Object name
  7812. name = outname or filename.split('/')[-1].split('\\')[-1]
  7813. # New object creation and file processing
  7814. obj_ret = self.new_object("cncjob", name, obj_init, autoselected=False, plot=plot)
  7815. if obj_ret == 'fail':
  7816. self.inform.emit('[ERROR_NOTCL] %s' %
  7817. _("Failed to create CNCJob Object. Probable not a GCode file. "
  7818. "Try to load it from File menu.\n "
  7819. "Attempting to create a FlatCAM CNCJob Object from "
  7820. "G-Code file failed during processing"))
  7821. return "fail"
  7822. # Register recent file
  7823. self.file_opened.emit("cncjob", filename)
  7824. # GUI feedback
  7825. self.inform.emit('[success] %s: %s' %
  7826. (_("Opened"), filename))
  7827. def open_hpgl2(self, filename, outname=None):
  7828. """
  7829. Opens a HPGL2 file, parses it and creates a new object for
  7830. it in the program. Thread-safe.
  7831. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7832. :param filename: HPGL2 file filename
  7833. :return: None
  7834. """
  7835. filename = filename
  7836. # How the object should be initialized
  7837. def obj_init(geo_obj, app_obj):
  7838. assert isinstance(geo_obj, GeometryObject), \
  7839. "Expected to initialize a GeometryObject but got %s" % type(geo_obj)
  7840. # Opening the file happens here
  7841. obj = HPGL2(self)
  7842. try:
  7843. HPGL2.parse_file(obj, filename)
  7844. except IOError:
  7845. app_obj.inform.emit('[ERROR_NOTCL] %s: %s' % (_("Failed to open file"), filename))
  7846. return "fail"
  7847. except ParseError as err:
  7848. app_obj.inform.emit('[ERROR_NOTCL] %s: %s. %s' % (_("Failed to parse file"), filename, str(err)))
  7849. app_obj.log.error(str(err))
  7850. return "fail"
  7851. except Exception as e:
  7852. log.debug("App.open_hpgl2() --> %s" % str(e))
  7853. msg = '[ERROR] %s' % _("An internal error has occurred. See shell.\n")
  7854. msg += traceback.format_exc()
  7855. app_obj.inform.emit(msg)
  7856. return "fail"
  7857. geo_obj.multigeo = True
  7858. geo_obj.solid_geometry = deepcopy(obj.solid_geometry)
  7859. geo_obj.tools = deepcopy(obj.tools)
  7860. geo_obj.source_file = deepcopy(obj.source_file)
  7861. del obj
  7862. if not geo_obj.solid_geometry:
  7863. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  7864. _("Object is not HPGL2 file or empty. Aborting object creation."))
  7865. return "fail"
  7866. App.log.debug("open_hpgl2()")
  7867. with self.proc_container.new(_("Opening HPGL2")) as proc:
  7868. # Object name
  7869. name = outname or filename.split('/')[-1].split('\\')[-1]
  7870. # # ## Object creation # ##
  7871. ret = self.new_object("geometry", name, obj_init, autoselected=False)
  7872. if ret == 'fail':
  7873. self.inform.emit('[ERROR_NOTCL]%s' % _(' Open HPGL2 failed. Probable not a HPGL2 file.'))
  7874. return 'fail'
  7875. # Register recent file
  7876. self.file_opened.emit("geometry", filename)
  7877. # GUI feedback
  7878. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7879. def open_script(self, filename, outname=None, silent=False):
  7880. """
  7881. Opens a Script file, parses it and creates a new object for
  7882. it in the program. Thread-safe.
  7883. :param outname: Name of the resulting object. None causes the name to be that of the file.
  7884. :param filename: Script file filename
  7885. :return: None
  7886. """
  7887. App.log.debug("open_script()")
  7888. with self.proc_container.new(_("Opening TCL Script...")):
  7889. try:
  7890. with open(filename, "r") as opened_script:
  7891. script_content = opened_script.readlines()
  7892. script_content = ''.join(script_content)
  7893. if silent is False:
  7894. self.inform.emit('[success] %s' % _("TCL script file opened in Code Editor."))
  7895. except Exception as e:
  7896. log.debug("App.open_script() -> %s" % str(e))
  7897. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to open TCL Script."))
  7898. return
  7899. # Object name
  7900. script_name = outname or filename.split('/')[-1].split('\\')[-1]
  7901. # New object creation and file processing
  7902. self.on_filenewscript(name=script_name, text=script_content)
  7903. # Register recent file
  7904. self.file_opened.emit("script", filename)
  7905. # GUI feedback
  7906. self.inform.emit('[success] %s: %s' % (_("Opened"), filename))
  7907. def open_config_file(self, filename, run_from_arg=None):
  7908. """
  7909. Loads a config file from the specified file.
  7910. :param filename: Name of the file from which to load.
  7911. :param run_from_arg: if True the FlatConfig file will be open as an command line argument
  7912. :return: None
  7913. """
  7914. App.log.debug("Opening config file: " + filename)
  7915. if run_from_arg:
  7916. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7917. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7918. _("Opening FlatCAM Config file.")),
  7919. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7920. color=QtGui.QColor("gray"))
  7921. # # add the tab if it was closed
  7922. # self.ui.plot_tab_area.addTab(self.ui.text_editor_tab, _("Code Editor"))
  7923. # # first clear previous text in text editor (if any)
  7924. # self.ui.text_editor_tab.code_editor.clear()
  7925. #
  7926. # # Switch plot_area to CNCJob tab
  7927. # self.ui.plot_tab_area.setCurrentWidget(self.ui.text_editor_tab)
  7928. # close the Code editor if already open
  7929. if self.toggle_codeeditor:
  7930. self.on_toggle_code_editor()
  7931. self.on_toggle_code_editor()
  7932. try:
  7933. if filename:
  7934. f = QtCore.QFile(filename)
  7935. if f.open(QtCore.QIODevice.ReadOnly):
  7936. stream = QtCore.QTextStream(f)
  7937. code_edited = stream.readAll()
  7938. self.text_editor_tab.code_editor.setPlainText(code_edited)
  7939. f.close()
  7940. except IOError:
  7941. App.log.error("Failed to open config file: %s" % filename)
  7942. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  7943. (_("Failed to open config file"), filename))
  7944. return
  7945. def open_project(self, filename, run_from_arg=None, plot=True, cli=None):
  7946. """
  7947. Loads a project from the specified file.
  7948. 1) Loads and parses file
  7949. 2) Registers the file as recently opened.
  7950. 3) Calls on_file_new()
  7951. 4) Updates options
  7952. 5) Calls new_object() with the object's from_dict() as init method.
  7953. 6) Calls plot_all() if plot=True
  7954. :param filename: Name of the file from which to load.
  7955. :param run_from_arg: True if run for arguments
  7956. :param plot: If True plot all objects in the project
  7957. :param cli: Run from command line
  7958. :return: None
  7959. """
  7960. App.log.debug("Opening project: " + filename)
  7961. # block autosaving while a project is loaded
  7962. self.block_autosave = True
  7963. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  7964. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  7965. if cli is None:
  7966. self.set_ui_title(name=_("Loading Project ... Please Wait ..."))
  7967. if run_from_arg:
  7968. self.splash.showMessage('%s: %ssec\n%s' % (_("Canvas initialization started.\n"
  7969. "Canvas initialization finished in"), '%.2f' % self.used_time,
  7970. _("Opening FlatCAM Project file.")),
  7971. alignment=Qt.AlignBottom | Qt.AlignLeft,
  7972. color=QtGui.QColor("gray"))
  7973. # Open and parse an uncompressed Project file
  7974. try:
  7975. f = open(filename, 'r')
  7976. except IOError:
  7977. App.log.error("Failed to open project file: %s" % filename)
  7978. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  7979. (_("Failed to open project file"), filename))
  7980. return
  7981. try:
  7982. d = json.load(f, object_hook=dict2obj)
  7983. except Exception as e:
  7984. App.log.error("Failed to parse project file, trying to see if it loads as an LZMA archive: %s because %s" %
  7985. (filename, str(e)))
  7986. f.close()
  7987. # Open and parse a compressed Project file
  7988. try:
  7989. with lzma.open(filename) as f:
  7990. file_content = f.read().decode('utf-8')
  7991. d = json.loads(file_content, object_hook=dict2obj)
  7992. except Exception as e:
  7993. App.log.error("Failed to open project file: %s with error: %s" % (filename, str(e)))
  7994. self.inform.emit('[ERROR_NOTCL] %s: %s' %
  7995. (_("Failed to open project file"), filename))
  7996. return
  7997. # Clear the current project
  7998. # # NOT THREAD SAFE # ##
  7999. if run_from_arg is True:
  8000. pass
  8001. elif cli is True:
  8002. self.delete_selection_shape()
  8003. else:
  8004. self.on_file_new()
  8005. # Project options
  8006. self.options.update(d['options'])
  8007. self.project_filename = filename
  8008. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8009. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8010. if cli is None:
  8011. self.set_screen_units(self.options["units"])
  8012. # Re create objects
  8013. App.log.debug(" **************** Started PROEJCT loading... **************** ")
  8014. for obj in d['objs']:
  8015. try:
  8016. def obj_init(obj_inst, app_inst):
  8017. obj_inst.from_dict(obj)
  8018. App.log.debug("Recreating from opened project an %s object: %s" %
  8019. (obj['kind'].capitalize(), obj['options']['name']))
  8020. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8021. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8022. if cli is None:
  8023. self.set_ui_title(name="{} {}: {}".format(_("Loading Project ... restoring"),
  8024. obj['kind'].upper(),
  8025. obj['options']['name']
  8026. )
  8027. )
  8028. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=plot)
  8029. except Exception as e:
  8030. print('App.open_project() --> ' + str(e))
  8031. self.inform.emit('[success] %s: %s' % (_("Project loaded from"), filename))
  8032. self.should_we_save = False
  8033. self.file_opened.emit("project", filename)
  8034. # restore autosaving after a project was loaded
  8035. self.block_autosave = False
  8036. # for some reason, setting ui_title does not work when this method is called from Tcl Shell
  8037. # it's because the TclCommand is run in another thread (it inherit TclCommandSignaled)
  8038. if cli is None:
  8039. self.set_ui_title(name=self.project_filename)
  8040. App.log.debug(" **************** Finished PROJECT loading... **************** ")
  8041. def plot_all(self, fit_view=True, use_thread=True):
  8042. """
  8043. Re-generates all plots from all objects.
  8044. :param fit_view: if True will plot the objects and will adjust the zoom to fit all plotted objects into view
  8045. :param use_thread: if True will use threading for plotting the objects
  8046. :return: None
  8047. """
  8048. self.log.debug("Plot_all()")
  8049. self.inform.emit('[success] %s...' % _("Redrawing all objects"))
  8050. for plot_obj in self.collection.get_list():
  8051. def worker_task(obj):
  8052. with self.proc_container.new("Plotting"):
  8053. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  8054. if fit_view is True:
  8055. self.object_plotted.emit(obj)
  8056. if use_thread is True:
  8057. # Send to worker
  8058. self.worker_task.emit({'fcn': worker_task, 'params': [plot_obj]})
  8059. else:
  8060. worker_task(plot_obj)
  8061. def register_folder(self, filename):
  8062. """
  8063. Register the last folder used by the app to open something
  8064. :param filename: the last folder is extracted from the filename
  8065. :return: None
  8066. """
  8067. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  8068. def register_save_folder(self, filename):
  8069. """
  8070. Register the last folder used by the app to save something
  8071. :param filename: the last folder is extracted from the filename
  8072. :return: None
  8073. """
  8074. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  8075. # def set_progress_bar(self, percentage, text=""):
  8076. # """
  8077. # Set a progress bar to a value (percentage)
  8078. #
  8079. # :param percentage: Value set to the progressbar
  8080. # :param text: Not used
  8081. # :return: None
  8082. # """
  8083. # self.ui.progress_bar.setValue(int(percentage))
  8084. def setup_recent_items(self):
  8085. """
  8086. Setup a dictionary with the recent files accessed, organized by type
  8087. :return:
  8088. """
  8089. icons = {
  8090. "gerber": self.resource_location + "/flatcam_icon16.png",
  8091. "excellon": self.resource_location + "/drill16.png",
  8092. 'geometry': self.resource_location + "/geometry16.png",
  8093. "cncjob": self.resource_location + "/cnc16.png",
  8094. "script": self.resource_location + "/script_new24.png",
  8095. "document": self.resource_location + "/notes16_1.png",
  8096. "project": self.resource_location + "/project16.png",
  8097. "svg": self.resource_location + "/geometry16.png",
  8098. "dxf": self.resource_location + "/dxf16.png",
  8099. "pdf": self.resource_location + "/pdf32.png",
  8100. "image": self.resource_location + "/image16.png"
  8101. }
  8102. try:
  8103. image_opener = self.image_tool.import_image
  8104. except AttributeError:
  8105. image_opener = None
  8106. openers = {
  8107. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  8108. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  8109. 'geometry': lambda fname: self.worker_task.emit({'fcn': self.import_dxf, 'params': [fname]}),
  8110. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  8111. "script": lambda fname: self.worker_task.emit({'fcn': self.open_script, 'params': [fname]}),
  8112. "document": None,
  8113. 'project': self.open_project,
  8114. 'svg': self.import_svg,
  8115. 'dxf': self.import_dxf,
  8116. 'image': image_opener,
  8117. 'pdf': lambda fname: self.worker_task.emit({'fcn': self.pdf_tool.open_pdf, 'params': [fname]})
  8118. }
  8119. # Open recent file for files
  8120. try:
  8121. f = open(self.data_path + '/recent.json')
  8122. except IOError:
  8123. App.log.error("Failed to load recent item list.")
  8124. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent item list."))
  8125. return
  8126. try:
  8127. self.recent = json.load(f)
  8128. except json.errors.JSONDecodeError:
  8129. App.log.error("Failed to parse recent item list.")
  8130. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent item list."))
  8131. f.close()
  8132. return
  8133. f.close()
  8134. # Open recent file for projects
  8135. try:
  8136. fp = open(self.data_path + '/recent_projects.json')
  8137. except IOError:
  8138. App.log.error("Failed to load recent project item list.")
  8139. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to load recent projects item list."))
  8140. return
  8141. try:
  8142. self.recent_projects = json.load(fp)
  8143. except json.errors.JSONDecodeError:
  8144. App.log.error("Failed to parse recent project item list.")
  8145. self.inform.emit('[ERROR_NOTCL] %s' % _("Failed to parse recent project item list."))
  8146. fp.close()
  8147. return
  8148. fp.close()
  8149. # Closure needed to create callbacks in a loop.
  8150. # Otherwise late binding occurs.
  8151. def make_callback(func, fname):
  8152. def opener():
  8153. func(fname)
  8154. return opener
  8155. def reset_recent_files():
  8156. # Reset menu
  8157. self.ui.recent.clear()
  8158. self.recent = []
  8159. try:
  8160. ff = open(self.data_path + '/recent.json', 'w')
  8161. except IOError:
  8162. App.log.error("Failed to open recent items file for writing.")
  8163. return
  8164. json.dump(self.recent, ff)
  8165. def reset_recent_projects():
  8166. # Reset menu
  8167. self.ui.recent_projects.clear()
  8168. self.recent_projects = []
  8169. try:
  8170. frp = open(self.data_path + '/recent_projects.json', 'w')
  8171. except IOError:
  8172. App.log.error("Failed to open recent projects items file for writing.")
  8173. return
  8174. json.dump(self.recent, frp)
  8175. # Reset menu
  8176. self.ui.recent.clear()
  8177. self.ui.recent_projects.clear()
  8178. # Create menu items for projects
  8179. for recent in self.recent_projects:
  8180. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  8181. if recent['kind'] == 'project':
  8182. try:
  8183. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  8184. # Attach callback
  8185. o = make_callback(openers[recent["kind"]], recent['filename'])
  8186. action.triggered.connect(o)
  8187. self.ui.recent_projects.addAction(action)
  8188. except KeyError:
  8189. App.log.error("Unsupported file type: %s" % recent["kind"])
  8190. # Last action in Recent Files menu is one that Clear the content
  8191. clear_action_proj = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  8192. (_("Clear Recent projects")), self)
  8193. clear_action_proj.triggered.connect(reset_recent_projects)
  8194. self.ui.recent_projects.addSeparator()
  8195. self.ui.recent_projects.addAction(clear_action_proj)
  8196. # Create menu items for files
  8197. for recent in self.recent:
  8198. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  8199. if recent['kind'] != 'project':
  8200. try:
  8201. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  8202. # Attach callback
  8203. o = make_callback(openers[recent["kind"]], recent['filename'])
  8204. action.triggered.connect(o)
  8205. self.ui.recent.addAction(action)
  8206. except KeyError:
  8207. App.log.error("Unsupported file type: %s" % recent["kind"])
  8208. # Last action in Recent Files menu is one that Clear the content
  8209. clear_action = QtWidgets.QAction(QtGui.QIcon(self.resource_location + '/trash32.png'),
  8210. (_("Clear Recent files")), self)
  8211. clear_action.triggered.connect(reset_recent_files)
  8212. self.ui.recent.addSeparator()
  8213. self.ui.recent.addAction(clear_action)
  8214. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  8215. # self.ui.menufilerecent.set_submenu(recent_menu)
  8216. # recent_menu.show_all()
  8217. # self.ui.recent.show()
  8218. self.log.debug("Recent items list has been populated.")
  8219. def setup_component_editor(self):
  8220. """
  8221. Default text for the Selected tab when is not taken by the Object UI.
  8222. :return:
  8223. """
  8224. # label = QtWidgets.QLabel("Choose an item from Project")
  8225. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  8226. sel_title = QtWidgets.QTextEdit(
  8227. _('<b>Shortcut Key List</b>'))
  8228. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  8229. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  8230. f_settings = QSettings("Open Source", "FlatCAM")
  8231. if f_settings.contains("notebook_font_size"):
  8232. fsize = f_settings.value('notebook_font_size', type=int)
  8233. else:
  8234. fsize = 12
  8235. tsize = fsize + int(fsize / 2)
  8236. # selected_text = (_('''
  8237. # <p><span style="font-size:{tsize}px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span>
  8238. # </p>
  8239. #
  8240. # <p><span style="font-size:{fsize}px"><strong>Details</strong>:<br />
  8241. # The normal flow when working in FlatCAM is the following:</span></p>
  8242. #
  8243. # <ol>
  8244. # <li><span style="font-size:{fsize}px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG
  8245. # file into
  8246. # FlatCAM using either the menu&#39;s, toolbars, key shortcuts or
  8247. # even dragging and dropping the files on the GUI.<br />
  8248. # <br />
  8249. # You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp;
  8250. # drop of the
  8251. # file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  8252. # &nbsp;</li>
  8253. # <li><span style="font-size:{fsize}px">Once an object is available in the Project Tab, by selecting it
  8254. # and then
  8255. # focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the
  8256. # Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to
  8257. # it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  8258. # <br />
  8259. # If the selection of the object is done on the canvas by single click instead, and the
  8260. # <strong>SELECTED TAB</strong>
  8261. # is in focus, again the object properties will be displayed into the Selected Tab. Alternatively,
  8262. # double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate
  8263. # it even if it was out of focus.<br />
  8264. # <br />
  8265. # You can change the parameters in this screen and the flow direction is like this:<br />
  8266. # <br />
  8267. # <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;
  8268. # <strong> Geometry Object
  8269. # </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object
  8270. # </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in
  8271. # <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  8272. # </ol>
  8273. #
  8274. # <p><span style="font-size:{fsize}px">A list of key shortcuts is available through an menu entry in
  8275. # <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut:
  8276. # <strong>F3</strong>.</span></p>
  8277. #
  8278. # ''').format(fsize=fsize, tsize=tsize))
  8279. selected_text = '''
  8280. <p><span style="font-size:{tsize}px"><strong>{title}</strong></span></p>
  8281. <p><span style="font-size:{fsize}px"><strong>{subtitle}</strong>:<br />
  8282. {s1}</span></p>
  8283. <ol>
  8284. <li><span style="font-size:{fsize}px">{s2}<br />
  8285. <br />
  8286. {s3}</span><br />
  8287. &nbsp;</li>
  8288. <li><span style="font-size:{fsize}px">{s4}<br />
  8289. &nbsp;</li>
  8290. <br />
  8291. <li><span style="font-size:{fsize}px">{s5}<br />
  8292. &nbsp;</li>
  8293. <br />
  8294. <li><span style="font-size:{fsize}px">{s6}<br />
  8295. <br />
  8296. {s7}</span></li>
  8297. </ol>
  8298. <p><span style="font-size:{fsize}px">{s8}</span></p>
  8299. '''.format(
  8300. title=_("Selected Tab - Choose an Item from Project Tab"),
  8301. subtitle=_("Details"),
  8302. s1=_("The normal flow when working in FlatCAM is the following:"),
  8303. s2=_("Load/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM "
  8304. "using either the toolbars, key shortcuts or even dragging and dropping the "
  8305. "files on the GUI."),
  8306. s3=_("You can also load a FlatCAM project by double clicking on the project file, "
  8307. "drag and drop of the file into the FLATCAM GUI or through the menu (or toolbar) "
  8308. "actions offered within the app."),
  8309. s4=_("Once an object is available in the Project Tab, by selecting it and then focusing "
  8310. "on SELECTED TAB (more simpler is to double click the object name in the Project Tab, "
  8311. "SELECTED TAB will be updated with the object properties according to its kind: "
  8312. "Gerber, Excellon, Geometry or CNCJob object."),
  8313. s5=_("If the selection of the object is done on the canvas by single click instead, "
  8314. "and the SELECTED TAB is in focus, again the object properties will be displayed into the "
  8315. "Selected Tab. Alternatively, double clicking on the object on the canvas will bring "
  8316. "the SELECTED TAB and populate it even if it was out of focus."),
  8317. s6=_("You can change the parameters in this screen and the flow direction is like this:"),
  8318. s7=_("Gerber/Excellon Object --> Change Parameter --> Generate Geometry --> Geometry Object --> "
  8319. "Add tools (change param in Selected Tab) --> Generate CNCJob --> CNCJob Object --> "
  8320. "Verify GCode (through Edit CNC Code) and/or append/prepend to GCode "
  8321. "(again, done in SELECTED TAB) --> Save GCode."),
  8322. s8=_("A list of key shortcuts is available through an menu entry in Help --> Shortcuts List "
  8323. "or through its own key shortcut: <b>F3</b>."),
  8324. tsize=tsize,
  8325. fsize=fsize
  8326. )
  8327. sel_title.setText(selected_text)
  8328. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  8329. self.ui.selected_scroll_area.setWidget(sel_title)
  8330. def setup_obj_classes(self):
  8331. """
  8332. Sets up application specifics on the FlatCAMObj class. This way the object.app attribute will point to the App
  8333. class.
  8334. :return: None
  8335. """
  8336. FlatCAMObj.app = self
  8337. ObjectCollection.app = self
  8338. Gerber.app = self
  8339. Excellon.app = self
  8340. Geometry.app = self
  8341. CNCjob.app = self
  8342. FCProcess.app = self
  8343. FCProcessContainer.app = self
  8344. OptionsGroupUI.app = self
  8345. def version_check(self):
  8346. """
  8347. Checks for the latest version of the program. Alerts the
  8348. user if theirs is outdated. This method is meant to be run
  8349. in a separate thread.
  8350. :return: None
  8351. """
  8352. self.log.debug("version_check()")
  8353. if self.ui.general_defaults_form.general_app_group.send_stats_cb.get_value() is True:
  8354. full_url = "%s?s=%s&v=%s&os=%s&%s" % (
  8355. App.version_url,
  8356. str(self.defaults['global_serial']),
  8357. str(self.version),
  8358. str(self.os),
  8359. urllib.parse.urlencode(self.defaults["global_stats"])
  8360. )
  8361. # full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + \
  8362. # "&v=" + str(self.version) + "&os=" + str(self.os) + "&" + \
  8363. # urllib.parse.urlencode(self.defaults["global_stats"])
  8364. else:
  8365. # no_stats dict; just so it won't break things on website
  8366. no_ststs_dict = {}
  8367. no_ststs_dict["global_ststs"] = {}
  8368. full_url = App.version_url + "?s=" + str(self.defaults['global_serial']) + "&v=" + str(self.version) +\
  8369. "&os=" + str(self.os) + "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  8370. App.log.debug("Checking for updates @ %s" % full_url)
  8371. # ## Get the data
  8372. try:
  8373. f = urllib.request.urlopen(full_url)
  8374. except Exception:
  8375. # App.log.warning("Failed checking for latest version. Could not connect.")
  8376. self.log.warning("Failed checking for latest version. Could not connect.")
  8377. self.inform.emit('[WARNING_NOTCL] %s' % _("Failed checking for latest version. Could not connect."))
  8378. return
  8379. try:
  8380. data = json.load(f)
  8381. except Exception as e:
  8382. App.log.error("Could not parse information about latest version.")
  8383. self.inform.emit('[ERROR_NOTCL] %s' % _("Could not parse information about latest version."))
  8384. App.log.debug("json.load(): %s" % str(e))
  8385. f.close()
  8386. return
  8387. f.close()
  8388. # ## Latest version?
  8389. if self.version >= data["version"]:
  8390. App.log.debug("FlatCAM is up to date!")
  8391. self.inform.emit('[success] %s' % _("FlatCAM is up to date!"))
  8392. return
  8393. App.log.debug("Newer version available.")
  8394. self.message.emit(
  8395. _("Newer Version Available"),
  8396. '%s<br><br>><b>%s</b><br>%s' % (
  8397. _("There is a newer version of FlatCAM available for download:"),
  8398. str(data["name"]),
  8399. str(data["message"])
  8400. ),
  8401. _("info")
  8402. )
  8403. def on_plotcanvas_setup(self, container=None):
  8404. """
  8405. This is doing the setup for the plot area (canvas).
  8406. :param container: QT Widget where to install the canvas
  8407. :return: None
  8408. """
  8409. if container:
  8410. plot_container = container
  8411. else:
  8412. plot_container = self.ui.right_layout
  8413. modifier = QtWidgets.QApplication.queryKeyboardModifiers()
  8414. if self.is_legacy is True or modifier == QtCore.Qt.ControlModifier:
  8415. self.is_legacy = True
  8416. self.defaults["global_graphic_engine"] = "2D"
  8417. self.plotcanvas = PlotCanvasLegacy(plot_container, self)
  8418. else:
  8419. try:
  8420. self.plotcanvas = PlotCanvas(plot_container, self)
  8421. except Exception as er:
  8422. msg_txt = traceback.format_exc()
  8423. log.debug("App.on_plotcanvas_setup() failed -> %s" % str(er))
  8424. log.debug("OpenGL canvas initialization failed with the following error.\n" + msg_txt)
  8425. msg = '[ERROR_NOTCL] %s' % _("An internal error has occurred. See shell.\n")
  8426. msg += _("OpenGL canvas initialization failed. HW or HW configuration not supported."
  8427. "Change the graphic engine to Legacy(2D) in Edit -> Preferences -> General tab.\n\n")
  8428. msg += msg_txt
  8429. self.inform.emit(msg)
  8430. return 'fail'
  8431. # So it can receive key presses
  8432. self.plotcanvas.native.setFocus()
  8433. if self.is_legacy is False:
  8434. pan_button = 2 if self.defaults["global_pan_button"] == '2' else 3
  8435. # Set the mouse button for panning
  8436. self.plotcanvas.view.camera.pan_button_setting = pan_button
  8437. self.mm = self.plotcanvas.graph_event_connect('mouse_move', self.on_mouse_move_over_plot)
  8438. self.mp = self.plotcanvas.graph_event_connect('mouse_press', self.on_mouse_click_over_plot)
  8439. self.mr = self.plotcanvas.graph_event_connect('mouse_release', self.on_mouse_click_release_over_plot)
  8440. self.mdc = self.plotcanvas.graph_event_connect('mouse_double_click', self.on_mouse_double_click_over_plot)
  8441. # Keys over plot enabled
  8442. self.kp = self.plotcanvas.graph_event_connect('key_press', self.ui.keyPressEvent)
  8443. if self.defaults['global_cursor_type'] == 'small':
  8444. self.app_cursor = self.plotcanvas.new_cursor()
  8445. else:
  8446. self.app_cursor = self.plotcanvas.new_cursor(big=True)
  8447. if self.ui.grid_snap_btn.isChecked():
  8448. self.app_cursor.enabled = True
  8449. else:
  8450. self.app_cursor.enabled = False
  8451. if self.is_legacy is False:
  8452. self.hover_shapes = ShapeCollection(parent=self.plotcanvas.view.scene, layers=1)
  8453. else:
  8454. # will use the default Matplotlib axes
  8455. self.hover_shapes = ShapeCollectionLegacy(obj=self, app=self, name='hover')
  8456. def on_zoom_fit(self, event):
  8457. """
  8458. Callback for zoom-fit request. This can be either from the corresponding
  8459. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  8460. with axes limits from the geometry bounds of all objects.
  8461. :param event: Ignored.
  8462. :return: None
  8463. """
  8464. if self.is_legacy is False:
  8465. self.plotcanvas.fit_view()
  8466. else:
  8467. xmin, ymin, xmax, ymax = self.collection.get_bounds()
  8468. width = xmax - xmin
  8469. height = ymax - ymin
  8470. xmin -= 0.05 * width
  8471. xmax += 0.05 * width
  8472. ymin -= 0.05 * height
  8473. ymax += 0.05 * height
  8474. self.plotcanvas.adjust_axes(xmin, ymin, xmax, ymax)
  8475. def on_zoom_in(self):
  8476. """
  8477. Callback for zoom-in request.
  8478. :return:
  8479. """
  8480. self.plotcanvas.zoom(1 / float(self.defaults['global_zoom_ratio']))
  8481. def on_zoom_out(self):
  8482. """
  8483. Callback for zoom-out request.
  8484. :return:
  8485. """
  8486. self.plotcanvas.zoom(float(self.defaults['global_zoom_ratio']))
  8487. def disable_all_plots(self):
  8488. self.report_usage("disable_all_plots()")
  8489. self.disable_plots(self.collection.get_list())
  8490. self.inform.emit('[success] %s' %
  8491. _("All plots disabled."))
  8492. def disable_other_plots(self):
  8493. self.report_usage("disable_other_plots()")
  8494. self.disable_plots(self.collection.get_non_selected())
  8495. self.inform.emit('[success] %s' %
  8496. _("All non selected plots disabled."))
  8497. def enable_all_plots(self):
  8498. self.report_usage("enable_all_plots()")
  8499. self.enable_plots(self.collection.get_list())
  8500. self.inform.emit('[success] %s' %
  8501. _("All plots enabled."))
  8502. def on_enable_sel_plots(self):
  8503. log.debug("App.on_enable_sel_plot()")
  8504. object_list = self.collection.get_selected()
  8505. self.enable_plots(objects=object_list)
  8506. self.inform.emit('[success] %s' % _("Selected plots enabled..."))
  8507. def on_disable_sel_plots(self):
  8508. log.debug("App.on_disable_sel_plot()")
  8509. # self.inform.emit(_("Disabling plots ..."))
  8510. object_list = self.collection.get_selected()
  8511. self.disable_plots(objects=object_list)
  8512. self.inform.emit('[success] %s' % _("Selected plots disabled..."))
  8513. def enable_plots(self, objects):
  8514. """
  8515. Enable plots
  8516. :param objects: list of Objects to be enabled
  8517. :return:
  8518. """
  8519. log.debug("Enabling plots ...")
  8520. # self.inform.emit(_("Working ..."))
  8521. for obj in objects:
  8522. if obj.options['plot'] is False:
  8523. obj.options.set_change_callback(lambda x: None)
  8524. obj.options['plot'] = True
  8525. try:
  8526. # only the Gerber obj has on_plot_cb_click() method
  8527. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  8528. # disable this cb while disconnected,
  8529. # in case the operation takes time the user is not allowed to change it
  8530. obj.ui.plot_cb.setDisabled(True)
  8531. except AttributeError:
  8532. pass
  8533. obj.set_form_item("plot")
  8534. try:
  8535. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  8536. obj.ui.plot_cb.setDisabled(False)
  8537. except AttributeError:
  8538. pass
  8539. obj.options.set_change_callback(obj.on_options_change)
  8540. def worker_task(objs):
  8541. with self.proc_container.new(_("Enabling plots ...")):
  8542. for plot_obj in objs:
  8543. # obj.options['plot'] = True
  8544. if isinstance(plot_obj, CNCJobObject):
  8545. plot_obj.plot(visible=True, kind=self.defaults["cncjob_plot_kind"])
  8546. else:
  8547. plot_obj.plot(visible=True)
  8548. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8549. # self.plots_updated.emit()
  8550. def disable_plots(self, objects):
  8551. """
  8552. Disables plots
  8553. :param objects: list of Objects to be disabled
  8554. :return:
  8555. """
  8556. # if no objects selected then do nothing
  8557. if not self.collection.get_selected():
  8558. return
  8559. log.debug("Disabling plots ...")
  8560. # self.inform.emit(_("Working ..."))
  8561. for obj in objects:
  8562. if obj.options['plot'] is True:
  8563. obj.options.set_change_callback(lambda x: None)
  8564. obj.options['plot'] = False
  8565. try:
  8566. # only the Gerber obj has on_plot_cb_click() method
  8567. obj.ui.plot_cb.stateChanged.disconnect(obj.on_plot_cb_click)
  8568. obj.ui.plot_cb.setDisabled(True)
  8569. except AttributeError:
  8570. pass
  8571. obj.set_form_item("plot")
  8572. try:
  8573. obj.ui.plot_cb.stateChanged.connect(obj.on_plot_cb_click)
  8574. obj.ui.plot_cb.setDisabled(False)
  8575. except AttributeError:
  8576. pass
  8577. obj.options.set_change_callback(obj.on_options_change)
  8578. try:
  8579. self.delete_selection_shape()
  8580. except Exception as e:
  8581. log.debug("App.disable_plots() --> %s" % str(e))
  8582. # self.plots_updated.emit()
  8583. def worker_task(objs):
  8584. with self.proc_container.new(_("Disabling plots ...")):
  8585. for plot_obj in objs:
  8586. # obj.options['plot'] = True
  8587. if isinstance(plot_obj, CNCJobObject):
  8588. plot_obj.plot(visible=False, kind=self.defaults["cncjob_plot_kind"])
  8589. else:
  8590. plot_obj.plot(visible=False)
  8591. self.worker_task.emit({'fcn': worker_task, 'params': [objects]})
  8592. def toggle_plots(self, objects):
  8593. """
  8594. Toggle plots visibility
  8595. :param objects: list of Objects for which to be toggled the visibility
  8596. :return: None
  8597. """
  8598. # if no objects selected then do nothing
  8599. if not self.collection.get_selected():
  8600. return
  8601. log.debug("Toggling plots ...")
  8602. self.inform.emit(_("Working ..."))
  8603. for obj in objects:
  8604. if obj.options['plot'] is False:
  8605. obj.options['plot'] = True
  8606. else:
  8607. obj.options['plot'] = False
  8608. self.plots_updated.emit()
  8609. def clear_plots(self):
  8610. """
  8611. Clear the plots
  8612. :return: None
  8613. """
  8614. objects = self.collection.get_list()
  8615. for obj in objects:
  8616. obj.clear(obj == objects[-1])
  8617. # Clear pool to free memory
  8618. self.clear_pool()
  8619. def on_set_color_action_triggered(self):
  8620. """
  8621. This slot gets called by clicking on the menu entry in the Set Color submenu of the context menu in Project Tab
  8622. :return:
  8623. """
  8624. new_color = self.defaults['gerber_plot_fill']
  8625. clicked_action = self.sender()
  8626. assert isinstance(clicked_action, QAction), "Expected a QAction, got %s" % type(clicked_action)
  8627. act_name = clicked_action.text()
  8628. sel_obj_list = self.collection.get_selected()
  8629. if not sel_obj_list:
  8630. return
  8631. # a default value, I just chose this one
  8632. alpha_level = 'BF'
  8633. for sel_obj in sel_obj_list:
  8634. if sel_obj.kind == 'excellon':
  8635. alpha_level = str(hex(
  8636. self.ui.excellon_defaults_form.excellon_gen_group.color_alpha_slider.value())[2:])
  8637. elif sel_obj.kind == 'gerber':
  8638. alpha_level = str(hex(self.ui.gerber_defaults_form.gerber_gen_group.pf_color_alpha_slider.value())[2:])
  8639. elif sel_obj.kind == 'geometry':
  8640. alpha_level = 'FF'
  8641. else:
  8642. log.debug(
  8643. "App.on_set_color_action_triggered() --> Default alpfa for this object type not supported yet")
  8644. continue
  8645. sel_obj.alpha_level = alpha_level
  8646. if act_name == _('Red'):
  8647. new_color = '#FF0000' + alpha_level
  8648. if act_name == _('Blue'):
  8649. new_color = '#0000FF' + alpha_level
  8650. if act_name == _('Yellow'):
  8651. new_color = '#FFDF00' + alpha_level
  8652. if act_name == _('Green'):
  8653. new_color = '#00FF00' + alpha_level
  8654. if act_name == _('Purple'):
  8655. new_color = '#FF00FF' + alpha_level
  8656. if act_name == _('Brown'):
  8657. new_color = '#A52A2A' + alpha_level
  8658. if act_name == _('White'):
  8659. new_color = '#FFFFFF' + alpha_level
  8660. if act_name == _('Black'):
  8661. new_color = '#000000' + alpha_level
  8662. if act_name == _('Custom'):
  8663. new_color = QtGui.QColor(self.defaults['gerber_plot_fill'][:7])
  8664. c_dialog = QtWidgets.QColorDialog()
  8665. plot_fill_color = c_dialog.getColor(initial=new_color)
  8666. if plot_fill_color.isValid() is False:
  8667. return
  8668. new_color = str(plot_fill_color.name()) + alpha_level
  8669. if act_name == _("Default"):
  8670. for sel_obj in sel_obj_list:
  8671. if sel_obj.kind == 'excellon':
  8672. new_color = self.defaults['excellon_plot_fill']
  8673. new_line_color = self.defaults['excellon_plot_line']
  8674. elif sel_obj.kind == 'gerber':
  8675. new_color = self.defaults['gerber_plot_fill']
  8676. new_line_color = self.defaults['gerber_plot_line']
  8677. elif sel_obj.kind == 'geometry':
  8678. new_color = self.defaults['geometry_plot_line']
  8679. new_line_color = self.defaults['geometry_plot_line']
  8680. else:
  8681. log.debug(
  8682. "App.on_set_color_action_triggered() --> Default color for this object type not supported yet")
  8683. continue
  8684. sel_obj.fill_color = new_color
  8685. sel_obj.outline_color = new_line_color
  8686. sel_obj.shapes.redraw(
  8687. update_colors=(new_color, new_line_color)
  8688. )
  8689. return
  8690. if act_name == _("Opacity"):
  8691. alpha_level, ok_button = QtWidgets.QInputDialog.getInt(
  8692. self.ui, _("Set alpha level ..."), '%s:' % _("Value"), min=0, max=255, step=1, value=191)
  8693. if ok_button:
  8694. alpha_str = str(hex(alpha_level)[2:]) if alpha_level != 0 else '00'
  8695. for sel_obj in sel_obj_list:
  8696. sel_obj.fill_color = sel_obj.fill_color[:-2] + alpha_str
  8697. sel_obj.shapes.redraw(
  8698. update_colors=(sel_obj.fill_color, sel_obj.outline_color)
  8699. )
  8700. return
  8701. new_line_color = color_variant(new_color[:7], 0.7)
  8702. if act_name == _("White"):
  8703. new_line_color = color_variant("#dedede", 0.7)
  8704. for sel_obj in sel_obj_list:
  8705. sel_obj.fill_color = new_color
  8706. sel_obj.outline_color = new_line_color
  8707. sel_obj.shapes.redraw(
  8708. update_colors=(new_color, new_line_color)
  8709. )
  8710. def on_grid_snap_triggered(self, state):
  8711. """
  8712. :param state: A parameter with the state of the grid, boolean
  8713. :return:
  8714. """
  8715. if state:
  8716. self.ui.snap_infobar_label.setPixmap(QtGui.QPixmap(self.resource_location + '/snap_filled_16.png'))
  8717. else:
  8718. self.ui.snap_infobar_label.setPixmap(QtGui.QPixmap(self.resource_location + '/snap_16.png'))
  8719. self.ui.snap_infobar_label.clicked_state = state
  8720. def on_grid_icon_snap_clicked(self):
  8721. """
  8722. Slot called by clicking a GUI element, in this case a FCLabel
  8723. :return:
  8724. """
  8725. if isinstance(self.sender(), FCLabel):
  8726. self.ui.grid_snap_btn.trigger()
  8727. def generate_cnc_job(self, objects):
  8728. """
  8729. Slot that will be called by clicking an entry in the contextual menu generated in the Project Tab tree
  8730. :param objects: Selected objects in the Project Tab
  8731. :return:
  8732. """
  8733. self.report_usage("generate_cnc_job()")
  8734. # for obj in objects:
  8735. # obj.generatecncjob()
  8736. for obj in objects:
  8737. obj.on_generatecnc_button_click()
  8738. def save_project(self, filename, quit_action=False, silent=False):
  8739. """
  8740. Saves the current project to the specified file.
  8741. :param filename: Name of the file in which to save.
  8742. :type filename: str
  8743. :param quit_action: if the project saving will be followed by an app quit; boolean
  8744. :param silent: if True will not display status messages
  8745. :return: None
  8746. """
  8747. self.log.debug("save_project()")
  8748. self.save_in_progress = True
  8749. with self.proc_container.new(_("Saving FlatCAM Project")):
  8750. # Capture the latest changes
  8751. # Current object
  8752. try:
  8753. current_object = self.collection.get_active()
  8754. if current_object:
  8755. current_object.read_form()
  8756. except Exception as e:
  8757. self.log.debug("save_project() --> There was no active object. Skipping read_form. %s" % str(e))
  8758. pass
  8759. # Serialize the whole project
  8760. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  8761. "options": self.options,
  8762. "version": self.version}
  8763. if self.defaults["global_save_compressed"] is True:
  8764. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  8765. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  8766. # # Write
  8767. f.write(g)
  8768. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8769. else:
  8770. # Open file
  8771. try:
  8772. f = open(filename, 'w')
  8773. except IOError:
  8774. App.log.error("Failed to open file for saving: %s", filename)
  8775. self.inform.emit('[ERROR_NOTCL] %s' % _("The object is used by another application."))
  8776. return
  8777. # Write
  8778. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  8779. f.close()
  8780. # verification of the saved project
  8781. # Open and parse
  8782. try:
  8783. saved_f = open(filename, 'r')
  8784. except IOError:
  8785. if silent is False:
  8786. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8787. (_("Failed to verify project file"), filename, _("Retry to save it.")))
  8788. return
  8789. try:
  8790. saved_d = json.load(saved_f, object_hook=dict2obj)
  8791. except Exception:
  8792. if silent is False:
  8793. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8794. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8795. f.close()
  8796. return
  8797. saved_f.close()
  8798. if silent is False:
  8799. if 'version' in saved_d:
  8800. self.inform.emit('[success] %s: %s' % (_("Project saved to"), filename))
  8801. else:
  8802. self.inform.emit('[ERROR_NOTCL] %s: %s %s' %
  8803. (_("Failed to parse saved project file"), filename, _("Retry to save it.")))
  8804. tb_settings = QSettings("Open Source", "FlatCAM")
  8805. lock_state = self.ui.lock_action.isChecked()
  8806. tb_settings.setValue('toolbar_lock', lock_state)
  8807. # This will write the setting to the platform specific storage.
  8808. del tb_settings
  8809. # if quit:
  8810. # t = threading.Thread(target=lambda: self.check_project_file_size(1, filename=filename))
  8811. # t.start()
  8812. self.start_delayed_quit(delay=500, filename=filename, should_quit=quit_action)
  8813. def start_delayed_quit(self, delay, filename, should_quit=None):
  8814. """
  8815. :param delay: period of checking if project file size is more than zero; in seconds
  8816. :param filename: the name of the project file to be checked periodically for size more than zero
  8817. :param should_quit: if the task finished will be followed by an app quit; boolean
  8818. :return:
  8819. """
  8820. to_quit = should_quit
  8821. self.save_timer = QtCore.QTimer()
  8822. self.save_timer.setInterval(delay)
  8823. self.save_timer.timeout.connect(lambda: self.check_project_file_size(filename=filename, should_quit=to_quit))
  8824. self.save_timer.start()
  8825. def check_project_file_size(self, filename, should_quit=None):
  8826. """
  8827. :param filename: the name of the project file to be checked periodically for size more than zero
  8828. :param should_quit: will quit the app if True; boolean
  8829. :return:
  8830. """
  8831. try:
  8832. if os.stat(filename).st_size > 0:
  8833. self.save_in_progress = False
  8834. self.save_timer.stop()
  8835. if should_quit:
  8836. self.app_quit.emit()
  8837. except Exception:
  8838. traceback.print_exc()
  8839. def save_project_auto(self):
  8840. """
  8841. Called periodically to save the project.
  8842. It will save if there is no block on the save, if the project was saved at least once and if there is no save in
  8843. # progress.
  8844. :return:
  8845. """
  8846. if self.block_autosave is False and self.should_we_save is True and self.save_in_progress is False:
  8847. self.on_file_saveproject()
  8848. def save_project_auto_update(self):
  8849. """
  8850. Update the auto save time interval value.
  8851. :return:
  8852. """
  8853. log.debug("App.save_project_auto_update() --> updated the interval timeout.")
  8854. try:
  8855. if self.autosave_timer.isActive():
  8856. self.autosave_timer.stop()
  8857. except Exception:
  8858. pass
  8859. if self.defaults['global_autosave'] is True:
  8860. self.autosave_timer.setInterval(int(self.defaults['global_autosave_timeout']))
  8861. self.autosave_timer.start()
  8862. def on_plotarea_tab_closed(self, tab_idx):
  8863. """
  8864. :param tab_idx: Index of the Tab from the plotarea that was closed
  8865. :return:
  8866. """
  8867. widget = self.ui.plot_tab_area.widget(tab_idx)
  8868. if widget is not None:
  8869. widget.deleteLater()
  8870. self.ui.plot_tab_area.removeTab(tab_idx)
  8871. def on_options_app2project(self):
  8872. """
  8873. Callback for Options->Transfer Options->App=>Project. Copies options
  8874. from application defaults to project defaults.
  8875. :return: None
  8876. """
  8877. self.report_usage("on_options_app2project")
  8878. self.preferencesUiManager.defaults_read_form()
  8879. self.options.update(self.defaults)
  8880. # self.options_write_form()
  8881. def toggle_shell(self):
  8882. """
  8883. Toggle shell: if is visible close it, if it is closed then open it
  8884. :return: None
  8885. """
  8886. self.report_usage("toggle_shell()")
  8887. if self.ui.shell_dock.isVisible():
  8888. self.ui.shell_dock.hide()
  8889. self.plotcanvas.native.setFocus()
  8890. else:
  8891. self.ui.shell_dock.show()
  8892. # I want to take the focus and give it to the Tcl Shell when the Tcl Shell is run
  8893. # self.shell._edit.setFocus()
  8894. QtCore.QTimer.singleShot(0, lambda: self.ui.shell_dock.widget()._edit.setFocus())
  8895. # HACK - simulate a mouse click - alternative
  8896. # no_km = QtCore.Qt.KeyboardModifier(QtCore.Qt.NoModifier) # no KB modifier
  8897. # pos = QtCore.QPoint((self.shell._edit.width() - 40), (self.shell._edit.height() - 2))
  8898. # e = QtGui.QMouseEvent(QtCore.QEvent.MouseButtonPress, pos, QtCore.Qt.LeftButton, QtCore.Qt.LeftButton,
  8899. # no_km)
  8900. # QtWidgets.qApp.sendEvent(self.shell._edit, e)
  8901. # f = QtGui.QMouseEvent(QtCore.QEvent.MouseButtonRelease, pos, QtCore.Qt.LeftButton, QtCore.Qt.LeftButton,
  8902. # no_km)
  8903. # QtWidgets.qApp.sendEvent(self.shell._edit, f)
  8904. def on_toggle_shell_from_settings(self, state):
  8905. """
  8906. Toggle shell: if is visible close it, if it is closed then open it
  8907. :return: None
  8908. """
  8909. self.report_usage("on_toggle_shell_from_settings()")
  8910. if state is True:
  8911. if not self.ui.shell_dock.isVisible():
  8912. self.ui.shell_dock.show()
  8913. else:
  8914. if self.ui.shell_dock.isVisible():
  8915. self.ui.shell_dock.hide()
  8916. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  8917. """
  8918. Shows a message on the FlatCAM Shell
  8919. :param msg: Message to display.
  8920. :param show: Opens the shell.
  8921. :param error: Shows the message as an error.
  8922. :param warning: Shows the message as an warning.
  8923. :param success: Shows the message as an success.
  8924. :param selected: Indicate that something was selected on canvas
  8925. :return: None
  8926. """
  8927. if show:
  8928. self.ui.shell_dock.show()
  8929. try:
  8930. if error:
  8931. self.shell.append_error(msg + "\n")
  8932. elif warning:
  8933. self.shell.append_warning(msg + "\n")
  8934. elif success:
  8935. self.shell.append_success(msg + "\n")
  8936. elif selected:
  8937. self.shell.append_selected(msg + "\n")
  8938. else:
  8939. self.shell.append_output(msg + "\n")
  8940. except AttributeError:
  8941. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  8942. class ArgsThread(QtCore.QObject):
  8943. open_signal = pyqtSignal(list)
  8944. start = pyqtSignal()
  8945. if sys.platform == 'win32':
  8946. address = (r'\\.\pipe\NPtest', 'AF_PIPE')
  8947. else:
  8948. address = ('/tmp/testipc', 'AF_UNIX')
  8949. def __init__(self):
  8950. super(ArgsThread, self).__init__()
  8951. self.listener = None
  8952. self.start.connect(self.run)
  8953. def my_loop(self, address):
  8954. try:
  8955. self.listener = Listener(*address)
  8956. while True:
  8957. conn = self.listener.accept()
  8958. self.serve(conn)
  8959. except socket.error:
  8960. conn = Client(*address)
  8961. conn.send(sys.argv)
  8962. conn.send('close')
  8963. # close the current instance only if there are args
  8964. if len(sys.argv) > 1:
  8965. try:
  8966. self.listener.close()
  8967. except Exception:
  8968. pass
  8969. sys.exit()
  8970. def serve(self, conn):
  8971. while True:
  8972. msg = conn.recv()
  8973. if msg == 'close':
  8974. break
  8975. self.open_signal.emit(msg)
  8976. conn.close()
  8977. # the decorator is a must; without it this technique will not work unless the start signal is connected
  8978. # in the main thread (where this class is instantiated) after the instance is moved o the new thread
  8979. @pyqtSlot()
  8980. def run(self):
  8981. self.my_loop(self.address)
  8982. # end of file